<?php
/**
 * 微信 lib
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: lilong<lilong@suxuantech.cn> 2019-08-23 $
 */
namespace app\Weixin\lib;
use think\Controller;
use think\Exception;
use app\common\lib\redisQueue;

class Weixin extends Controller{

	/**
     * 检查并处理对话表 1:表是否存在 2:字段是否存在 3:数据类型是否发生变动
     *
     * @param  table_name       表明
     *
     * @author lilong<lilong@suxuantech.cn>
     */
	public function checkTalkTable($param){
		$table_name = trim($param['table_name']);
		if (!$table_name) {
			return ['code'=>99,'msg'=>'缺少参数','data'=>json_encode($param)];
		}
		// 如果表不存在 以 talk表为模板创建新表
		if (!isTableExist($table_name)) {
			try {
				$sql = "CREATE TABLE IF NOT EXISTS `".$table_name."` (LIKE `crm_s_wx_talk`)";
            	db()->master()->query($sql);
            	return ['code'=>200,'msg'=>'新建表：'.$table_name.'成功','data'=>''];
			} catch (\Exception $e) {
				return ['code'=>100,'msg'=>'新增Table‘'.$table_name.'’失败，SQL：'.$sql,'data'=>$e->getMessage()];
			}
		}
		// 如果表存在
		else{
			$baseSql = "SHOW COLUMNS FROM `crm_s_wx_talk`";
    		$baseColumns = db()->master()->query($baseSql);
    		$baseField = array_column($baseColumns,'Field');
    		$baseType = array_column($baseColumns,'Type');

    		$tableSql = "SHOW COLUMNS FROM `".$table_name."`";
    		$tableColumns = db()->master()->query($tableSql);
    		$tableField = array_column($tableColumns,'Field');
    		$tableType = array_column($tableColumns,'Type');
    		// 字段不一样
    		$diffField = array_diff($baseField, $tableField);
    		if ($diffField) {
    			try {
    				foreach ($diffField as $key => $value) {
    					$alertSql = 'ALTER TABLE `'.$table_name.'` ADD COLUMN `'.$value.'` '.$baseColumns[$key]['Type'];
    					db()->master()->query($alertSql);
	    			}
	    			return ['code'=>200,'msg'=>'','data'=>''];
    			} catch (\Exception $e) {
    				return ['code'=>101,'msg'=>'新增字段‘'.json_encode($diffField).'’失败，SQL：'.$alertSql,'data'=>$e->getMessage()];
    			}
    		}
    		// 类型不一样
    		$diffType = [];
    		foreach ($baseType as $key => $value) {
    			if ($value != $tableType[$key]) {
    				$temp['column'] = $baseColumns[$key]['Field'];
    				$temp['type'] = $value;
    				array_push($diffType, $temp);
    			}
    		}
    		if ($diffType) {
    			try {
    				foreach ($diffType as $key => $value) {
    					$alertSql = 'ALTER TABLE `'.$table_name.'`  MODIFY COLUMN `'.$value['column'].'` '.$value['type'];
    					db()->master()->query($alertSql);
	    			}
	    			return ['code'=>200,'msg'=>'','data'=>''];
    			} catch (\Exception $e) {
    				return ['code'=>102,'msg'=>'修改字段类型‘'.json_encode($diffType).'’失败，SQL：'.$alertSql,'data'=>$e->getMessage()];
    			}
    		}
		}
		return ['code'=>200,'msg'=>'','data'=>''];
	}
	/**
     * 上传临时素材
     *
     * @param  access_token     公众号access_token
     * @param  media_url        资源存放的URL（相对路径）
     * @param  type             资源类型 分别有图片（ image ）、语音（ voice ）、视频（ video ）和缩略图（ thumb ，主要用于视频与音乐格式的缩略图）
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getWxSendTemporaryMaterial($params){
        if (!$params['media_url']) {
            return array('code'=>100,'msg'=>'没有url参数！');
        }
        $access_token = $params['access_token'];
        if (!$access_token) {
        	$brandclass_id = (int)$params['brandclass_id'] ? (int)$params['brandclass_id'] : session('brandclass_id');
            $mc = new \app\common\lib\mcInterface();
			$access_token = $mc->getAccessToken(['brandclass_id'=>$brandclass_id]);
        }

        // 上传临时素材
        $mediaUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$access_token."&type=".$params['type'];
        if(class_exists('\CURLFile')){  //7.0
            // $fileData['media'] = new \CURLFile( realpath($params['url']) );
            $fileData['media'] = new \CURLFile(ROOT_PATH.'public'.$params['media_url']);
        }else{  //5.6以及5.6以下
            $fileData['media'] = '@'.$params['media_url'];
        }
        // var_dump($fileData);
        //设置URL和相应的选项 
        $curl = curl_init();
        if (class_exists('\CURLFile' )) {//php5.5跟php5.6中的CURLOPT_SAFE_UPLOAD的默认值不同
            curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true );
        } else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        curl_setopt($curl, CURLOPT_URL, $mediaUrl);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($fileData)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $fileData);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        $wxrs_id_card=json_decode($output,true);
        $media_id = $wxrs_id_card['media_id'];
        
        return [
        	'code'=>200,
        	'msg'=>'',
        	'data'=>['media_id'=>$media_id],
        ];
    }

   	/**
     * 获取emoji表情地址
     *
     * @param  opercode     操作码，2002（客服发送信息），2003（客服接收消息）
     * @param  text         文本内容
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
   	public function changeTextEmoji($param){
   		// 获取表情数组
   		$emojiArr = $this->getEmojiArr(['opercode'=>$param['opercode']]);
   		$text = $param['text'];
   		$config = config('ext.app_config');
		$url = $config['sx_mc']['addr'];
   		if ($param['opercode'] == 2002) {
   			//表情
            preg_match_all ("/\[.*?\]/i", $param['text'], $bq);
            if (count($bq[0]) > 0) {
                foreach ($bq[0] as $k => $v) {
                    if ($emojiArr[$v]) {
                        $text = str_replace($v,'<img style="width: 25px;" type="emoji" src="'.$url.'/public/wx/img/'.$emojiArr[$v].'" msg="'.$v.'">',$text);
                    }
                }
            }
   		}else {
   			foreach ($emojiArr as $k => $v) {
                $text = str_replace($k,'<img style="width: 25px;" type="emoji" src="'.$url.'/public/wx/img/'.$v.'" msg="'.$v.'">',$text);
            }
   		}
   		// var_dump($text);
   		return $text;
   	}
    /**
     * 获取emoji表情地址
     *
     * @param  opercode     操作码，2002（客服发送信息），2003（客服接收消息）
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getEmojiArr($param){
        if ($param['opercode']==2002) {
            $tupian_arr = ["[微笑]"=>"smiley_0.png","[撇嘴]"=>"smiley_1.png","[色]"=>"smiley_2.png","[发呆]"=>"smiley_3.png","[得意]"=>"smiley_4.png","[流泪]"=>"smiley_5.png","[害羞]"=>"smiley_6.png","[闭嘴]"=>"smiley_7.png","[睡]"=>"smiley_8.png","[大哭]"=>"smiley_9.png","[尴尬]"=>"smiley_10.png","[发怒]"=>"smiley_11.png","[调皮]"=>"smiley_12.png","[呲牙]"=>"smiley_13.png","[惊讶]"=>"smiley_14.png","[难过]"=>"smiley_15.png","[酷]"=>"smiley_16.png","[囧]"=>"smiley_17.png","[抓狂]"=>"smiley_18.png","[吐]"=>"smiley_19.png","[偷笑]"=>"smiley_20.png","[愉快]"=>"smiley_21.png","[白眼]"=>"smiley_22.png","[傲慢]"=>"smiley_23.png","[饥饿]"=>"smiley_24.png","[困]"=>"smiley_25.png","[惊恐]"=>"smiley_26.png","[流汗]"=>"smiley_27.png","[憨笑]"=>"smiley_28.png","[悠闲]"=>"smiley_29.png","[奋斗]"=>"smiley_30.png","[咒骂]"=>"smiley_31.png","[疑问]"=>"smiley_32.png","[嘘]"=>"smiley_33.png","[晕]"=>"smiley_34.png","[疯了]"=>"smiley_35.png","[衰]"=>"smiley_36.png","[骷髅]"=>"smiley_37.png","[敲打]"=>"smiley_38.png","[再见]"=>"smiley_39.png","[擦汗]"=>"smiley_40.png","[抠鼻]"=>"smiley_41.png","[鼓掌]"=>"smiley_42.png","[糗大了]"=>"smiley_43.png","[坏笑]"=>"smiley_44.png","[左哼哼]"=>"smiley_45.png","[右哼哼]"=>"smiley_46.png","[哈欠]"=>"smiley_47.png","[鄙视]"=>"smiley_48.png","[委屈]"=>"smiley_49.png","[快哭]"=>"smiley_50.png","[阴险]"=>"smiley_51.png","[亲亲]"=>"smiley_52.png","[吓]"=>"smiley_53.png","[可怜]"=>"smiley_54.png","[菜刀]"=>"smiley_55.png","[西瓜]"=>"smiley_56.png","[啤酒]"=>"smiley_57.png","[篮球]"=>"smiley_58.png","[乒乓]"=>"smiley_59.png","[咖啡]"=>"smiley_60.png","[饭]"=>"smiley_61.png","[猪头]"=>"smiley_62.png","[玫瑰]"=>"smiley_63.png","[凋谢]"=>"smiley_64.png","[嘴唇]"=>"smiley_65.png","[爱心]"=>"smiley_66.png","[心碎]"=>"smiley_67.png","[蛋糕]"=>"smiley_68.png","[闪电]"=>"smiley_69.png","[炸弹]"=>"smiley_70.png","[刀]"=>"smiley_71.png","[足球]"=>"smiley_72.png","[瓢虫]"=>"smiley_73.png","[便便]"=>"smiley_74.png","[月亮]"=>"smiley_75.png","[太阳]"=>"smiley_76.png","[礼物]"=>"smiley_77.png","[拥抱]"=>"smiley_78.png","[强]"=>"smiley_79.png","[弱]"=>"smiley_80.png","[握手]"=>"smiley_81.png","[胜利]"=>"smiley_82.png","[抱拳]"=>"smiley_83.png","[勾引]"=>"smiley_84.png","[拳头]"=>"smiley_85.png","[差劲]"=>"smiley_86.png","[爱你]"=>"smiley_87.png","[No]"=>"smiley_88.png","[OK]"=>"smiley_89.png","[爱情]"=>"smiley_90.png","[飞吻]"=>"smiley_91.png","[跳跳]"=>"smiley_92.png","[发抖]"=>"smiley_93.png","[怄火]"=>"smiley_94.png","[转圈]"=>"smiley_95.png","[磕头]"=>"smiley_96.png","[回头]"=>"smiley_97.png","[跳绳]"=>"smiley_98.png","[右太极]"=>"smiley_99.png","[激动]"=>"smiley_100.png","[乱舞]"=>"smiley_101.png","[献吻]"=>"smiley_102.png","[左太极]"=>"smiley_103.png","[投降]"=>"smiley_104.png","[奸笑]"=>"2_02.png","[嘿哈]"=>"2_04.png","[捂脸]"=>"2_05.png","[机智]"=>"2_06.png","[耶]"=>"2_11.png","[皱眉]"=>"2_12.png","[红包]"=>"2_09.png"];
        }else{
            $tupian_arr = ["/::)"=>"smiley_0.png","/::~"=>"smiley_1.png","/::B"=>"smiley_2.png","/::|"=>"smiley_3.png","/:8-)"=>"smiley_4.png","/::<"=>"smiley_5.png","/::$"=>"smiley_6.png","/::X"=>"smiley_7.png","/::Z"=>"smiley_8.png","/::’("=>"smiley_9.png","/::-|"=>"smiley_10.png","::@"=>"smiley_11.png","/::P"=>"smiley_12.png","/::D"=>"smiley_13.png","/::O"=>"smiley_14.png","/::("=>"smiley_15.png","/::+"=>"smiley_16.png","/:–b"=>"smiley_17.png","/::Q"=>"smiley_18.png","/::T"=>"smiley_19.png","/:,@P"=>"smiley_20.png","/:,@-D"=>"smiley_21.png","/::d"=>"smiley_22.png","/:,@o"=>"smiley_23.png","/::g"=>"smiley_24.png","/:|-)"=>"smiley_25.png","/::!"=>"smiley_26.png","/::L"=>"smiley_27.png","/::>"=>"smiley_28.png","/::,@"=>"smiley_29.png","/:,@f"=>"smiley_30.png","/::-S"=>"smiley_31.png","/:?"=>"smiley_32.png","/:,@x"=>"smiley_33.png","/:,@@"=>"smiley_34.png","/::8"=>"smiley_35.png","/:,@!"=>"smiley_36.png","/:!!!"=>"smiley_37.png","/:xx"=>"smiley_38.png","/:bye"=>"smiley_39.png","/:wipe"=>"smiley_40.png","/:dig"=>"smiley_41.png","/:handclap"=>"smiley_42.png","/:&-("=>"smiley_43.png","/:B-)"=>"smiley_44.png","/:<@"=>"smiley_45.png","/:@>"=>"smiley_46.png","/::-O"=>"smiley_47.png","/:>-|"=>"smiley_48.png","/:P-("=>"smiley_49.png","/::’|"=>"smiley_50.png","/:X-)"=>"smiley_51.png","/::*"=>"smiley_52.png","/:@x"=>"smiley_53.png","/:8*"=>"smiley_54.png","/:pd"=>"smiley_55.png","/:<W>"=>"smiley_56.png","/:beer"=>"smiley_57.png","/:basketb"=>"smiley_58.png","/:oo"=>"smiley_59.png","/:coffee"=>"smiley_60.png","/:eat"=>"smiley_61.png","/:pig"=>"smiley_62.png","/:rose"=>"smiley_63.png","/:fade"=>"smiley_64.png","/:showlove"=>"smiley_65.png","/:heart"=>"smiley_66.png","/:break"=>"smiley_67.png","/:cake"=>"smiley_68.png","/:li"=>"smiley_69.png","/:bome"=>"smiley_70.png","/:kn"=>"smiley_71.png","/:footb"=>"smiley_72.png","/:ladybug"=>"smiley_73.png","/:shit"=>"smiley_74.png","/:moon"=>"smiley_75.png","/:sun"=>"smiley_76.png","/:gift"=>"smiley_77.png","/:hug"=>"smiley_78.png","/:strong"=>"smiley_79.png","/:weak"=>"smiley_80.png","/:share"=>"smiley_81.png","/:v"=>"smiley_82.png","/:@)"=>"smiley_83.png","/:jj"=>"smiley_84.png","/:@@"=>"smiley_85.png","/:bad"=>"smiley_86.png","/:lvu"=>"smiley_87.png","/:no"=>"smiley_88.png","/:ok"=>"smiley_89.png","/:love"=>"smiley_90.png","/:<L>"=>"smiley_91.png","/:jump"=>"smiley_92.png","/:shake"=>"smiley_93.png","/:<O>"=>"smiley_94.png","/:circle"=>"smiley_95.png","/:kotow"=>"smiley_96.png","/:turn"=>"smiley_97.png","/:skip"=>"smiley_98.png","/:&>"=>"smiley_99.png","/:#-0"=>"smiley_100.png","/:hiphot"=>"smiley_101.png","/:kiss"=>"smiley_102.png","/:<&"=>"smiley_103.png","/:oY"=>"smiley_104.png","[Smirk]"=>"2_02.png","[Hey]"=>"2_04.png","[Facepalm]"=>"2_05.png","[Smart]"=>"2_06.png","[Yeah!]"=>"2_11.png","[Concerned]"=>"2_12.png","[Packet]"=>"2_09.png"];
        }
        return $tupian_arr;
    }

    /**
     * 根据客服id 获取最新的消息
     *
     * @param  kf_id     客服id
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getNewWxMessage($param){
    	$kf_id = (int)$param['kf_id'];
    	
    	// $msg = db('crm_s_wx_talk')->where('kf_id',$kf_id)->select();
    	return $kf_id;
    }
    /**
     * 对接收到的新消息保存新消息
     * 
     * @param  [type] $messageList [description]
     * @return [type]              [description]
     */
    public  function saveNewWxMessage($messageList){
        $appid = [];
        $openid = [];
        $messages = [];
        $maxId = 0;
        $maxInfo = [];
        $existMaxId = db('crm_s_wx_talk')->max('mc_id');
        // 设定的消息接收人
        $staff_id = db_config('wx_talk_remind_staffids');
        $mc = new \app\common\lib\mcInterface();
        $staffinfo = $mc->getStaffByIds($staff_id);

        foreach ($messageList as $key => $value) {
            $appid[$value['appid']] = ['appid'=>$value['appid'],'id'=>0];
            $msg = json_decode($value['msg'],true);
            $subscribe = 1;
            if($value['msg_type'] == 'event'){
                $subscribe = $msg['Event'] == 'unsubscribe'?0:1;
            }
            $openid[$value['openid']] = [
                'openid'=>$value['openid'],
                'subscribe'=>$subscribe,
                'appid' =>$value['appid'],
                'sex'=>$value['sex'],
                'create_time'=>$value['create_time'],
                'headimgurl'=>$value['headimgurl'],
                'subscribe_time'=>$value['subscribe_time'],
                'unionid'=>$value['unionid'],
                'nickname'=>$value['nickname'],
                'language'=>$value['language'],
            ];
            $table = 'crm_s_wx_talk_'.strtolower(substr($value['openid'], -1));
            $tbres = $this->checkTalkTable(['table_name'=>$table]);
            if($tbres['code'] != 200){
                textlog('微信消息数据保存失败，检查消息表失败：'.$tbres['msg'].';消息ID'.$value['id'],SX_LOG_LEVEL_ERROR);
                continue;
            }
            // $maxId = $value['id'] > $maxId ? $value['id'] : $maxId;
            $msg = json_decode($value['msg'],true);
            $lastText = '';
            switch ($value['msg_type']) {
                case 'text':
                    $text = json_decode('{"str":"'.$msg['Content'].'"}',true);
                    $lastText = $text['str'];
                    $talkData[$table][] = [
                        'mc_id'=>$value['id'],
                        'openid'=>$value['openid'],
                        'opercode'=>'2003',
                        'type'=>$value['msg_type'],
                        'time'=>$value['create_time'],
                        'status'=>0,
                        'text'=>$text['str'],
                        'type_supply'=>NULL,
                    ];
                    break;
                case 'image':
                    $lastText = $msg['MediaId'];
                    $talkData[$table][] = [
                        'mc_id'=>$value['id'],
                        'openid'=>$value['openid'],
                        'opercode'=>'2003',
                        'type'=>$value['msg_type'],
                        'time'=>$value['create_time'],
                        'status'=>0,
                        'text'=>$msg['MediaId'],
                        'type_supply'=>'temp',// 客户发送的图片消息全部当做 临时 素材处理
                    ];
                    break;
                case 'voice':
                case 'video':
                    $lastText = $msg['MediaId'];
                    $talkData[$table][] = [
                        'mc_id'=>$value['id'],
                        'openid'=>$value['openid'],
                        'opercode'=>'2003',
                        'type'=>$value['msg_type'],
                        'time'=>$value['create_time'],
                        'status'=>0,
                        'text'=>$msg['MediaId'],
                        'type_supply'=>NULL,
                    ];
                    break;
                default:
                    
                    break;
            }
            if($value['id'] > $maxId){
                $maxId = $value['id'];
                $maxInfo = [
                        'mc_id'=>$value['id'],
                        'openid'=>$value['openid'],
                        'opercode'=>'2003',
                        'type'=>$value['msg_type'],
                        'time'=>$value['create_time'],
                        'status'=>0,
                        'text'=>$lastText,
                        'type_supply'=>NULL,
                    ];
            }
        }
        try{
            //更新APP表
            foreach ($appid as $kapp => $vapp) {
                $exist = db('crm_s_wx_system')->where('appid',$kapp)->find();
                if($exist){
                    $appid[$kapp]['id'] = $exist['id'];
                }else{
                    $appid[$kapp]['id'] = db('crm_s_wx_system')->insertGetId(['appid'=>$kapp]);
                }
            }
            //更新openid表
            foreach ($openid as $kopenid => $vopenid) {
                $exist = db('crm_s_wx_relation')->where('openid',$vopenid['openid'])->find();
                $opendata = [
                    'subscribe'=>$vopenid['subscribe'],
                    'wx_sys_id'=>$appid[$vopenid['appid']]['id'],
                    'openid'=>$vopenid['openid'],
                    'headimgurl'=>$vopenid['headimgurl'],
                    'subscribe_time'=>$vopenid['subscribe_time'],
                    'unionid'=>$vopenid['unionid'],
                    'nickname'=>$vopenid['nickname'],
                    'language'=>$vopenid['language'],
                    'sex'=>$vopenid['sex'],
                    'update_time'=>date('Y-m-d H:i:s'),
                ];
                if(!$exist){
                    $opendata['create_time'] = date('Y-m-d H:i:s');
                    db('crm_s_wx_relation')->insert($opendata);

                    // 给设定的员工发送消息 （弹窗，带上会话列表的链接）
                    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{
                    db('crm_s_wx_relation')->where('openid',$vopenid['openid'])->update($opendata);

                    $rInfo = db('crm_s_wx_relation')->where('openid',$vopenid['openid'])->field('id,nickname,headimgurl,remark,kf_id')->find();
                    if ($rInfo['kf_id']) {
                        // 根据客服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{
                        // 没有kf_id 给设定的接收人发送弹窗带上会话列表的链接
                        foreach($staffinfo as $key=>$val){
                            $msg = '已有新用户发来消息，请前去分配，<a href="/weixin/weixin/wxTalkList" target="_blank" style="color: red;">点击cake</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);
                        }
                    }
                }
            }
            db()->startTrans();
            //更新会话表
            foreach ($talkData as $key => $talks) {
                $lastWord = [];
                foreach ($talks as $kt => $talk) {
                    if($talk['type'] == 'text' && $talk['text'] != '【收到不支持的消息类型，暂无法显示】'){
                        $lastWord[$talk['openid']] = $talk['text'];
                    }
                    // 发广播 带上 openid
                    $message = ['openid'=>$talk['openid']];
                    $res = \app\common\lib\redisQueue::init()->publish('wx_get_msg_by_openid_'.$talk['openid'], $message);
                    # code...
                    /*  //更新最大id放到最后，因为可能有些消息并不是可聊天消息。
                    if($maxId == $talk['mc_id']){
                        if($existMaxId){
                            db('crm_s_wx_talk')->where('mc_id',$existMaxId)->update($talk);
                        }else{
                            db('crm_s_wx_talk')->delete(true);
                            db('crm_s_wx_talk')->insert($talk);
                        }
                        // textlog('保存Talk表 Sql===>'.db()->getLastSql(),SX_LOG_LEVEL_ERROR);
                        break;
                    }*/
                    //已有的消息忽略，防止同一条消息重复记录。
                    $exist = db($key)->where('mc_id',$talk['mc_id'])->find();
                    if($exist){
                        unset($talks[$kt]);
                    }
                }

                db($key)->insertAll($talks);
                if(!empty($lastWord)){
                    foreach ($lastWord as $lk => $lv) {
                        db('crm_s_wx_relation')->where('openid',$lk)->update(['last_word'=>$lv,'update_time'=>date('Y-m-d H:i:s')]);
                        db('crm_s_wx_relation')->where('openid',$lk)->setInc('new_msg_num');
                    }
                }
            }
            if($maxId > $existMaxId){
                db('crm_s_wx_talk')->delete(true);
                db('crm_s_wx_talk')->insert($maxInfo);
            }
            db()->commit();
        }catch(\Exception $e){
            db()->rollback();
            textlog('微信消息数据保存失败。'.$e->getMessage(),SX_LOG_LEVEL_ERROR);
        }
    }
}