<?php
/**
 * 微信功能模块响应微信调用模块
 * 继承controller模块
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2019-07-17 $
 */
namespace app\weixin\controller;
use think\Controller;
class Serverrequest extends Controller{

    /**
     * crm调mc  socke 的客户端
     *
     * @param  max_msg_id    最大消息ID
     * @param  app_id        微信appid
     *
     * @author lilong<lilong@suxuantech.cn>
     */
    public function socketClient($param){
        // error_reporting(E_ALL);
        set_time_limit(0);
        $port = 7159;
        $ip = "127.0.0.1";
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($socket < 0) {
            // socket 创建socket 连接失败
            // echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";die;
        }
        // 创建 ip 端口 的socket连接
        $result = socket_connect($socket, $ip, $port);
        if ($result < 0) {
            // 创建 ip 端口 的socket连接 
            // echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";die;
        }
        $socketData['max_msg_id'] = (int)$param['max_msg_id'];
        $socketData['app_id'] = trim($param['app_id']);
        $in = json_encode($socketData);
        // 发送
        if(!socket_write($socket, $in, strlen($in))) {
            // 发送socket失败
            // echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";die;
        }
        // 接收返回的消息
        while($out = socket_read($socket, 8192)) {
            return $out;
            // echo "接收服务器回传信息成功！\n";
            // echo "接受的内容为:",$out;
        }

    }

    //------------------------------ 微信会话机制调整，将server放到mc上以下代码没用了  开始 ------------------------------//
    /**
     * 微信配置的通知服务url就配置index的访问地址
     * @return [type] [description]
     */
    public function wxrequest(){
        define("TOKEN", config('WX_MSG_TOKEN'));//定义识别码
        textlog('jinru');
        //获得参数 signature nonce token timestamp echostr
        $nonce     = $_GET['nonce'];
        $token     = config('WX_MSG_TOKEN');
        $timestamp = $_GET['timestamp'];
        $echostr   = $_GET['echostr'];
        $signature = $_GET['signature'];
        textlog(date('Y-m-d H:i:s',time()));
        textlog("nonce--".$nonce);
        textlog("Token--".$token);
        textlog("timestamp--".$timestamp);
        textlog("echostr--".$echostr);
        textlog("signature--".$signature);

        //形成数组，然后按字典序排序
        $array = array($nonce, $timestamp, $token);
        sort($array);

        //拼接成字符串,sha1加密 ，然后与signature进行校验
        $str = sha1( implode( $array ) );
        textlog("加密后".$str);
        if( $str == $signature && $echostr ){
            //第一次接入weixin api接口的时候
            textlog("验证成功");
            echo  $echostr;
            exit;
        }else{
            $postStr = file_get_contents("php://input");//接收用户输入的信息
            //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//接收用户输入的信息
            //$brandid = (int)input('brandid');
            if (!empty($postStr)){
                libxml_disable_entity_loader(true);//防止文件泄漏
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;//发送方帐号（一个OpenID）
                $toUsername = $postObj->ToUserName;//接收方账号
                $msgType = $postObj->MsgType;//消息类型
                if ($msgType=='image') {
                    $picUrl = trim($postObj->PicUrl);
                    $mediaId = trim($postObj->MediaId);
                    $imgTyep = 'jpg';
                }else if ($msgType=='voice') {
                    $format = trim($postObj->Format);//语音格式：amr
                    $mediaId = trim($postObj->MediaId);
                }else if ($msgType=='text') {
                    $keywords = trim($postObj->Content);//消息内容
                }
                $MsgId = $postObj->MsgId;// 消息id，64位整型 关于重试的消息排重，推荐使用msgid排重。
                $Event = $postObj->Event;//事件
                $EventKey = $postObj->EventKey;//二维码参数

                $Latitude = $postObj->Latitude;//地理位置纬度
                $Longitude = $postObj->Longitude;//地理位置经度
                $Precision = $postObj->Precision;//地理位置精度
                $time = time();
                textlog("msgType:".$msgType);
                textlog("fromUsername:".$fromUsername);
            }
            $staff_id = db_config('wx_talk_remind_staffids');
            $mc = new \app\common\lib\mcInterface();
            $staffinfo = $mc->getStaffByIds($staff_id);
            $openid = $fromUsername['0'];
            if($Event){
                // 关注 或者 扫码
                if($Event=='subscribe' || $Event=='SCAN'){
                    textlog('关注');
                    textlog($Event.'=='.$EventKey);
                    $mc = new \app\common\lib\mcInterface();
                    $wx = db('crm_s_wx_system')->select();
                    foreach($wx as $k=>$v){
                        $access_token = $mc->getAccessToken($v['appid'],$v['secret'],0);
                        if ($access_token) {
                            textlog('获取token');
                            // 自动回复  auto_type=3
                            $autoRule = db('crm_s_wx_auto_answer')->where('wxsys_id',$v['id'])->where('auto_type', 3)->find();
                            $contents = json_decode($autoRule['contents'], true);
                            $wxParam['openid']  = $openid;
                            $wxParam['content'] = $contents['content'];
                            $wxParam['fromUsername'] = $fromUsername;
                            $wxParam['toUsername'] = $toUsername;
                            $wxParam['time'] = time();
                            // textlog('自动回复参数'.json_encode($wxParam));
                            // 回复类型为 文本
                            if ($contents['type']=='text') {
                                textlog('进入自动回复文本消息');
                                $wxParam['type'] = 'text';
                                $this->sendWxMsg($wxParam);
                            }
                            // 回复类型为 图片
                            else if ($contents['type']=='img') {
                                $wxParam['type'] = 'img';
                                $this->sendWxMsg($wxParam);
                            }
                            // 回复类型为 图文消息
                            else if ($contents['type']=='news') {
                                $wxParam['news_info'] = $contents['news_info'];
                                $wxParam['type'] = 'news';
                                $this->sendWxMsg($wxParam);
                            }
                            // 回复类型为 语音
                            else if ($contents['type']=='voice') {
                                $wxParam['type'] = 'voice';
                                $this->sendWxMsg($wxParam);
                            }
                            // 回复类型为 视频
                            else if ($contents['type']=='video') {
                                $wxParam['type'] = 'video';
                                $this->sendWxMsg($wxParam);
                            }

                            $getUInfoUrl = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
                            $uInfo = http_request($getUInfoUrl,'GET');
                            $info = json_decode($uInfo['response'],true);
                            if($info['errcode'] > 0){
                                textlog('获取用户的基本信息失败【openid：'.$openid.'；错误信息：'.$uInfo.'】');
                            }else{
                                // 用户已经关注
                                if ($info['subscribe'] == 1) {
                                    $rid = db('crm_s_wx_relation')->where('openid',$info['openid'])->value('id');
                                    if ($rid) {
                                        $upData['subscribe']     = $info['subscribe'];
                                        $upData['nickname']      = $info['nickname'];
                                        $upData['sex']           = $info['sex'];
                                        $upData['language']      = $info['language'];
                                        $upData['headimgurl']    = $info['headimgurl'];
                                        $upData['subscribe_time']= $info['subscribe_time'];
                                        $upData['unionid']       = $info['unionid'];
                                        $upData['remark']        = $info['remark'];
                                        $upData['wx_sys_id']     = $v['id'];
                                    }else{
                                        $inData['subscribe']     = $info['subscribe'];
                                        $inData['openid']        = $info['openid'];
                                        $inData['nickname']      = $info['nickname'];
                                        $inData['sex']           = $info['sex'];
                                        $inData['language']      = $info['language'];
                                        $inData['headimgurl']    = $info['headimgurl'];
                                        $inData['subscribe_time']= $info['subscribe_time'];
                                        $inData['unionid']       = $info['unionid'];
                                        $inData['remark']        = $info['remark'];
                                        $inData['wx_sys_id']     = $v['id'];
                                    }
                                    
                                    db()->startTrans();
                                    try {
                                        if ($upData) {
                                            db('crm_s_wx_relation')->where('id',$rid)->update($upData);
                                            $inRcdata['rid'] = $rid;
                                        }else{
                                            $inRes = db('crm_s_wx_relation')->insertGetId($inData);
                                            $inRcdata['rid'] = $inRes;
                                        }
                                        if ($Event=='subscribe') {
                                            $key = substr($EventKey,8);
                                            $key = explode(',', $key);
                                            // 渠道
                                            $inRcdata['channel_id'] = $key[0];
                                            $inRcdata['channel_name'] = db('crm_s_channel')->where('id', $inRcdata['channel_id'])->value('channel_name');
                                            // 关键字
                                            $inRcdata['keywords'] = db('crm_s_channel_keywords')->where('id', $key[1])->value('keyword');
                                        }else if ($Event=='SCAN') {
                                            $key = explode(',',$EventKey);
                                            textlog('key：'.json_encode($key));
                                            $inRcdata['channel_id'] = $key[0];
                                            $inRcdata['channel_name'] = db('crm_s_channel')->where('id', $inRcdata['channel_id'])->value('channel_name');
                                            // 关键字
                                            $inRcdata['keywords'] = db('crm_s_channel_keywords')->where('id', $key[1])->value('keyword');
                                        }
                                        $inRcdata['create_time'] = date('Y-m-d H:i:s',time());
                                        textlog('inData：'.json_encode($inRcdata));
                                        db('crm_s_wx_rchannel')->insert($inRcdata);
                                        db()->commit();
                                    } catch (\Exception $e) {
                                        db()->rollback();
                                        textlog('保存用户信息失败，ERROR：'.$e->getMessage());
                                    }
                                    // 给设定的管理员发送消息 （弹窗，带上会话列表的链接）
                                    foreach($staffinfo as $key=>$val){
                                        $msg = '已有新用户关注，请前去分配，<a href="/weixin/weixin/wxTalkList" target="_blank" style="color: red;">点击前去</a>';
                                        $message['send_type']      = 1;
                                        $message['send_title']     = '会话提醒';
                                        $message['send_msg']       = $msg;
                                        $message['customer_id']    = 0;
                                        $message['receive_id']     = $val['id'];
                                        $message['receive_name']   = $val['staffname'];
                                        $message['receive_status'] = 0;
                                        $message['operation_type'] = 2;
                                        $message['operation']      = [];
                                        $message['time_out']       = 240;
                                        sendSystemMessage($message);
                                    }
                                }
                            }
                        }
                    }
                }
                // 取消关注
                else if ($Event=='unsubscribe') {
                    $res = db('crm_s_wx_relation')->where('openid',$openid)->find();
                    if ($res) {
                        $update['subscribe'] = 0;
                        $update['subscribe_time'] = time();
                        db('crm_s_wx_relation')->where('id',$res['id'])->update($update);
                    }
                }
                // 菜单点击事件
                else if ($Event=='CLICK') {
                    textlog("Event==>".$EventKey);
                    $content = db('crm_s_wx_menu')->where('menu_code',$EventKey)->where('status',1)->value('url');
                    // textlog("EventSql==>".db()->getLastSql());
                    if ($content) {
                        $wxParam['openid']  = $openid;
                        $wxParam['content'] = $content;
                        $wxParam['fromUsername'] = $fromUsername;
                        $wxParam['toUsername'] = $toUsername;
                        $wxParam['time'] = time();
                        $wxParam['type'] = 'text';
                        $this->sendWxMsg($wxParam);
                    }
                }
            }
            if ($msgType=='image') {
                $picUrl = trim($postObj->PicUrl);
                $mediaId = trim($postObj->MediaId);
                textlog("picUrl:".$picUrl);
                $imgAddr = ROOT_PATH.'public'.DS.'wx'.DS.'pic'.DS.$fromUsername.DS.date('Ymd');
                $showAddr= DS.'wx'.DS.'pic'.DS.$fromUsername.DS.date('Ymd');
                // $prefix = ROOT_PATH.DS.'public'.DS.'wx'.DS.'pic'.DS.$fromUsername.DS.date('Ymd');
                textlog("imgAddr:".$imgAddr);
                if(!file_exists($imgAddr)){
                    $mkres = @mkdir($imgAddr,0777,true);
                    textlog("mkres:".$mkres);
                    if(!$mkres){
                        return false;
                    }
                }
                $image = file_get_contents($picUrl);
                $putRes = file_put_contents($imgAddr.DS.$MsgId.'.'.$imgTyep, $image);// 返回字节数
                textlog("putres:".$putres);
                if ($putRes) {
                    // 获取用户的基本信息 如果表里没有重新请求微信接口
                    $rInfo = db('crm_s_wx_relation')->where('openid',$fromUsername)->field('id,nickname,headimgurl,remark,kf_id')->find();
                    if ($rInfo) {
                        textlog("inIf");
                        // 如果之前有用户的信息，看看有没有分配客服
                        if ($rInfo['kf_id']) {
                            // 如果有客服id，把这条消息保存下来
                            $inTalk['openid']  = "$openid";
                            $inTalk['opercode']= '2003';
                            $inTalk['text']    = '<img class="showimg" style="width:20%;" src="'.$showAddr.DS.$MsgId.'.'.$imgTyep.'"/>';
                            $inTalk['time']    = date('Y-m-d H:i:s');
                            $inTalk['kf_id']   = $rInfo['kf_id'];
                            /*
                            // 如果有客服id，创建会话  这是个坑，必须用微信后台登录才行
                            $linkUrl = 'https://api.weixin.qq.com/customservice/kfsession/create?access_token='.$access_token;
                            $kf_account = db('crm_s_wx_kf_staff')->where('id',$rInfo['kf_id'])->value('kf_account');
                            $linkPost['kf_account'] = $kf_account;
                            $linkPost['openid'] = $openid;
                            $linkRes = http_request($linkUrl,'POST',json_encode($linkPost));
                            textlog('创建客服会话==》'.$linkRes);
                            */
                            // 根据客服id找到staff_id 给这个员工发弹窗带上会话列表的链接）
                            $sInfo = db('crm_s_wx_kf_staff')->where('id',$rInfo['kf_id'])->find();
                            $msg = '已有用户发来消息，请前去会话，<a href="/weixin/weixin/wxTalkList" target="_blank" style="color: red;">点击前去</a>';
                            $message['send_type']      = 1;
                            $message['send_title']     = '会话提醒';
                            $message['send_msg']       = $msg;
                            $message['customer_id']    = 0;
                            $message['receive_id']     = $sInfo['staff_id'];
                            $message['receive_name']   = $sInfo['staff_name'];
                            $message['receive_status'] = 0;
                            $message['operation_type'] = 2;
                            $message['operation']      = [];
                            $message['time_out']       = 240;
                            sendSystemMessage($message);
                        }else{
                            textlog("inElse");
                            // 如果有客服id，把这条消息保存下来
                            $inTalk['openid']  = "$openid";
                            $inTalk['opercode']= '2003';
                            $inTalk['text']    = '<img src="'.$imgAddr.DS.$MsgId.'.'.$imgTyep.'"/>';
                            $inTalk['time']    = date('Y-m-d H:i:s');
                            /* 
                            // 如果没有对应的客服 将消息转发到客服 在会话界面调接口，获取未接入会话(GET https://api.weixin.qq.com/customservice/kfsession/getwaitcase?access_token=ACCESS_TOKEN) 这就是坑，大坑
                            $itemTpl = "<xml> 
                                   <ToUserName><![CDATA[%s]]></ToUserName>  
                                   <FromUserName><![CDATA[%s]]></FromUserName>  
                                   <CreateTime>%s</CreateTime>  
                                   <MsgType><![CDATA[transfer_customer_service]]></MsgType> 
                                </xml>";
                            $result = sprintf($itemTpl, $fromUsername, $toUsername, $time);
                            //返回消息给微信
                            echo $result;
                            */
                            // 没有kf_id 给设定的管理员发送弹窗带上会话列表的链接）
                            foreach($staffinfo as $key=>$val){
                                $msg = '已有新用户发来消息，请前去分配，<a href="/weixin/weixin/wxTalkList" target="_blank" style="color: red;">点击前去</a>';
                                $message['send_type']      = 1;
                                $message['send_title']     = '会话提醒';
                                $message['send_msg']       = $msg;
                                $message['customer_id']    = 0;
                                $message['receive_id']     = $val['id'];
                                $message['receive_name']   = $val['staffname'];
                                $message['receive_status'] = 0;
                                $message['operation_type'] = 2;
                                $message['operation']      = [];
                                $message['time_out']       = 240;
                                sendSystemMessage($message);
                            }
                        }
                        textlog('保存信息==》'.json_encode($inTalk));
                        try {
                            $talkRes = db('crm_s_wx_talk')->insert($inTalk);

                        } catch (\Exception $e) {
                            textlog('catch==》'.$e->getMessage());
                        }
                        
                        textlog('保存结果==》'.$talkRes);
                        textlog('talkSql==》'.db()->getLastSql());
                        // $sendMsg = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
                        // // textlog("发送的地址==>".$sendMsg);
                        // // textlog("openid==>".$openid);
                        // $post['touser'] = "$openid";
                        // $post['msgtype'] = 'text';
                        // $post['text']['content'] = "Hello World";
                        // $post['customservice']['kf_account'] = 'kf2006@suxuantech';
                        // textlog("发送的内容==>".json_encode($post));
                        // $addRes = http_request($sendMsg,'POST',json_encode($post));
                        // textlog("发送的结果==>".json_encode($addRes));
                    }else{
                        $getUInfoUrl = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
                        $uInfo = http_request($getUInfoUrl,'GET');
                        $info = json_decode($uInfo['response'],true);
                        if($info['errcode'] > 0){
                            textlog('获取用户的基本信息失败【openid：'.$openid.'；错误信息：'.$uInfo.'】');
                        }else{
                            // 用户已经关注
                            if ($info['subscribe'] == 1) {
                                $inData['subscribe']     = $info['subscribe'];
                                $inData['openid']        = $info['openid'];
                                $inData['nickname']      = $info['nickname'];
                                $inData['sex']           = $info['sex'];
                                $inData['language']      = $info['language'];
                                $inData['headimgurl']    = $info['headimgurl'];
                                $inData['subscribe_time']= $info['subscribe_time'];
                                $inData['unionid']       = $info['unionid'];
                                $inData['remark']        = $info['remark'];
                                $inData['wx_sys_id']     = $v['id'];
                                $inRes = db('crm_s_wx_relation')->insert($inData);
                                if (!$inRes) {
                                    textlog('保存用户信息失败，lastSQL：'.db()->getLastSql());
                                }
                                $inTalk['openid']  = $openid;
                                $inTalk['opercode']= '2003';
                                $inTalk['text']    = $keywords;
                                $inTalk['time']    = date('Y-m-d H:i:s');
                                db('crm_s_wx_talk')->insert($inTalk);
                                /*
                                $itemTpl = "<xml> 
                                        <ToUserName><![CDATA[%s]]></ToUserName>  
                                        <FromUserName><![CDATA[%s]]></FromUserName>  
                                        <CreateTime>%s</CreateTime>  
                                        <MsgType><![CDATA[transfer_customer_service]]></MsgType> 
                                    </xml>";
                                $result = sprintf($itemTpl, $fromUsername, $toUsername, $time, $content);
                                //返回消息给微信
                                echo $result;
                                */
                            }
                        }
                    }
                }
            }else if ($msgType=='voice') {
                # code...
            }else if ($msgType=='text') {
                if ($keywords){
                    textlog("消息内容==>".$keywords);
                    $mc = new \app\common\lib\mcInterface();
                    $wx = db('crm_s_wx_system')->select();
                    foreach($wx as $k=>$v){
                        $access_token = $mc->getAccessToken($v['appid'],$v['secret'],0);
                        textlog("access_token==>".$access_token);
                        if($access_token){
                            // 关键词回复
                            $autoRule = db('crm_s_wx_auto_answer')->where('wxsys_id',$v['id'])->where('auto_type',1)->where('keywords','like','%'.$keywords.'%')->select();
                            if ($autoRule) {
                                $matchKey = false;
                                foreach ($autoRule as $key => $value) {
                                    $answer_type = $value['answer_type'];
                                    $ruleKeys = unserialize($value['keywords']);
                                    // textlog('ruleKeys--'.json_encode($ruleKeys));
                                    foreach ($ruleKeys as $k => $v) {
                                        // textlog('rulekye--'.$v['content']);
                                        if ($keywords==$v['content']) {
                                            $matchKey = true;
                                        }else{
                                            if ($v['match_mode']=='contain') {
                                                if (strpos($v['content'],$keywords)!==false) {
                                                    $matchKey = true;
                                                }
                                            }
                                        }
                                    }
                                    // textlog('match--'.$matchKey);
                                    // 匹配上关键词
                                    if ($matchKey) {
                                        $answer = json_decode($value['contents'], true);
                                        // textlog('answer--'.json_encode($answer));
                                        // 回复全部
                                        if ($value['answer_type']=='reply_all') {
                                            foreach ($answer as $k => $v) {
                                                textlog('answerV--'.json_encode($v));
                                                $contents = $v;
                                                $wxParam['openid']  = $openid;
                                                $wxParam['content'] = $contents['content'];
                                                $wxParam['fromUsername'] = $fromUsername;
                                                $wxParam['toUsername'] = $toUsername;
                                                $wxParam['time'] = time();
                                                textlog('wxParam'.json_encode($wxParam));
                                                // 回复类型为 文本
                                                if ($contents['type']=='text') {
                                                    textlog('进入自动回复文本消息');
                                                    $wxParam['type'] = 'text';
                                                    $this->sendWxMsg($wxParam);
                                                }
                                                // 回复类型为 图片
                                                else if ($contents['type']=='img') {
                                                    $wxParam['type'] = 'img';
                                                    $this->sendWxMsg($wxParam);
                                                }
                                                // 回复类型为 图文消息
                                                else if ($contents['type']=='news') {
                                                    $wxParam['news_info'] = $contents['news_info'];
                                                    $wxParam['type'] = 'news';
                                                    $this->sendWxMsg($wxParam);
                                                }
                                                // 回复类型为 语音
                                                else if ($contents['type']=='voice') {
                                                    $wxParam['type'] = 'voice';
                                                    $this->sendWxMsg($wxParam);
                                                }
                                                // 回复类型为 视频
                                                else if ($contents['type']=='video') {
                                                    $wxParam['type'] = 'video';
                                                    $this->sendWxMsg($wxParam);
                                                }
                                            }
                                        }
                                        // 随机回复一条
                                        else if ($value['answer_type']=='random_one') {
                                            $rand = array_rand($answer);
                                            $contents = $answer[$rand];
                                            // textlog('answerC--'.json_encode($contents));
                                            $wxParam['openid']  = $openid;
                                            $wxParam['content'] = $contents['content'];
                                            $wxParam['fromUsername'] = $fromUsername;
                                            $wxParam['toUsername'] = $toUsername;
                                            $wxParam['time'] = time();
                                            // 回复类型为 文本
                                            if ($contents['type']=='text') {
                                                // textlog('进入自动回复文本消息');
                                                $wxParam['type'] = 'text';
                                                $this->sendWxMsg($wxParam);
                                            }
                                            // 回复类型为 图片
                                            else if ($contents['type']=='img') {
                                                $wxParam['type'] = 'img';
                                                $this->sendWxMsg($wxParam);
                                            }
                                            // 回复类型为 图文消息
                                            else if ($contents['type']=='news') {
                                                $wxParam['news_info'] = $contents['news_info'];
                                                $wxParam['type'] = 'news';
                                                $this->sendWxMsg($wxParam);
                                            }
                                            // 回复类型为 语音
                                            else if ($contents['type']=='voice') {
                                                $wxParam['type'] = 'voice';
                                                $this->sendWxMsg($wxParam);
                                            }
                                            // 回复类型为 视频
                                            else if ($contents['type']=='video') {
                                                $wxParam['type'] = 'video';
                                                $this->sendWxMsg($wxParam);
                                            }
                                        }
                                        break;
                                    }
                                }
                                // 如果没有匹配的关键词 查看
                                if ($matchKey === false) {
                                    $autoRule = db('crm_s_wx_auto_answer')->where('wxsys_id',$v['id'])->where('auto_type',2)->find();
                                    if ($autoRule) {
                                        $contents = json_decode($autoRule['contents'], true);
                                        $wxParam['openid']  = $openid;
                                        $wxParam['content'] = $contents['content'];
                                        $wxParam['fromUsername'] = $fromUsername;
                                        $wxParam['toUsername'] = $toUsername;
                                        $wxParam['time'] = time();
                                        // 回复类型为 文本
                                        if ($contents['type']=='text') {
                                            textlog('进入自动回复文本消息');
                                            $wxParam['type'] = 'text';
                                            $this->sendWxMsg($wxParam);
                                        }
                                        // 回复类型为 图片
                                        else if ($contents['type']=='img') {
                                            $wxParam['type'] = 'img';
                                            $this->sendWxMsg($wxParam);
                                        }
                                        // 回复类型为 图文消息
                                        else if ($contents['type']=='news') {
                                            $wxParam['news_info'] = $contents['news_info'];
                                            $wxParam['type'] = 'news';
                                            $this->sendWxMsg($wxParam);
                                        }
                                        // 回复类型为 语音
                                        else if ($contents['type']=='voice') {
                                            $wxParam['type'] = 'voice';
                                            $this->sendWxMsg($wxParam);
                                        }
                                        // 回复类型为 视频
                                        else if ($contents['type']=='video') {
                                            $wxParam['type'] = 'video';
                                            $this->sendWxMsg($wxParam);
                                        }
                                    }
                                }
                            }else{
                                // 收到消息回复
                                $autoRule = db('crm_s_wx_auto_answer')->where('wxsys_id',$v['id'])->where('auto_type',2)->find();
                                if ($autoRule) {
                                    $contents = json_decode($autoRule['contents'], true);
                                    $wxParam['openid']  = $openid;
                                    $wxParam['content'] = $contents['content'];
                                    $wxParam['fromUsername'] = $fromUsername;
                                    $wxParam['toUsername'] = $toUsername;
                                    $wxParam['time'] = time();
                                    // 回复类型为 文本
                                    if ($contents['type']=='text') {
                                        textlog('进入自动回复文本消息');
                                        $wxParam['type'] = 'text';
                                        $this->sendWxMsg($wxParam);
                                    }
                                    // 回复类型为 图片
                                    else if ($contents['type']=='img') {
                                        $wxParam['type'] = 'img';
                                        $this->sendWxMsg($wxParam);
                                    }
                                    // 回复类型为 图文消息
                                    else if ($contents['type']=='news') {
                                        $wxParam['news_info'] = $contents['news_info'];
                                        $wxParam['type'] = 'news';
                                        $this->sendWxMsg($wxParam);
                                    }
                                    // 回复类型为 语音
                                    else if ($contents['type']=='voice') {
                                        $wxParam['type'] = 'voice';
                                        $this->sendWxMsg($wxParam);
                                    }
                                    // 回复类型为 视频
                                    else if ($contents['type']=='video') {
                                        $wxParam['type'] = 'video';
                                        $this->sendWxMsg($wxParam);
                                    }
                                }
                            }
                            
                            // 获取用户的基本信息 如果表里没有重新请求微信接口
                            $rInfo = db('crm_s_wx_relation')->where('openid',$openid)->field('id,nickname,headimgurl,remark,kf_id')->find();
                            if ($rInfo) {
                                textlog("inIf");
                                // 如果之前有用户的信息，看看有没有分配客服
                                if ($rInfo['kf_id']) {
                                    // 如果有客服id，把这条消息保存下来
                                    $inTalk['openid']  = "$openid";
                                    $inTalk['opercode']= '2003';
                                    $inTalk['text']    = $keywords;
                                    $inTalk['time']    = date('Y-m-d H:i:s');
                                    $inTalk['kf_id']   = $rInfo['kf_id'];
                                    /*
                                    // 如果有客服id，创建会话  这是个坑，必须用微信后台登录才行
                                    $linkUrl = 'https://api.weixin.qq.com/customservice/kfsession/create?access_token='.$access_token;
                                    $kf_account = db('crm_s_wx_kf_staff')->where('id',$rInfo['kf_id'])->value('kf_account');
                                    $linkPost['kf_account'] = $kf_account;
                                    $linkPost['openid'] = $openid;
                                    $linkRes = http_request($linkUrl,'POST',json_encode($linkPost));
                                    textlog('创建客服会话==》'.$linkRes);
                                    */
                                    // 根据客服id找到staff_id 给这个员工发弹窗带上会话列表的链接）
                                    $sInfo = db('crm_s_wx_kf_staff')->where('id',$rInfo['kf_id'])->find();
                                    $msg = '已有用户发来消息，请前去会话，<a href="/weixin/weixin/wxTalkList" target="_blank" style="color: red;">点击前去</a>';
                                    $message['send_type']      = 1;
                                    $message['send_title']     = '会话提醒';
                                    $message['send_msg']       = $msg;
                                    $message['customer_id']    = 0;
                                    $message['receive_id']     = $sInfo['staff_id'];
                                    $message['receive_name']   = $sInfo['staff_name'];
                                    $message['receive_status'] = 0;
                                    $message['operation_type'] = 2;
                                    $message['operation']      = [];
                                    $message['time_out']       = 240;
                                    sendSystemMessage($message);
                                }else{
                                    textlog("inElse");
                                    // 如果有客服id，把这条消息保存下来
                                    $inTalk['openid']  = "$openid";
                                    $inTalk['opercode']= '2003';
                                    $inTalk['text']    = $keywords;
                                    $inTalk['time']    = date('Y-m-d H:i:s');
                                    /* 
                                    // 如果没有对应的客服 将消息转发到客服 在会话界面调接口，获取未接入会话(GET https://api.weixin.qq.com/customservice/kfsession/getwaitcase?access_token=ACCESS_TOKEN) 这就是坑，大坑
                                    $itemTpl = "<xml> 
                                           <ToUserName><![CDATA[%s]]></ToUserName>  
                                           <FromUserName><![CDATA[%s]]></FromUserName>  
                                           <CreateTime>%s</CreateTime>  
                                           <MsgType><![CDATA[transfer_customer_service]]></MsgType> 
                                        </xml>";
                                    $result = sprintf($itemTpl, $fromUsername, $toUsername, $time);
                                    //返回消息给微信
                                    echo $result;
                                    */
                                    // 没有kf_id 给设定的管理员发送弹窗带上会话列表的链接）
                                    foreach($staffinfo as $key=>$val){
                                        $msg = '已有新用户发来消息，请前去分配，<a href="/weixin/weixin/wxTalkList" target="_blank" style="color: red;">点击前去</a>';
                                        $message['send_type']      = 1;
                                        $message['send_title']     = '会话提醒';
                                        $message['send_msg']       = $msg;
                                        $message['customer_id']    = 0;
                                        $message['receive_id']     = $val['id'];
                                        $message['receive_name']   = $val['staffname'];
                                        $message['receive_status'] = 0;
                                        $message['operation_type'] = 2;
                                        $message['operation']      = [];
                                        $message['time_out']       = 240;
                                        sendSystemMessage($message);
                                    }
                                }
                                textlog('保存信息==》'.json_encode($inTalk));
                                try {
                                    $talkRes = db('crm_s_wx_talk')->insert($inTalk);

                                } catch (\Exception $e) {
                                    textlog('catch==》'.$e->getMessage());
                                }
                                
                                textlog('保存结果==》'.$talkRes);
                                textlog('talkSql==》'.db()->getLastSql());
                                // $sendMsg = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
                                // // textlog("发送的地址==>".$sendMsg);
                                // // textlog("openid==>".$openid);
                                // $post['touser'] = "$openid";
                                // $post['msgtype'] = 'text';
                                // $post['text']['content'] = "Hello World";
                                // $post['customservice']['kf_account'] = 'kf2006@suxuantech';
                                // textlog("发送的内容==>".json_encode($post));
                                // $addRes = http_request($sendMsg,'POST',json_encode($post));
                                // textlog("发送的结果==>".json_encode($addRes));
                            }else{
                                $getUInfoUrl = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
                                $uInfo = http_request($getUInfoUrl,'GET');
                                $info = json_decode($uInfo['response'],true);
                                if($info['errcode'] > 0){
                                    textlog('获取用户的基本信息失败【openid：'.$openid.'；错误信息：'.$uInfo.'】');
                                }else{
                                    // 用户已经关注
                                    if ($info['subscribe'] == 1) {
                                        $inData['subscribe']     = $info['subscribe'];
                                        $inData['openid']        = $info['openid'];
                                        $inData['nickname']      = $info['nickname'];
                                        $inData['sex']           = $info['sex'];
                                        $inData['language']      = $info['language'];
                                        $inData['headimgurl']    = $info['headimgurl'];
                                        $inData['subscribe_time']= $info['subscribe_time'];
                                        $inData['unionid']       = $info['unionid'];
                                        $inData['remark']        = $info['remark'];
                                        $inData['wx_sys_id']     = $v['id'];
                                        $inRes = db('crm_s_wx_relation')->insert($inData);
                                        if (!$inRes) {
                                            textlog('保存用户信息失败，lastSQL：'.db()->getLastSql());
                                        }
                                        $inTalk['openid']  = $openid;
                                        $inTalk['opercode']= '2003';
                                        $inTalk['text']    = $keywords;
                                        $inTalk['time']    = date('Y-m-d H:i:s');
                                        db('crm_s_wx_talk')->insert($inTalk);
                                        /*
                                        $itemTpl = "<xml> 
                                                <ToUserName><![CDATA[%s]]></ToUserName>  
                                                <FromUserName><![CDATA[%s]]></FromUserName>  
                                                <CreateTime>%s</CreateTime>  
                                                <MsgType><![CDATA[transfer_customer_service]]></MsgType> 
                                            </xml>";
                                        $result = sprintf($itemTpl, $fromUsername, $toUsername, $time, $content);
                                        //返回消息给微信
                                        echo $result;
                                        */
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    /**
     * 被动回复用户消息     只能回复一条  文本，图片，图文已经实现  其他的感觉接口有问题 语音消息只有一秒，视频消息获取不到media_id
     *
     * @param  type         回复消息类型 text:文本 img:图片 news:图文消息 voice:语音 video:视频
     * @param  content      短信内容
     * @param  fromUsername 
     * @param  toUsername    
     * @param  time    
     *
     * @author lilong<lilong@suxuantech.cn>
     */
    public function sendWxMsg($param){
        // db()->startTrans();
        try {
            // 保存发送的消息
            $inTalk['openid'] = $param['openid'];
            $inTalk['opercode'] = '2002';
            $inTalk['type']  = $param['type'];
            $inTalk['text']  = $param['content'];
            $inTalk['time']  = date('Y-m-d H:i:s',$param['time']);
            $inTalk['kf_id'] = '-1';
            $inRes = db('crm_s_wx_talk')->insert($inTalk);
            textlog('进数据库的数据'.json_encode($inTalk));
            // 回复类型为 文本
            if ($param['type']=='text') {
                $itemTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[text]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                            </xml>";
                $result = sprintf($itemTpl, $param['fromUsername'], $param['toUsername'], $param['time'], $param['content']);
            }
            // 回复类型为 图片
            else if ($param['type']=='img') {
                $itemTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[image]]></MsgType>
                                <Image>
                                    <MediaId><![CDATA[%s]]></MediaId>
                                </Image>
                            </xml>";
                $result = sprintf($itemTpl, $param['fromUsername'], $param['toUsername'], $param['time'], $param['content']);
            }
            // 回复类型为 图文消息
            else if ($param['type']=='news') {
                $info = $param['news_info']['list'][0];
                // textlog('newsInfo--'.json_encode($info));
                $itemTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[news]]></MsgType>
                                <ArticleCount>1</ArticleCount>
                                <Articles>
                                    <item>
                                        <Title><![CDATA[%s]]></Title>
                                        <Description><![CDATA[%s]]></Description>
                                        <PicUrl><![CDATA[%s]]></PicUrl>
                                        <Url><![CDATA[%s]]></Url>
                                    </item>
                                </Articles>
                            </xml>";
                $result = sprintf($itemTpl, $param['fromUsername'], $param['toUsername'], $param['time'], $info['title'],$info['digest'],$info['cover_url'],$info['content_url']);
            }
            // 回复类型为 语音
            else if ($param['type']=='voice') {
                $itemTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[voice]]></MsgType>
                                <Voice>
                                    <MediaId><![CDATA[%s]]></MediaId>
                                </Voice>
                            </xml>";
                // $result = sprintf($itemTpl, $param['fromUsername'], $param['toUsername'], $param['time'], $param['content']);
            }
            // 回复类型为 视频
            else if ($param['type']=='video') {
                $itemTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[video]]></MsgType>
                                <Video>
                                    <MediaId><![CDATA[%s]]></MediaId>
                                    <Title><![CDATA[%s]]></Title>
                                    <Description><![CDATA[%s]]></Description>
                                </Video>
                            </xml>";
                // $result = sprintf($itemTpl, $param['fromUsername'], $param['toUsername'], $param['time'], $param['content']);
            }            
            textlog('被动回复用户消息：'.$result);
            //返回消息给微信
            echo $result ? $result : 'success';
        } catch (\Exception $e) {
            // db()->rollback();
            textlog('被动回复失败'.$e->getMessage());
        }
    }

    /**
     * 主动发送客服消息     只发送一条，如需发送多条消息，可以重复调用
     *
     * @param  access_token 公众号access_token
     * @param  type         回复消息类型 text:文本 img:图片 news:图文消息 voice:语音 video:视频
     * @param  content      短信内容  如果是非文本消息，发送是需要的参数都在该参数中
     * @param  time         发送消息的时间
     * @param  openid       接收消息的用户的openid 
     * @param  kid          发送消息的客服id  如果为-1 则代表系统自动发送
     * @param  kf_account   发送消息的客服账号  系统发送该字段为空
     *
     * @author lilong<lilong@suxuantech.cn>
     */
    public function sendKfMsg($param){
        db()->startTrans();
        try {
            // 保存发送的消息
            $inTalk['openid'] = $param['openid'];
            $inTalk['opercode'] = '2002';
            $inTalk['type'] = $param['type'];
            $inTalk['text'] = $param['content']['text'];
            $inTalk['time'] = $param['time'];
            $inTalk['kf_id']= $param['kid'];
            $inRes = db('crm_s_wx_talk')->insert($inTalk);
            // 调微信接口，发送消息
            $sendUrl = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
            // 文本消息
            if ($param['type']=='text') {
                $sendPost['touser'] = $param['openid'];
                $sendPost['msgtype'] = 'text';
                $sendPost['text']['content'] = $param['content']['text'];
            }
            // 图片消息
            else if ($param['type']=='img') {
                $sendPost['touser'] = $param['openid'];
                $sendPost['msgtype'] = 'image';
                $sendPost['image']['media_id'] = $param['content']['media_id'];
            }
            // 语音消息
            else if ($param['type']=='voice') {
                $sendPost['touser'] = $param['openid'];
                $sendPost['msgtype'] = 'voice';
                $sendPost['voice']['media_id'] = $param['content']['media_id'];
            }
            // 视频消息
            else if ($param['type']=='video') {
                $sendPost['touser'] = $param['openid'];
                $sendPost['msgtype'] = 'video';
                $sendPost['video']['media_id'] = $param['content']['media_id'];
                $sendPost['video']['thumb_media_id'] = $param['content']['media_id'];
                $sendPost['video']['title'] = $param['content']['title'];
                $sendPost['video']['description'] = $param['content']['description'];
            }
            // 图文消息A  发送图文消息（点击跳转到外链） 图文消息条数限制在1条以内，注意，如果图文数超过1，则将会返回错误码45008。
            else if ($param['type']=='news') {
                $sendPost['touser'] = $param['openid'];
                $sendPost['msgtype'] = 'news';
                $sendPost['news']['articles'][0]['title'] = $param['content']['title'];
                $sendPost['news']['articles'][0]['description'] = $param['content']['description'];
                $sendPost['news']['articles'][0]['url'] = $param['content']['url'];
                $sendPost['news']['articles'][0]['picurl'] = $param['content']['picurl'];
            }
            // 图文消息B  发送图文消息（点击跳转到图文消息页面） 图文消息条数限制在1条以内，注意，如果图文数超过1，则将会返回错误码45008。
            else if ($param['type']=='mpnews') {
                $sendPost['touser'] = $param['openid'];
                $sendPost['msgtype'] = 'mpnews';
                $sendPost['mpnews']['media_id'] = $param['content']['media_id'];
            }
            // 音乐消息
            else if ($param['type']=='music') {
                $sendPost['touser'] = $param['openid'];
                $sendPost['msgtype'] = 'music';
                $sendPost['music']['title'] = $param['content']['title'];
                $sendPost['music']['description'] = $param['content']['description'];
                $sendPost['music']['musicurl'] = $param['content']['musicurl'];
                $sendPost['music']['hqmusicurl'] = $param['content']['hqmusicurl'];
                $sendPost['music']['thumb_media_id'] = $param['content']['thumb_media_id'];
            }
            // 菜单消息
            else if ($param['type']=='msgmenu') {
                $sendPost['touser'] = $param['openid'];
                $sendPost['msgtype'] = 'msgmenu';
                $sendPost['msgmenu']['head_content'] = $param['content']['head_content'];
                // 暂时固定两个，以后可以考虑写成循环
                $sendPost['msgmenu']['list'][0]['id']     = $param['content']['list'][0]['id'];
                $sendPost['msgmenu']['list'][0]['content']= $param['content']['list'][0]['content'];
                $sendPost['msgmenu']['list'][1]['id']     = $param['content']['list'][1]['id'];
                $sendPost['msgmenu']['list'][1]['content']= $param['content']['list'][1]['content'];

                $sendPost['msgmenu']['tail_content'] = $param['content']['tail_content'];
            }
            // 客服帐号
            if ($param['kf_account']) {
                $sendPost['customservice']['kf_account'] = $param['kf_account'];
                $kf_account = $param['kf_account'];
            }else{
                $kf_account = '系统';
            }
            
            $sendRes = http_request($sendUrl, 'POST', json_encode($sendPost, JSON_UNESCAPED_UNICODE));
            $response = json_decode($sendRes['response'],true);
            if ($response['errcode'] > 0) {
                db()->rollback();
                return array('code' => $sendRes['errcode'], 'msg' => $kf_account. '发送消息 ' .$param['content']['text']. ' 时出错' . $sendRes['errmsg'], 'data' => $sendRes['errcode']);
            }
            db()->commit();
            return array('code' => 200, 'msg' => '发送成功 ', 'data' => '');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 101, 'msg' => '保存信息失败，请重试。', 'error' => $e->getMessage());
        }
    }
    //------------------------------ 微信会话机制调整，将server放到mc上以下代码没用了  结束 ------------------------------//
}