<?php

namespace app\mob\controller;

use think\Request;
use think\Controller;

class Weixin extends Controller
{   
    private $_fromUser;
    private $_toUser;
    private $_msgType;
    private $_content;

    // 微信服务接入时，服务器需授权验证
    public function valid()
    {
        if (isset($_GET['echostr'])) {
            $echoStr = $_GET["echostr"];
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            // valid signature , option
            if($this->checkSignature($signature, $timestamp, $nonce)){
                echo $echoStr;
            }
        }else{
            $this->responseMsg();
        }
    }
    
    // 参数校验
    private function checkSignature($signature, $timestamp, $nonce)
    {
        $token = config("wechat.Token");
        if (!$token) {
            echo 'TOKEN is not defined!';
        }else{
            $tmpArr = array($token, $timestamp, $nonce);
            // use SORT_STRING rule
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode( $tmpArr );
            $tmpStr = sha1( $tmpStr );

            if( $tmpStr == $signature ){
                return true;
            }else{
                return false;
            }
        }
    }

    public function responseMsg()
    {
        $postStr = file_get_contents("php://input");
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

        // init 
        $this->_fromUser = $postObj->ToUserName;   // 开发者微信号
        $this->_toUser = $postObj->FromUserName;    // 用户微信号
        $this->_msgType = $postObj->MsgType;    
        $this->_content = $postObj->Content; // text

        if ( $this->_msgType=='event' && $postObj->Event=='subscribe' ) {  
            $reply = "您好，感谢关注华元一世界[玫瑰][玫瑰][玫瑰] 客服在线时间：上午9:00-11:00，下午3:00-5:00，感谢您的支持与理解！您可回复以下编号获取指定信息：
1. 项目地址
2. 售楼处地址
3. 销售电话";
            $this->_text( $reply, 0 );
            exit;
        }else if ( $this->_msgType=='event' && $postObj->Event=='SCAN' ) {    
            // SCAN：用户已关注时的事件推送
            
        }else if( $this->_msgType=='event' && $postObj->Event=='unsubscribe' ){
            // 取消订阅事件
        }elseif ( $this->_msgType=='event' && $postObj->Event=='CLICK' ){
            // 自定义菜单点击事件
            $eventKey = $postObj->EventKey;
            switch ( $eventKey ) {
                case 'LOUSHU_SXY':
                    $reply = '楼书展示 - 书香苑 - 尽请期待...';
                    $params = [
                        [
                            'title' => '书香苑楼书',
                            'description' => '一世界楼书介绍，华元一世界！',
                            'picurl' => 'http://ysj.imgondar.com/static/img/weather.jpg',
                            'url' => 'http://it.imgondar.com'
                        ]
                    ];
                    $this->_imagetext( $params );
                    break;
                case 'LOUSHU_YSJ':
                    $reply = '楼书展示 - 一世界 - 尽请期待...';
                    $params = [
                        [
                            'title' => '一世界楼书',
                            'description' => '一世界楼书介绍，华元一世界！',
                            'picurl' => 'http://ysj.imgondar.com/static/img/profile-02.jpg',
                            'url' => 'http://it.imgondar.com'
                        ]
                    ];
                    $this->_imagetext( $params );
                    break;
                case 'YSJ_KEFU':
                    $h = date('H', time());
                    if ( ($h>=9&&$h<=11) || ($h>=16&&$h<=17) ) {
                        $reply = '您好，很高兴为您服务，有什么可以帮助您的吗？';
                    }else{
                        $reply = '客服在线时间：上午9:00-11:00，下午3:00-5:00，感谢您的支持与理解！您可回复以下编号获取指定信息：
1. 项目地址
2. 售楼处地址
3. 销售电话';
                    }
                    $this->_text( $reply, 0 );
                    break;
                default:
                    $msg = "楼书展示 - 尽请期待...";
                    $this->_text( $msg, 0 );
                    break;
            }
        }else if( $this->_msgType=='text' ){
            // 把消息转发到客服系统：$this->_text2kf();
            $msg = $this->_content;
            if ($msg=='项目地址' || $msg=='1') {
                $reply = "项目地址：沧州市运河区解放西路南侧，开元大道东侧";
            }else if ($msg=='售楼处地址' || $msg=='2') {
                $reply = "售楼处地址：沧州市运河区一世界B座桔子酒店西侧底商华元地产展示中心";
            }else if ($msg=='销售电话' || $msg=='3') {
                $reply = "销售电话：2151111/2222";
            }else{
                $reply = "感谢关注华元一世界[玫瑰][玫瑰][玫瑰] 客服在线时间：上午9:00-11:00，下午3:00-5:00，感谢您的支持与理解！您可回复以下编号获取指定信息：
1. 项目地址
2. 售楼处地址
3. 销售电话";
            }
            $this->_text( $reply, 0 );
            exit;
        }else {
            // 接受用户发布的消息
            echo "";
            exit;
        }
    }

    /**
     * 发送文本消息
     * @param  [type]  $reply [description]
     * @param  integer $flag  [description]
     * @return [type]         [description]
     */
    private function _text( $reply, $flag=0 ){     // flag=0 默认不标星 
        $textTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                <FuncFlag>%s</FuncFlag>
                </xml>";             
        $resultStr = sprintf( $textTpl, $this->_toUser, $this->_fromUser, time(), 'text', $reply, $flag );
        echo $resultStr;
    }

     /**
     * 转发文本消息给客服
     * @param  [type]  $reply [description]
     * @param  integer $flag  [description]
     * @return [type]         [description]
     */
    private function _text2kf(){     // flag=0 默认不标星 
        $textTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[transfer_customer_service]]></MsgType>
                </xml>";             
        $resultStr = sprintf( $textTpl, $this->_toUser, $this->_fromUser, time() );
        echo $resultStr;
    }

    /**
     * 发送图文消息
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    private function _image( $media_id ){    // 最多可发10条图文消息  $i<=10  $params 是数组参数
         $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Image>
                        <MediaId><![CDATA[%s]]></MediaId>
                        </Image>
                    </xml>";             
        $resultStr = sprintf( $textTpl, $this->_toUser, $this->_fromUser, time(), 'image', $media_id );
        echo $resultStr;
    }

    /**
     * 发送图文消息 - 最多发5条图文
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    private function _imagetext( $params ){    // 最多可发10条图文消息  $i<=10  $params 是数组参数
        $MsgType = 'news';
        $time = time();
        $i = count( $params );
        $i = $i>5 ? 5 : $i;
        $head = "<xml>
                 <ToUserName><![CDATA[$this->_toUser]]></ToUserName>
                 <FromUserName><![CDATA[$this->_fromUser]]></FromUserName>
                 <CreateTime>$time</CreateTime>
                 <MsgType><![CDATA[$MsgType]]></MsgType>
                 <ArticleCount>$i</ArticleCount>
                 <Articles>";
        $end = "</Articles>
                 <FuncFlag>0</FuncFlag> 
                </xml>";
        $middle = "<item>
                     <Title><![CDATA[%s]]></Title> 
                     <Description><![CDATA[%s]]></Description>
                     <PicUrl><![CDATA[%s]]></PicUrl>
                     <Url><![CDATA[%s]]></Url>
                 </item>";

        for ($j=0; $j<$i ; $j++) { 
            $head.=sprintf( $middle, $params[$j]['title'], $params[$j]['description'], $params[$j]['picurl'], $params[$j]['url'] );
        }
        $head.=$end;
        echo $head;
    }

    private function https_curl_post($url='', $postdata='', $options=array()){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        if (!empty($options)){
            curl_setopt_array($ch, $options);
        }
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}
