<?php
/**
 * CRM 基本模块
 * 默认接口方法，此方法内定议基础框架所需要的方法，用于验证模块合法性，模块版本，对接基础架构中需要的方法
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2017-10-17 $
 */
namespace app\weixin\controller;
use think\Cache;
use app\index\controller\Base;
use think\Request;
use think\Session;
use think\Controller;
use app\common\lib\redisQueue;
use Endroid\QrCode\QrCode;
use think\Response;
class Weixin extends Base{ 
    
    public function receiveCustomer()
    {
        $cid = input('cid/d');
        //$message = controller("Customer","lib")->getMessageByCustomerId($cid);
        $message = db('crm_c_message')
            ->where('receive_id', session('staff_id'))
            ->where('customer_id', $cid)
            ->order('id desc')
            ->find();
        if ($message) {
            if ($message['time_out'] < time()) {
                $message['timeout'] = 1;
            }
            $message['time_out'] = date('Y-m-d H:i:s', $message['time_out']);
            $this->assign('message', $message);
        }
        return $this->fetch();
    }

    /*---------- 客服人员管理 ------start-------------------*/
    public function kfStaffToJSON()
    {
        $param = input('post.');

        $mc = new \app\common\lib\mcInterface();
        $shopInfo = $mc->getShopInfo(['shop_code'=>session('shop_code')]);
        
        $kfList = db('crm_s_wx_kf_staff')->alias('kf')
            ->join('crm_s_wx_system s','s.id=kf.belong_wx_id','left')
            ->where('s.appid',$shopInfo[0]['wx_appid'])->field('kf.*')->select();
        return ['code'=>0,'data'=>$kfList,'sql'=>db()->getLastSql()];
    }

    // 客服列表页面
    public function kfStaffSystem(){
        $dep = getDepartments(['shop_code'=>session('shop_code')]);
        $this->assign('dep', $dep);
        return $this->fetch();
    }

    //根据部门id查询小组
    public function getGroup()
    {
        $data = input('post.');
        $params['department_id'] = (int)$data['department_id'];
        $mc = new \app\common\lib\mcInterface();
        $grouInfo = $mc->getGroupInfo($params);
        return $grouInfo;
    }

    public function getStaffs()
    {
        $staff = getShopStaffs(input('post.'));
        return $staff;
    }

    // 添加客服人员
    public function addkf(){
        $param = input('post.');
        $photo = $param['photo'];
        unset($param['photo']);

        $mc = new \app\common\lib\mcInterface();
        $shopInfo = $mc->getShopInfo(['shop_code'=>session('shop_code')]);
        // var_dump($shopInfo);die;
        $wx_sys_id= db('crm_s_wx_system')->where('appid',$shopInfo['0']['wx_appid'])->value('id');
        if (!$wx_sys_id) {
            return ['code'=>99,'msg'=>'当前店面未设定微信公众号。'];
        }
        // 将客服账号存表
        $staffinfo = getStaffinfoById((int)$param['staff_id']);
        $inKfData['staff_id'] = (int)$param['staff_id'];
        $inKfData['staff_name'] = $staffinfo['staffname'];
        $inKfData['staff_number'] = $staffinfo['staffnumber'];
        $inKfData['kf_nick'] = $param['kf_nick'];
        $inKfData['kf_wx'] = $param['kf_wx'];
        $inKfData['belong_wx_id'] = $wx_sys_id;
        
        db()->startTrans();
        try {
            $kf_id = db('crm_s_wx_kf_staff')->insertGetId($inKfData);
            // mc负责 添加客服，绑定微信号 
            $param['shop_code'] = session('shop_code');
            $res = $mc->getWxAddkf($param);
            if ($res['code']!=200) {
                db()->rollback();
                return $res;
            }else{
                db()->commit();
            }
        } catch (\Exception $e) {
            db()->rollback();
            return ['code'=>100,'msg'=>$e->message()];
        }

        db()->startTrans();
        try {
            $upKfData['photo'] = $photo;
            $upKfData['kf_account'] = $res['data']['kf_account'];
            db('crm_s_wx_kf_staff')->where('id',$kf_id)->update($upKfData);
            $paramImg['kf_account'] = $res['data']['kf_account'];
            $paramImg['media'] = $photo;
            $paramImg['access_token'] = $mc->getAccessToken(['shop_code'=>session('shop_code')]);
            // 成功之后，crm 上传头像
            $resImg = $this->getWxUploadheadimg($paramImg);
            if ($resImg['code']!=200) {
                db()->rollback();
                return $resImg;
            }else{
                db()->commit();
                return ['code'=>200,'msg'=>'成功'];
            }
        } catch (\Exception $e) {
            db()->rollback();
            return ['code'=>300,'msg'=>$e->message];
        }
    }
    /*
     *  上传客服头像(直接调取微信接口)
     */
    public function getWxUploadheadimg($params){
        if (!$params['kf_account']) {
            return array('code'=>100,'msg'=>'没有kf_account参数！');
        }
        if (!$params['media']) {
            return array('code'=>100,'msg'=>'没有media参数！');
        }
        if (!$params['access_token']) {
            return array('code'=>100,'msg'=>'没有access_token参数！');
        }

        // 上传客服头像
        $mediaUrl = "https://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?access_token=".$params['access_token']."&kf_account=".$params['kf_account'];
        // textlog('上传客服头像 $mediaUrl==》'.json_encode($mediaUrl));
        if(class_exists('\CURLFile')){  //7.0
            // $params['media'] = new \CURLFile( realpath($params['url']) );
            $fileData['media'] = new \CURLFile(ROOT_PATH.'public'.$params['media']);
        }else{  //5.6以及5.6以下
            $fileData['media'] = '@'.$params['media'];
        }
        // var_dump($params);
        // textlog('上传客服头像 $fileData==》'.json_encode($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);
        // textlog('上传客服头像返回==》'.json_encode($wxrs_id_card));
        if ($wxrs_id_card['errcode']!=0) {
            return ['code'=>199,'msg'=>'添加客服，绑定微信号成功，上传头像失败！'.$wxrs_id_card['errmsg']];
        }else{
            return ['code'=>200,'msg'=>'添加客服成功，请在客服微信确认！'.$wxrs_id_card['errmsg']];
        }
    }
    //修改客服人员
    public function editkf()
    {
        $param = input('post.');
        $param['brandclass_id'] = session('brandclass_id');
        $param['photo'] = imgToBase64(ROOT_PATH.DS.'public'.DS.$param['photo']);
        
        $mc = new \app\common\lib\mcInterface();
        
        return $mc->getWxEditkf($param);
    }

    //删除客服人员
    public function delkf()
    {
        $param = input('post.');
        $param['brandclass_id'] = session('brandclass_id');

        $mc = new \app\common\lib\mcInterface();
        return $mc->getWxDelkf($param);

    }
    /*---------- 客服人员管理 ------ end -------------------*/

    /*---------- 微信公众号配置 ------ start -------------------*/
    public function wxSetting()
    {
        return $this->fetch();
    }

    //增加公众号配置
    public function addwxSetting()
    {
        $param = input('post.');
        $data['name'] = trim($param['name']);
        $data['appid'] = trim($param['appid']);
        $data['secret'] = trim($param['secret']);
        $data['password'] = trim($param['password']);
        $data['wx_number'] = trim($param['wx_number']);
        $data['token'] = trim($param['token']);
        $data['staff_id'] = session('staff_id');
        $data['staff_name'] = session('staff_name');
        $data['create_time'] = date('Y-m-d H:i:s');
        $res = db('crm_s_wx_system')->where('appid', $data['appid'])->value('id');
        if ($res) {
            return array('code' => 99, 'msg' => 'appid重复，不可添加', 'data' => '');
        }
        db()->startTrans();
        try {
            db('crm_s_wx_system')->insert($data);
            db()->commit();
            return array('code' => 200, 'msg' => '公众号配置添加成功', 'data' => '');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 100, 'msg' => '公众号配置添加失败', 'data' => $e->getMessage());
        }
    }

    //修改公众号配置
    public function editwxSetting()
    {
        $param = input('post.');
        $data['id'] = intval($param['id']);
        $data['name'] = trim($param['name']);
        $res = db('crm_s_wx_system')->where('id', '<>', $data['id'])->where('name', $data['name'])->find();
        if (!empty($res)) {
            return array('code' => 101, 'msg' => '公众号名称重复', 'data' => '');
        }
        $data['appid'] = trim($param['appid']);
        $res = db('crm_s_wx_system')->where('id', '<>', $data['id'])->value('appid');
        if ($res) {
            return array('code' => 99, 'msg' => 'appid重复，不可修改', 'data' => '');
        }
        $data['secret'] = trim($param['secret']);
        $data['password'] = trim($param['password']);
        $data['wx_number'] = trim($param['wx_number']);
        $data['token'] = trim($param['token']);
        $data['staff_id'] = session('staff_id');
        $data['staff_name'] = session('staff_name');
        $data['update_time'] = date('Y-m-d H:i:s');
        db()->startTrans();
        try {
            db('crm_s_wx_system')->update($data);
            db()->commit();
            return array('code' => 200, 'msg' => '公众号配置修改成功', 'data' => '');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 100, 'msg' => '公众号配置修改失败', 'data' => $e->getMessage());
        }
    }

    //删除公众号配置
    public function delwxSetting()
    {
        $param = input('post.');
        $id = intval($param['id']);
        db()->startTrans();
        try {
            db('crm_s_wx_system')->where('id', $id)->delete();
            db()->commit();
            return array('code' => 200, 'msg' => '公众号配置删除成功', 'data' => '');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 100, 'msg' => '公众号配置删除失败', 'data' => $e->getMessage());
        }
    }

    public function wxSettingToJSON()
    {
        $param = input('post.');
        $name = $param['search_name'] ? trim($param['search_name']) : '';
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_wx_system')->where('name', 'like', '%' . $name . '%')->select();
        $count = db('crm_s_wx_system')->where('name', 'like', '%' . $name . '%')->count();
        if ($res) {
            $result['data'] = $res;
            $result['count'] = $count;
        } else {
            $result['data'] = array();
        }
        return ($result);
    }
    /*---------- 微信公众号配置 ------ start -------------------*/

    /*---------- 快捷回复设定 ------start-------------------*/
    public function replySetting()
    {
        $info = db('crm_s_reply_cat')->where('brandclass_id', session('brandclass_id'))->where('status', 2)->select();
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * @cc 添加回复分类
     * */
    public function addReplyCat()
    {
        $param = input();
        $id = db('crm_s_reply_cat')->where('brandclass_id', session('brandclass_id'))->where('status', 2)->where('reply_cat_name', $param['reply_cat_name'])->value('id');
        if ($id) {
            return array('code' => 100, 'msg' => '回复分类名称重复');
        }
        $data['reply_cat_name'] = trim($param['reply_cat_name']);
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');
        $log = '添加回复分类：' . $param['reply_cat_name'];
        db()->startTrans();
        try {
            $cid = db('crm_s_reply_cat')->insertGetId($data);
            action_log($log, '', 0, session('staff_id'), session('staff_name'));
            db()->commit();
            return array('code' => 200, 'msg' => '回复分类设置成功', 'id' => $cid);
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 110, 'msg' => '回复分类设置失败', 'data' => $e->getMessage());
        }
    }

    /**
     * @cc 修改回复分类
     * */
    public function editReplyCat()
    {
        $param = input();
        $id = db('crm_s_reply_cat')->where('brandclass_id', session('brandclass_id'))->where('status', 2)->where('reply_cat_name', $param['reply_cat_name'])->value('id');
        if ($id && $id != $param['id']) {
            return array('code' => 100, 'msg' => '回复分类名称重复');
        }
        $data['reply_cat_name'] = trim($param['reply_cat_name']);
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');
        db()->startTrans();
        try {
            $res = db('crm_s_reply_cat')->where('id', $param['id'])->update($data);
            if ($res) {
                $log = '修改回复分类：' . $param['reply_cat_name'];
                action_log($log, '', 0, session('staff_id'), session('staff_name'));
            }
            $cat = db('crm_s_reply_cat')->where('brandclass_id', session('brandclass_id'))->where('status', 2)->select();
            db()->commit();
            return array('code' => 200, 'msg' => '回复分类设置成功', 'cat' => $cat);
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 110, 'msg' => '回复分类设置失败', 'data' => $e->getMessage());
        }
    }

    public function getReplyCatJSON()
    {
        $param = input();
        $result['code'] = 0;
        $result['msg'] = '';
        if ($param['reply_cat_name']) {
            $result['count'] = db('crm_s_reply_cat')->where('brandclass_id', session('brandclass_id'))->where('reply_cat_name', 'like', '%' . $param['reply_cat_name'] . '%')->field('id,reply_cat_name')->where('status', 2)->order('id desc')->count();
            $result['data'] = db('crm_s_reply_cat')->where('brandclass_id', session('brandclass_id'))->where('reply_cat_name', 'like', '%' . $param['reply_cat_name'] . '%')->field('id,reply_cat_name')->where('status', 2)->order('id desc')->select();
        } else {
            $result['count'] = db('crm_s_reply_cat')->where('status', 2)->where('brandclass_id', session('brandclass_id'))->order('id desc')->count();
            $result['data'] = db('crm_s_reply_cat')->where('status', 2)->where('brandclass_id', session('brandclass_id'))->field('id,reply_cat_name')->order('id desc')->select();
        }
        return (($result));
    }

    public function getReplyJSON()
    {
        $param = input();
        $result['code'] = 0;
        $result['msg'] = '';
        $limit = $param['limit'] ? $param['limit'] : 10;
        $page = $param['page'] ? $param['page'] : 1;
        if ($param['reply_content']) {
            $result['count'] = db('crm_s_reply')->where('brandclass_id', session('brandclass_id'))->where('reply_content', 'like', '%' . $param['reply_content'] . '%')->where('is_delete', 2)->order('reply_cat_id desc')->count();
            $result['data'] = db('crm_s_reply')->where('brandclass_id', session('brandclass_id'))->where('reply_content', 'like', '%' . $param['reply_content'] . '%')->where('is_delete', 2)->order('reply_cat_id desc')->page($page)->limit($limit)->select();
        } else {
            $result['count'] = db('crm_s_reply')->where('is_delete', 2)->where('brandclass_id', session('brandclass_id'))->order('reply_cat_id desc')->count();
            $result['data'] = db('crm_s_reply')->where('is_delete', 2)->where('brandclass_id', session('brandclass_id'))->page($page)->limit($limit)->order('reply_cat_id desc')->select();
        }
        return (($result));
    }

    /**
     * @cc 删除回复分类
     * */
    public function delReplyCat()
    {
        $id = input('post.id');
        db()->startTrans();
        try {
            db('crm_s_reply_cat')->where('id', $id)->update(['status' => 1]);
            action_log('删除名称为：' . input('post.reply_cat_name') . '的回复分类', '', 0, session('staff_id'), session('staff_name'));
            db()->commit();
            return array('code' => 200, 'msg' => '回复分类删除成功');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 110, 'msg' => '回复分类删除失败', 'data' => $e->getMessage());
        }
    }

    /**
     * @cc 删除回复
     * */
    public function delReply()
    {
        $id = input('post.id');
        db()->startTrans();
        try {
            db('crm_s_reply')->where('id', $id)->update(['is_delete' => 1]);
            action_log('删除名称为：' . input('post.reply_content') . ' 的标签', '', 0, session('staff_id'), session('staff_name'));
            db()->commit();
            return array('code' => 200, 'msg' => '回复内容删除成功');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 110, 'msg' => '回复内容删除失败', 'data' => $e->getMessage());
        }
    }

    /**
     * @cc 添加回复内容
     * */
    public function addReplyName()
    {
        $param = input();
        $id = db('crm_s_reply')->where('brandclass_id', session('brandclass_id'))->where('is_delete', 2)->where('reply_content', $param['reply_content'])->value('id');
        if ($id) {
            return array('code' => 100, 'msg' => '回复内容重复');
        }
        $data['reply_cat_id'] = intval($param['reply_cat_id']);
        $data['reply_cat_name'] = trim($param['reply_cat_name']);
        $data['reply_content'] = trim($param['reply_content']);
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');
        $data['create_time'] = date('Y-m-d H:i:s');
        $log = '添加回复内容：' . $data['reply_cat_name'] . '=>' . $data['reply_content'];
        db()->startTrans();
        try {
            db('crm_s_reply')->insert($data);
            action_log($log, '', 0, session('staff_id'), session('staff_name'));
            db()->commit();
            return array('code' => 200, 'msg' => '回复内容设置成功');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 110, 'msg' => '回复内容设置失败', 'data' => $e->getMessage());
        }
    }

    /**
     * @cc 修改回复内容
     * */
    public function editReplyName()
    {
        $param = input();
        $id = db('crm_s_reply')->where('brandclass_id', session('brandclass_id'))->where('id', '<>', $param['id'])->where('is_delete', 2)->where('reply_content', $param['reply_content'])->value('id');
        if ($id && $id != $param['id']) {
            return array('code' => 100, 'msg' => '回复内容重复');
        }
        $data['reply_cat_id'] = intval($param['reply_cat_id']);
        $data['reply_cat_name'] = trim($param['reply_cat_name']);
        $data['reply_content'] = trim($param['reply_content']);
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');
        $data['update_time'] = date('Y-m-d H:i:s');
        db()->startTrans();
        try {
            $res = db('crm_s_reply')->where('id', $param['id'])->update($data);
            if ($res) {
                $log = '修改回复内容：' . $data['reply_cat_name'] . '=>' . $data['reply_content'];
                action_log($log, '', 0, session('staff_id'), session('staff_name'));
            }
            db()->commit();
            return array('code' => 200, 'msg' => '回复内容设置成功');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 110, 'msg' => '回复内容设置失败', 'data' => $e->getMessage());
        }
    }
    /*---------- 快捷回复设定 ------end-------------------*/

    /*----------- 微信会话列表 -------------start-----------*/
    public function wxTalkList(){
        $mc = new \app\common\lib\mcInterface();
        $shopInfo = $mc->getShopInfo(['shop_code'=>session('shop_code')]);
        
        $kfList = db('crm_s_wx_kf_staff')->alias('kf')
            ->join('crm_s_wx_system s','s.id=kf.belong_wx_id','left')
            ->where('s.appid',$shopInfo[0]['wx_appid'])->field('kf.*')->select();
        $this->assign('kfList', $kfList);
        //分配客服权限
        $this->assign('auth', check_right('menu1565071368'));
        return $this->fetch();
    }

    public function wxTalkListJSON(){
        $param = input('');
        $limit = $param['limit'];
        $page = $param['page'];
        // $name = $param['search_name'] ? trim($param['search_name']) : '';
        $result['code'] = 0;
        $result['msg'] = '';

        $mc = new \app\common\lib\mcInterface();
        $shopInfo = $mc->getShopInfo(['shop_code'=>session('shop_code')]);

        if (check_right('menu1564540006')) {
            $res = db('crm_s_wx_relation')->alias('r')
                ->join('crm_s_wx_kf_staff k', 'r.kf_id=k.id', 'left')
                ->join('crm_s_wx_system s','s.id=r.wx_sys_id','left')
                ->where('s.appid',$shopInfo[0]['wx_appid'])
                // ->where('r.subscribe', '1')
                ->field('r.id,r.subscribe,r.nickname,r.headimgurl,r.sex,r.subscribe_time,k.id as kf_id,k.staff_name,k.photo,r.update_time')
                ->group('r.openid')->order('r.update_time desc,r.id desc')
                ->page($page)->limit($limit)
                ->select();
            $listSql = db()->getLastSql();
            $data = [];
            foreach ($res as $key => $value) {
                $temp['id'] = $value['id'];
                $temp['nickname'] = $value['nickname'];
                $temp['headimgurl'] = $value['headimgurl'];
                $temp['type'] = $value['staff_name'] ? '老客' : '新客';
                $temp['channel_name'] = db('crm_s_wx_rchannel')->where('rid', $value['id'])->order('create_time desc')->value('channel_name');
                $temp['add_time'] = $value['subscribe_time'] ? date('Y-m-d H:i:s', $value['subscribe_time']) : '';
                $temp['update_time'] = $value['update_time'] ? date('Y-m-d H:i:s', strtotime($value['update_time']) ) : '';
                $temp['staff_name'] = $value['staff_name'];
                $temp['kf_id'] = $value['kf_id'];
                if ($value['subscribe']===0) {
                    $temp['subscribe'] = '已取关';
                }else{
                    $temp['subscribe'] = '已关注';
                }
                if ($value['sex'] == 0) {
                    $temp['sex'] = '未知';
                } elseif ($value['sex'] == 1) {
                    $temp['sex'] = '男';
                } elseif ($value['sex'] == 2) {
                    $temp['sex'] = '女';
                }
                // $temp['time'] = $value['time'];
                array_push($data, $temp);
                unset($temp);
            }

            $count = db('crm_s_wx_relation')->alias('r')
                ->join('crm_s_wx_kf_staff k', 'r.kf_id=k.id', 'left')
                ->join('crm_s_wx_system s','s.id=k.belong_wx_id','left')
                ->where('s.appid',$shopInfo[0]['wx_appid'])
                // ->where('r.subscribe', '1')
                ->group('r.openid')->count();
        } else if (check_right('menu1564539988')) { //个人
            $kf_id = db('crm_s_wx_kf_staff')->where('staff_id', session('staff_id'))->value('id');
            $res = db('crm_s_wx_relation')->alias('r')
                ->join('crm_s_wx_kf_staff k', 'r.kf_id=k.id', 'left')
                ->join('crm_s_wx_system s','s.id=r.wx_sys_id','left')
                ->where('s.appid',$shopInfo[0]['wx_appid'])
                // ->where('r.subscribe', '1')
                ->where('k.id', $kf_id)
                ->field('r.id,r.subscribe,r.nickname,r.headimgurl,r.sex,r.subscribe_time,k.id as kf_id,k.staff_name,k.photo,r.update_time')
                ->group('r.openid')->order('r.update_time desc desc,r.id desc')
                ->page($page)->limit($limit)
                ->select();
            $listSql = db()->getLastSql();
            $count = db('crm_s_wx_relation')->alias('r')
                ->join('crm_s_wx_kf_staff k', 'r.kf_id=k.id', 'left')
                ->join('crm_s_wx_system s','s.id=k.belong_wx_id','left')
                ->where('s.appid',$shopInfo[0]['wx_appid'])
                // ->where('r.subscribe', '1')
                ->where('k.id', $kf_id)
                ->group('r.openid')->count();
            $data = [];
            foreach ($res as $key => $value) {
                $temp['id'] = $value['id'];
                $temp['nickname'] = $value['nickname'];
                $temp['headimgurl'] = $value['headimgurl'];
                $temp['type'] = $value['staff_name'] ? '老客' : '新客';
                $temp['channel_name'] = db('crm_s_wx_rchannel')->where('rid', $value['id'])->order('create_time desc')->value('channel_name');
                $temp['add_time'] = $value['subscribe_time'] ? date('Y-m-d H:i:s', $value['subscribe_time']) : '';
                $temp['update_time'] = $value['update_time'] ? date('Y-m-d H:i:s', strtotime($value['update_time']) ) : '';
                $temp['staff_name'] = $value['staff_name'];
                $temp['kf_id'] = $value['kf_id'];
                if ($value['sex'] == 0) {
                    $temp['sex'] = '未知';
                } elseif ($value['sex'] == 1) {
                    $temp['sex'] = '男';
                } elseif ($value['sex'] == 2) {
                    $temp['sex'] = '女';
                }
                // $temp['time'] = $value['time'];
                array_push($data, $temp);
                unset($temp);
            }
        } else {
            $this->redirect('/');
        }
        // echo db()->getLastSql();die;
        if ($data) {
            $result['data'] = $data;
            $result['count']= $count;
        } else {
            $result['data'] = array();
            $result['count']= 0;
        }
        $result['sql'] = $listSql;
        return ($result);
    }

    // 分配客服
    public function allotKf()
    {
        if (!check_right('menu1565071368')) {
            $dat = ["code"=>100,"msg"=>"您没有此操作权限"];
        }else{
            $param = input('');
            $rid = (int)$param['id'];
            $kf_id = (int)$param['kf_id'];
            try {
                db('crm_s_wx_relation')->where('id',$rid)->update(['kf_id'=>$kf_id]);
                $dat['code']=200;
                $dat['msg'] ='分配成功';
            } catch (\Exception $e) {
                $dat['code']=99;
                $dat['msg'] =$e->getMessage();
            }
            // $mc = new \app\common\lib\mcInterface();
            // $dat = $mc->getWxAllotKf($param);
        }

        return json($dat);
    }

    // 会话 页面
    public function kfTalk(){
        $param = input();

        $id = (int)$param['id'];
        $info = db('crm_s_wx_relation')->where('id',$id)->find();
        if (!$info) {
            return json_encode(['code'=>99,'msg'=>'获取客户信息失败','sql'=>db()->getLastSql()]);
            die;
        }
        $wxParam['table_name'] = 'crm_s_wx_talk_'.strtolower(substr($info['openid'],-1));
        $res = controller("weixin/weixin","lib")->checkTalkTable($wxParam);
        if ($res['code']!=200) {
            return json_encode($res);
            die;
        }
        // 当前页面的会话历史 即 左侧 历史会话记录
        $talkList = $param['talkList'] ? json_decode($param['talkList'],true) : [];
        $talkList = array_unique($talkList);
        $leftList = db('crm_s_wx_relation')->where('id','in',$talkList)->where('id','<>',$id)->select();
        array_unshift($leftList, $info);
        $listenArr = [];
        foreach ($leftList as $key => $value) {
            $listenTemp['openid'] = $value['openid'];
            $listenTemp['tid'] = db('crm_s_wx_talk_'.strtolower(substr($value['openid'],-1)))->where('openid',$value['openid'])->max('id');
            array_push($listenArr, $listenTemp);
        }
        $this->assign('listenArr', json_encode($listenArr) );
        $this->assign('users', $leftList);
        $this->assign('kf_id', $info['kf_id']);
        $this->assign('limg',db('crm_s_wx_kf_staff')->where('id',$info['kf_id'])->value('photo'));
        // 获取第一个客户的聊天记录
        $firstTalk = $this->getTalkByOpenid(array('openid' => $info['openid']));
        $this->assign('firstTalk', $firstTalk);
        $tid = end(array_column($firstTalk, 'id'));
        $this->assign('tid', $tid);

        // 右侧 1 快捷回复
        $temp = db('crm_s_reply_cat')->alias('c')
            ->join('crm_s_reply r', 'c.id=r.reply_cat_id', 'left')
            ->where('r.is_delete', 2)
            ->where('r.brandclass_id', session('brandclass_id'))
            ->field('c.id,r.id as rid,r.reply_cat_name,r.reply_content')
            ->select();
        $answer = [];
        foreach ($temp as $key => $value) {
            $answer[$value['id']]['name'] = $value['reply_cat_name'];
            $answer[$value['id']]['son'][] = $value;
        }
        // var_dump($answer);die;
        $this->assign('answer', $answer);
        // 渠道
        $channel = controller("crm/Customer", "lib")->getChannel();
        $this->assign("channel", $channel);
        //默认渠道
        $this->assign('channel_name', $param['channel_name']);
        // 宝宝性别
        $baby_sex = config('baby_sex');
        if (empty($baby_sex)) {
            $baby_sex = [
                ['sex' => '男',],
                ['sex' => '女',],
            ];
        }
        $this->assign('baby_sex', $baby_sex);
        //省
        $province = controller('crm/Customer', 'lib')->address(['type' => 1, 'shop_code' => session('shop_code')]);
        $this->assign("province", $province);
        // 右侧 2 客资信息
        if ($info['cid']) {
            $cInfo = db('crm_c_customerinfo')
                ->where('id', $info['cid'])->where('is_status', 1)
                ->field('id,customer_name,customer_tel,customer_wechat,customer_channel_id,customer_channel,ready_baby_day,baby_birthday,baby_name,baby_sex,province_id,province,city_id,city,county_id,county,customer_address')
                ->find();
        } else {
            $cInfo = [];
        }
        $mc = new \app\common\lib\mcInterface();
        $this->assign('tupian_arr',$mc->getWxTupian());
        $this->assign('cInfo', $cInfo);
        return $this->fetch();
    }

    // 发送消息
    public function wxkfTalk(){
        $params = input();
        // var_dump($params);die;
        $rid = (int)$params['rid'];
        if (!$rid) {
            return array('code'=>99,'msg'=>'没有id参数！','data'=>json_encode($params));
        }
        $msg = trim($params['msg']);
        if (!$msg) {
            return array('code'=>99,'msg'=>'没有发送信息！','data'=>json_encode($params));
        }

        // 处理 消息内容 
        $msg = trim($params['msg']);
        $msg = save_clips_to_file($msg,'wx/pic/'.date('Ymd',time()));
        // textlog('发送消息 save_clips_to_file==》'.json_encode($msg));
        $msgArr = [];   
        preg_match_all('/<\s*img\s+[^>]*>/i',$msg, $msgArr);
        // textlog('发送消息 preg_match_all==》'.json_encode($msgArr));
        $imgArr = [];
        foreach ($msgArr[0] as $key => $value) {
            /*preg_match('/<img[\s\S]*?msg\s*=\s*[\"|\'](.*?)[\"|\'][\s\S]*?>/', $value, $emojiArr);*/
            preg_match('/<img[\s\S]*?type\s*=\s*[\"|\'](.*?)[\"|\'][\s\S]*?>/', $value, $typeArr);
            //textlog('发送消息 $typeArr==》'.json_encode($typeArr));
            if ($typeArr[1]=='emoji') {
                preg_match('/<img[\s\S]*?msg\s*=\s*[\"|\'](.*?)[\"|\'][\s\S]*?>/', $value, $emojiArr);
                $emoji = trim($emojiArr[1],'"');
                $msg = str_replace($value, $emoji, $msg);
            }else if ($typeArr[1]=='image') {
                preg_match('/<img[\s\S]*?mid\s*=\s*[\"|\'](.*?)[\"|\'][\s\S]*?>/', $value, $imageArr);
                /*preg_match('/<img[\s\S]*?src\s*=\s*[\"|\'](.*?)[\"|\'][\s\S]*?>/', $value, $srcArr);*/
                $mid = trim($imageArr[1],'"');
                // 资源图片
                $temp['type'] = 'image';
                $temp['media_id'] = $mid;
                $temp['url'] = $value;
                array_push($imgArr, $temp);
                $msg = str_replace($value, '', $msg);
            }else{
                preg_match('/<img[\s\S]*?src\s*=\s*[\"|\'](.*?)[\"|\'][\s\S]*?>/', $value, $srcArr);
                // 本地图片
                $temp['type'] = 'img';
                $temp['media_id'] = '';
                $temp['output'] = $value;
                $temp['url'] = $srcArr['1'];
                array_push($imgArr, $temp);
                $msg = str_replace($value, '', $msg);
            }
        }
        $msg = strip_tags($msg);
        $time = date('Y-m-d H:i:s');
        // var_dump($msg);
        // var_dump($imgArr);
        // die;
        // 实例化MC类
        $mc = new \app\common\lib\mcInterface();
        // 查询客户信息
        $info = db('crm_s_wx_relation')->alias('r')
            ->join('crm_s_wx_kf_staff k', 'k.id=r.kf_id', 'left')
            ->where('r.id', $rid)
            ->field('r.openid,k.id as kid,k.kf_account')
            ->find();
        // 生成会话表
        $table_name = 'crm_s_wx_talk_'.strtolower(substr($info['openid'],-1));
        // 赋值mc接口必须参数
        $talkParam['openid'] = $info['openid'];
        $talkParam['brandclass_id'] = session('brandclass_id');
        $talkParam['kid']   = $info['kid'];
        $talkParam['kf_account'] = $info['kf_account'];
        // 纯文本消息或者emoji表情
        if ($msg) {
            // 保存发送的消息(文本)
            $inTalk['openid']  = $info['openid'];
            $inTalk['opercode']= '2002';
            $inTalk['type']    = 'text';
            $inTalk['text']    = $msg;
            $inTalk['time']    = $time;
            $inTalk['kf_id']   = $info['kid'];
            $inTalk['status']  = 1;
            db()->startTrans();
            try {
                $max_id = db($table_name)->insertGetId($inTalk);
                db('crm_s_wx_relation')->where('id',$rid)->update(['update_time'=>$time,'last_word'=>$msg]);
                // 调mc接口
                $talkParam['type']= 'text';
                $talkParam['msg'] = $msg;
                $res = $mc->getWxKfTalk($talkParam);
                // var_dump($res);die;
                if ($res['code']!=200) {
                    db()->rollback();
                    return $res;
                }
                // $inTalk['id'] = $res['id'];
                
                db()->commit();
                // return ['code'=>200,'msg'=>'操作成功','data'=>$res];
            } catch (\Exception $e) {
                db()->rollback();
                return ['code'=>99,'msg'=>'操作失败：'.$e->getMessage()];
            }
        }
        // 20200916
        $access_token = $mc->getAccessToken(['shop_code'=>session('shop_code')]);
        // 是否存在图片消息
        if (!empty($imgArr)) {
            db('crm_s_wx_relation')->where('id',$rid)->update(['update_time'=>$time,'last_word'=>'[图片]']);
            foreach ($imgArr as $key => $value) {
                // var_dump($value);die;
                if (!$value['media_id']) {
                    $mediaParam['access_token'] = $access_token;
                    $mediaParam['media_url'] = $value['url'];
                    $mediaParam['type'] = 'image';
                    // 上传临时素材
                    $mediaReturn = controller("weixin/weixin","lib")->getWxSendTemporaryMaterial($mediaParam);
                    // 临时素材上传失败 
                    if ($mediaReturn['code']!=200) {
                        return $mediaReturn;
                    }
                    $media_id = $mediaReturn['data']['media_id'];
                    $inTalk['type_supply']  = 'temp';
                }else{
                    $media_id = $value['media_id'];
                    $inTalk['type_supply']  = 'ever';
                }
                $inTalk['openid']  = $info['openid'];
                $inTalk['opercode']= '2002';
                $inTalk['type']    = 'image';
                $inTalk['text']    = $media_id;
                $inTalk['time']    = $time;
                $inTalk['kf_id']   = $info['kid'];
                $inTalk['status']  = 1;
                db()->startTrans();
                try {
                    $max_id = db($table_name)->insertGetId($inTalk);
                    // var_dump($max_id);die;
                    // 调mc接口
                    $talkParam['type']= 'image';
                    $talkParam['msg'] = $media_id;
                    $res = $mc->getWxKfTalk($talkParam);
                    if ($res['code']!=200) {
                        db()->rollback();
                        return $res;
                    }
                    db()->commit();
                } catch (\Exception $e) {
                    db()->rollback();
                    return ['code'=>99,'msg'=>'操作失败：'.$e->getMessage()];
                }
            }
            // return ['code'=>200,'msg'=>'操作成功','data'=>$res];
        }
        return ['code'=>200,'msg'=>'操作成功','max_id'=>$max_id,'data'=>$res];
    }
    /*
    // 根据客户openid 获取该客户的 聊天记录 客户切换，获取聊天记录
    public function getTalkByOpenid_mc($param = [])
    {
        if (empty($param)) {
            $param = input('post.');
        }
        $mc = new \app\common\lib\mcInterface();
        $data = $mc->getTalkByOpenid($param);
        $firstTalk = my_sort($data,"id");
        
        return $this->WxMsgTime($firstTalk);
    }
    */
    // 根据客户openid 获取该客户的 聊天记录 客户切换，获取聊天记录
    /**
     * 根据openid 及 最后一条消息（crm的talk表）id 获取新消息 聊天记录 客户切换，获取聊天记录
     * @param  openid    openid
     * @param  rid       客户id
     * @param  tid       对应 openid 的最大消息id
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getTalkByOpenid($param = []) {
        if (empty($param)) {
            $param = input('post.');
        }
        if (!$param['openid'] && $param['rid']) {
            // 客户的基本信息
            $rInfo = db('crm_s_wx_relation')->where('id', $param['rid'])->find();
            $openid = $rInfo['openid'];
        } else {
            $openid = $param['openid'];
            // 客户的基本信息
            $rInfo = db('crm_s_wx_relation')->where('openid', $openid)->find();
        }
        db('crm_s_wx_relation')->where('openid', $openid)->update(['new_msg_num'=>0]);
        if ((int)$param['tid']) {
            $where['t.id'] = ['>',(int)$param['tid']];
        }
        $where['t.openid'] = $openid;
        $limit = $param['limit'] ? $param['limit'] : 20;
        $page = $param['page'] ? $param['page'] : 1;
        // 客户和客服的聊天记录
        $table_name = 'crm_s_wx_talk_'.strtolower(substr($openid,-1));
        $temp = db($table_name)->alias('t')
            ->join('crm_s_wx_kf_staff s', 't.kf_id=s.id', 'left')
            ->where($where)
            ->page($page)->limit($limit)
            ->order('t.time desc')
            ->field('t.*,s.photo')
            ->select();
        $talk = array_reverse($temp);
        $mc = new \app\common\lib\mcInterface();
        $access_token = $mc->getAccessToken(['shop_code'=>session('shop_code')]);
        foreach ($talk as $key => $value) {
            if ($value['type'] == 'image') {
                // 临时资源 
                if ($value['type_supply']=='temp') {
                    $talk[$key]['text'] = "<img src='https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$value['text']."' alt='' />";
                }else if ($value['type_supply']=='ever') {
                    if (!file_exists(ROOT_PATH.'public'.DS.'wx'.DS.'resource'.DS.$value['text'].'.jpg')) {
                        $getSourceUrl = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$access_token."";
                        $sendPost['media_id'] = $value['text'];
                        $sourceInfo = http_request($getSourceUrl, 'POST', json_encode($sendPost, JSON_UNESCAPED_UNICODE));
                        file_put_contents(ROOT_PATH.'public'.DS.'wx'.DS.'resource'.DS.$value['text'].'.jpg',$sourceInfo['response']);
                    }
                    $talk[$key]['text'] = '<img src="/wx/resource/'.$value['text'].'.jpg" />';
                }else{
                    $talk[$key]['text'] = "<img src='https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$value['text']."' alt='' />";
                }
            }else if ($value['type'] == 'voice') {
                $talk[$key]['text'] = ' <span style="background: url(\'/wx/img/wx_voice.png\')" data="/weixin/weixin/wxVoice?tid='.$value['id'].'&tname='.strtolower(substr($openid,-1)).'" onclick="amrPlay($(this))">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="display:none">0.00</span>';
            }else if ($value['type'] == 'video') {
                $talk[$key]['text'] = "<video controls muted='true'> <source src='https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$value['text']."' type='video/mp4'> </video>";
            }else if ($value['type'] == 'text') {
                $talk[$key]['text'] = controller("weixin/weixin","lib")->changeTextEmoji($value);
            }else{
                $talk[$key]['text'] = $value['text'];
            }
        }
        // var_dump($talk);
        // die;
        foreach ($talk as $key => $value) {
            $talk[0]['page'] = $page;
            $talk[$key]['subscribe'] = $rInfo['subscribe'];
            $talk[$key]['headimgurl'] = $rInfo['headimgurl'];
        }
        return $talk;
    }
    
    public function wxVoice(){
        $tid = input('tid');
        $table_name = 'crm_s_wx_talk_'.input('tname');
        // $
        $info = db($table_name)->alias('t')
            ->join('crm_s_wx_relation r','r.openid=t.openid','left')
            ->join('crm_s_wx_system s','r.wx_sys_id=s.id','left')
            ->where('t.id',$tid)
            ->field('t.text,s.appid')->find();
        // echo 11;
        $media_id = $info['text'];        
        $mc = new \app\common\lib\mcInterface();
        $access_token = $mc->getAccessToken(['wx_appid'=>$info['appid']]);
        // var_dump($access_token);die;
        $voiceUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$media_id;
        Response::create(file_get_contents($voiceUrl),'',200,['Content-Type'=>'audio/amr'])->send();
        die;
    }
    //获取最新消息
    public function getNewMsg(){
        $data = input('post.');

        $mc = new \app\common\lib\mcInterface();
        $res = $mc->getWxNewMsg($data);
        foreach ($res['is_new'] as $key => $value) {
            $res['is_new'][$key]['text'] = msubstr(preg_replace("/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i"," ",DeleteHtml($value['text'])),0,7);
        }
        foreach ($res['talk'] as $key => $value) {
            $res['talk'][$key]['texts'] = msubstr(preg_replace("/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i"," ",DeleteHtml($value['text'])),0,7);
        }

        // $rInfo = db('crm_s_wx_relation')->where('id', $data['rid'])->find();
        // $talk = db('crm_s_wx_talk')->alias('t')
        //     ->join('crm_s_wx_kf_staff s', 't.kf_id=s.id', 'left')
        //     ->where('t.openid', $rInfo['openid'])
        //     ->where('t.id', '>', $data['tid'])
        //     ->field('t.*,s.photo')
        //     ->select();
        // $sql = db()->getLastSql();
        // foreach ($talk as $key => $value) {
        //     $talk[$key]['subscribe'] = $rInfo['subscribe'];
        //     $talk[$key]['headimgurl'] = $rInfo['headimgurl'];

        //     $talk[$key]['text'] = $this->getWxBiaoqingTupian($value['text']);
        // }
        // $opids = db('crm_s_wx_relation')->where('kf_id', $data['kf_id'])->where('openid', '<>', $rInfo['openid'])->column('openid');

        // $is_new = db('crm_s_wx_talk')->alias('t')
        //     ->join('crm_s_wx_kf_staff s', 't.kf_id=s.id', 'left')
        //     ->join('crm_s_wx_relation r', 'r.openid=t.openid', 'left')
        //     ->where('t.openid', 'in', $opids)
        //     ->where('t.time', '>', date('Y-m-d H:i:s'))
        //     ->field('t.id as tid,r.id as rid,count(t.id)as num')->select();
        // // ->column('count(t.id)as num,t.id','r.id');
        // $sql2 = db()->getLastSql();
        return array('code' => 200, 'data' => $res['talk'], 'is_new' => $res['is_new'], 'sql' => $res['sql'], 'sql2' => $res['sql2']);
    }
    //更新已读消息
    // public function getUpdateMsg()
    // {
    //     $data = input('post.');
        
    //     $mc = new \app\common\lib\mcInterface();
    //     return $mc->getUpdateMsg($data);
    // }
    // 更新客户消息为已读
    public function setTalkRead(){
        $param = input();
        $rid = (int)$param['rid'];
        if ($rid) {
            $openid = db('crm_s_wx_relation')->where('id',$rid)->value('openid');
            $table_name = 'crm_s_wx_talk_'.strtolower(substr($openid,-1));
            db($table_name)->where('openid',$openid)->where('status',0)->update(['status'=>1]);
        }
    }
    // 根据openid 监听 广播
    public function openidSubscribe(){
        $param = input('');
        $openid = $param['openid'];
        if (!$openid) {
            return ['code'=>100,'msg'=>'openid获取失败'];
        }
        $message = [];
        $tid = (int)$param['tid'];
        // 更新最新的 tid
        cache('new_wx_tid_'.$openid,$tid);
        // var_dump($param);die;
        $newMessage = $this->getTalkByOpenid(['openid'=>$openid,'tid'=>$tid]);
        if (count($newMessage['data'])>0) {
            $message = $newMessage;
        }else{
            try {
                // 监听广播
                redisQueue::init()->subscribe(['wx_get_msg_by_openid_'.$openid], 'wxGetMsgByOpenid');
            } catch (\Exception $e) {
                $message = ['error'=>1,'msg'=>$e->getMessage()];
            }
            // return $message;
        }
        
        // die;
        return $message;
    }
    
    /*----------- 微信会话列表 ------------- end -----------*/
    /*-------------会话配置-----start-----------*/
    public function talkSetting() {
        if (request()->isAjax()) {
            $data = input('post.');
            $res = db_config('wx_talk_remind_staffids', $data['staff_id']);
            if ($res) {
                return array('code' => 200, 'msg' => '新客户通知配置成功');
            } else {
                return array('code' => 100, 'msg' => '新客户通知配置失败');
            }
        } else {
            $staff = getShopStaffs(['shop_code' => session('shop_code')]);
            $this->assign('staff', $staff);
            $staff_id = db_config('wx_talk_remind_staffids');
            $this->assign('staff_id', explode(',', $staff_id));

            $this->assign('menu', json_encode([]));            
            return $this->fetch();
        }
    }
    /*-------------会话配置-----end-----------*/
    /*------------- 生成渠道二维码 ----- start -----------*/
    // 页面
    public function getChannelQrcode()
    {
        $auth = check_right('menu1571816729');
        if (!$auth) {
            $return = array('error' => '1', 'msg' => '您没有生成渠道二维码，请先设置权限');
            return json($return);
            exit;
        }
        return $this->fetch();
    }

    // 渠道二维码数据
    public function getChannelQrcodeJson()
    {
        $auth = check_right('menu1571816729');
        if (!$auth) {
            $return = array('error' => '1', 'msg' => '您没有生成渠道二维码，请先设置权限');
            return json($return);
            exit;
        }
        $result['count'] = 0;
        $result['code'] = 0;
        $result['msg'] = '';
        $channel = controller("crm/Customer", "lib")->getChannel();

        $count = count($channel);
        if ($channel) {
            $result['data'] = $channel;
            $result['count'] = $count;
        } else {
            $result['data'] = array();
        }
        return ($result);
    }

    // 生成绑定的二维码
    public function getQrcode()
    {
        $data = input();
        $channel_id = $data['cid'];
        $keyword_id = $data['kid'];
        // $wx = db('crm_s_wx_system')->find();
        // if (!$wx) {
        //     $return['code'] = 100;
        //     $return['msg'] = '未获取到微信设定，请确认';
        //     return $return;
        // }
        // $mc = new \app\common\lib\mcInterface();
        // $access_token = $mc->getAccessToken($wx['appid'], $wx['secret'], 0);
        // if (!$access_token) {
        //     $return['code'] = 101;
        //     $return['msg'] = '未获取到微信access_token，检查secret和微信ip白名单，请联系管理员';
        //     $return['data'] = json_encode($wx);
        //     return $return;
        // }
        $scene_str = '';

        if (!$channel_id) {
            $return['code'] = 102;
            $return['msg'] = '未获取到渠道信息，请确认。';
            return $return;
        } else {
            $scene_str .= $channel_id;
        }
        $table = 'crm_s_channel';
        $where['id'] = $channel_id;
        $file_name = $channel_id . '.png';
        $upChannel['channel_qrcode'] = '/channelqr/' . $file_name;
        if ($keyword_id) {
            $scene_str .= ',' . $keyword_id;

            $table = 'crm_s_channel_keywords';
            $where['id'] = $keyword_id;

            $file_name = $channel_id . '_' . $keyword_id . '.png';

            $upChannel['channel_qrcode'] = '/channelqr/' . $file_name;
        }

        $params['scene_str'] = $scene_str;
        $params['brandclass_id'] = session('brandclass_id');
        // $params['file_name'] = $file_name;

        $mc = new \app\common\lib\mcInterface($params);
        $info = $mc->getWxQRorder($params);

        if ($info['code'] == 100) {
            return $info;
        }
        if ($info['errcode'] > 0) {
            $return['code'] = 102;
            $return['msg'] = '生成二维码失败，请重试！';
            $return['data'] = json_encode($info);
            return $return;
        }
        if ($table == 'crm_s_channel_keywords') {
            $upChannel['valid_date'] = date('Y-m-d H:i:s', time() + $info['expire_seconds']);
        }

        $upChannel['channel_qrcode'] = $info['urls'];

        $res = db($table)->where($where)->update($upChannel);
        if ($res === false) {
            $return['code'] = 103;
            $return['msg'] = '生成二维码失败，请重试！';
            $return['data'] = db()->getLastSql();
        } else {
            $return['code'] = 200;
            $return['msg'] = '生成二维码成功！';
            $return['data'] = '';
        }
        return $return;
    }

    //关键字
    public function channel_keywords()
    {
        $id = input('id');
        $this->assign('channel_id', $id);
        return $this->fetch();
    }

    public function channelKeywordsJSON()
    {
        $data = input();
        $result['code'] = 0;
        $result['msg'] = '';
        $limit = $data['limit'] ? $data['limit'] : 10;
        $page = $data['page'] ? $data['page'] : 1;
        $where['is_delete'] = 2;
        $where['channel_id'] = $data['channel_id'];
        if ($data['keyword']) {
            $where['keyword'] = ['like', '%' . trim($data['keyword']) . '%'];
        }
        $result['data'] = db('crm_s_channel_keywords')
            ->where($where)
            ->order('create_time desc')
            ->limit($limit)
            ->page($page)
            ->select();
        $result['count'] = db('crm_s_channel_keywords')
            ->where($where)
            ->order('create_time desc')
            ->count();
        return json($result);
    }

    /*
     * 添加关键字
     * */
    public function addKeyword()
    {
        $param = input();
        $where = [];

        if (empty($param['channel_id'])) {
            return array('code' => 100, 'msg' => '缺少渠道ID');
        } else {
            $where['channel_id'] = intval($param['channel_id']);
        }
        if (empty($param['keyword'])) {
            return array('code' => 101, 'msg' => '缺少关键字');
        } else {
            $where['keyword'] = trim($param['keyword']);
        }

        $res = db('crm_s_channel_keywords')->where($where)->where('shop_code', session('shop_code'))->value('id');
        if ($res) {
            return array('code' => 103, 'msg' => '已存在此关键字');
        }
        $channel_name = db('crm_s_channel')
            ->where('id', intval($param['channel_id']))
            ->where("find_in_set('" . session('shop_code') . "',share_shops)")
            ->value('channel_name');
        if (empty($channel_name)) {
            return array('code' => 104, 'msg' => '未发现此渠道', 'data' => db()->getLastSql());
        }
        $data['channel_id'] = intval($param['channel_id']);
        $data['channel_name'] = $channel_name;
        $data['staff_id'] = session('staff_id');
        $data['staff_name'] = session('staff_name');
        $data['shop_code'] = session('shop_code');
        $data['shop_name'] = session('shop_name');
        $data['create_time'] = date('Y-m-d H:i:s');
        $data['keyword'] = trim($param['keyword']);
        db()->startTrans();
        try {
            db('crm_s_channel_keywords')->insert($data);
            $log = '由 ' . session('staff_name') . ' 于 ' . $data['create_time'] . ' 添加关键字：' . $data['keyword'];
            action_log($log, []);
            db()->commit();
            return array('code' => 200, 'msg' => '添加成功');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 105, 'msg' => '添加失败', 'data' => $e->getMessage());
        }
    }

    /*
     * 删除关键字
     * */
    public function delKeyword()
    {
        $param = input();
        if (empty($param['id'])) {
            return array('code' => 100, 'msg' => '缺少关键字ID');
        }
        $info = db('crm_s_channel_keywords')->where('id', intval($param['id']))->find();
        if ($info['qrcode']) {
            return array('code' => 100, 'msg' => '已存在二维码，不能删除');
        }
        db()->startTrans();
        try {
            db('crm_s_channel_keywords')->where('id', intval($param['id']))->update(['is_delete' => 1]);
            $log = '由 ' . session('staff_name') . ' 于 ' . date('Y-m-d H:i:s') . ' 删除关键字：' . $info['keyword'];
            action_log($log, []);
            db()->commit();
            return array('code' => 200, 'msg' => '删除成功');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 105, 'msg' => '删除失败', 'data' => $e->getMessage());
        }
    }

    /*
     * 编辑关键字
     * */
    public function editKeyword()
    {
        $param = input();
        if (empty($param['id'])) {
            return array('code' => 100, 'msg' => '缺少关键字ID');
        }
        $where = [];
        if (empty($param['channel_id'])) {
            return array('code' => 100, 'msg' => '缺少渠道ID');
        } else {
            $where['channel_id'] = intval($param['channel_id']);
        }
        if (empty($param['keyword'])) {
            return array('code' => 101, 'msg' => '缺少关键字');
        } else {
            $where['keyword'] = trim($param['keyword']);
        }

        $res = db('crm_s_channel_keywords')->where($where)->where("shop_code", session('shop_code'))->where('id', '<>', intval($param['id']))->find();
        if ($res) {
            return array('code' => 103, 'msg' => '已存在此关键字');
        }
        $channel_name = db('crm_s_channel')
            ->where('id', intval($param['channel_id']))
            ->where("find_in_set('" . session('shop_code') . "',share_shops)")
            ->value('channel_name');
        if (empty($channel_name)) {
            return array('code' => 104, 'msg' => '未发现此渠道', 'data' => db()->getLastSql());
        }
        $data['keyword'] = trim($param['keyword']);
        $info = db('crm_s_channel_keywords')->where('id', intval($param['id']))->find();
        db()->startTrans();
        try {
            db('crm_s_channel_keywords')->where('id', intval($param['id']))->update($data);
            $log = '由 ' . session('staff_name') . ' 于 ' . date('Y-m-d H:i:s') . ' 编辑关键字：' . $info['keyword'] . '==>' . $data['keyword'];
            action_log($log, []);
            db()->commit();
            return array('code' => 200, 'msg' => '编辑成功');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code' => 105, 'msg' => '编辑失败', 'data' => $e->getMessage());
        }
    }
    /*------------- 生成渠道二维码 ----- start -----------*/
    /*------------- 录入客资时插入cid ----- start -----------*/
    public function addCid()
    {
        $param = input();
        if (empty($param['rid']) || empty($param['cid'])) {
            return array('code' => 50, 'msg' => '缺少参数');
        } else {
            db()->startTrans();
            try {
                db('crm_s_wx_relation')->where('id', $param['rid'])->update(['cid' => $param['cid']]);
                action_log('修改客户表id为' . $param['rid'] . '的客资id为：' . $param['cid'], [], $param['cid']);
                db()->commit();
                return array('code' => 200, 'msg' => '客资录入成功');
            } catch (\Exception $e) {
                db()->rollback();
                return array('code' => 100, 'msg' => '客资录入成功，客户表插入客资ID失败', 'data' => $e->getMessage());
            }
        }
    }
    /*------------- 录入客资时插入cid ----- end -----------*/
    /*----------------------自定义菜单-----start---------------*/
    /**
     * 把返回的数据集转换成Tree
     * @param $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param string $root
     * @return array
     */
    function listToTree($list, $pk='id', $pid = 'fid', $child = '_child', $root = '0') {
        $tree = array();
        if(is_array($list)) {
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] = &$list[$key];
            }
            foreach ($list as $key => $data) {
                $parentId =  $data[$pid];
                if ($root == $parentId) {
                    $tree[] = &$list[$key];
                }else{
                    if (isset($refer[$parentId])) {
                        $parent = &$refer[$parentId];
                        $parent[$child][] = &$list[$key];
                    }
                }
            }
        }
        return $tree;
    }

    function formatTree($list, $lv = 0, $title = 'name'){
        $formatTree = array();
        foreach($list as $key => $val){
            $title_prefix = '';
            for( $i=0;$i<$lv;$i++ ){
                $title_prefix .= "|---";
            }
            $val['lv'] = $lv;
            $val['namePrefix'] = $lv == 0 ? '' : $title_prefix;
            $val['showName'] = $lv == 0 ? $val[$title] : $title_prefix.$val[$title];
            if(!array_key_exists('_child', $val)){
                array_push($formatTree, $val);
            }else{
                $child = $val['_child'];
                unset($val['_child']);
                array_push($formatTree, $val);
                $middle = formatTree($child, $lv+1, $title); //进行下一层递归
                $formatTree = array_merge($formatTree, $middle);
            }
        }
        return $formatTree;
    }
    function getMenuJSON(){
        $param = input();
        $param['page'] = $param['page'] ? $param['page'] : 1;
        $param['limit'] = $param['limit'] ? $param['limit'] : 10;
        $param['brandclass_id'] = session('brandclass_id');

        $mc = new \app\common\lib\mcInterface();
        $result =  $mc->getWxMenu($param);

        return json($result);
    }

    //菜单数据列表
    function getMenuList()
    {
        $data = db('crm_s_wx_menu')->where('status','<>',99)->order('sort asc')->select();
        $res = $this->formatTree($this->listToTree($data));
        if ($res) {
            return $res;
        } else {
            return false;
        }
    }

    public function addMenuSet()
    {
        $id = input('get.id');

        $param['brandclass_id'] = session('brandclass_id');
        $param['id'] = $id;
        $mc = new \app\common\lib\mcInterface();
        $result =  $mc->getWxAddMenuSet($param);

        if ($id) {
            $detail = $result['detail'];
        }else{
            $detail['type'] = 'click';
            $detail['keyword'] = 'click';
        }
        $this->assign('detail', $detail);

        $this->assign('fList', $result['flist']);

        $this->assign('wx_public', $result['wx_public']);

        return $this->fetch();
    }

    public function addMenu()
    {
        $param = input();
        // var_dump($param);die;
        // 判断菜单类型
        if (!trim($param['type'])) {
            $return['code'] = 100;
            $return['msg']  = '请选择菜单类型';
            return $return;
        }else{
            if ( trim($param['type'])!='view' && trim($param['type'])!='click' && trim($param['type'])!='miniprogram' ) {
                $return['code'] = 101;
                $return['msg']  = '菜单类型错误，请确认';
                return $return;
            }
        }
        // 判断菜单名称
        if (!trim($param['name'])) {
            $return['code'] = 102;
            $return['msg']  = '请输入菜单名称';
            return $return;
        }
        // 判断菜单等级
        if (!(int)$param['level']) {
            $return['code'] = 103;
            $return['msg']  = '请选择菜单等级';
            return $return;
        }
        if ((int)$param['level']==2 && !(int)$param['fid']) {
            $return['code'] = 104;
            $return['msg']  = '请选择父级菜单';
            return $return;
        }
        // 判断回复内容
        if (trim($param['type'])=='view') {
            if (!trim($param['url'])) {
                $return['code'] = 105;
                $return['msg']  = '请输入跳转页面地址';
                return $return;
            }
        }else if (trim($param['type'])=='click') {
            if (trim($param['keyword'])!='view_limited' && trim($param['keyword'])!='media_id' && trim($param['keyword'])!='click') {
                $return['code'] = 106;
                $return['msg']  = '消息类型错误，请确认';
                return $return;
            }
            if ( trim($param['keyword'])=='view_limited' && !trim($param['media_id']) ) {
                $return['code'] = 107;
                $return['msg']  = '请选择图文消息';
                return $return;
            }else if (trim($param['keyword'])=='media_id' && !trim($param['media_id'])) {
                $return['code'] = 108;
                $return['msg']  = '请选择图片';
                return $return;
            }else if (trim($param['keyword'])=='click' && !trim($param['url'])) {
                $return['code'] = 108;
                $return['msg']  = '请输入文本内容';
                return $return;
            }
        }

        $mc = new \app\common\lib\mcInterface();
        $result =  $mc->getWxAddMenu($param);

        if ($result['code']==200) {
            $this->success($result['data']['msg'], '/');
        }elseif($result['code']==300){
            $this->error($result['data']['msg'], '/');
        }else{
            return $result;
        }
    }

    public function  delMenu()
    {
        $id = input('id');

        $mc = new \app\common\lib\mcInterface();
        $result =  $mc->getWxDelMenu(['id'=>$id]);

        if ($result['code']==200) {
            $this->success($result['msg'], '/');
        }elseif($result['code']==300){
            $this->error($result['msg'], '/');
        }else{
            return $result;
        }
    }

    /**
     * 调MC接口 将 微信 菜单推送给 微信公众号
     *
     * @author lilong<lilong@suxuantech.cn>
     */
    public function setmenutowx(){
        $data = input();
        
        if (empty($data['menu'])) {
            $returnData['code']= 100;
            $returnData['msg'] = '缺少设定菜单，请确认！';
            $returnData['data']= $data;
        }else{
            $menu = $data['menu'];
            foreach ($menu as $key => $value) {
                if ($value['type']=='click') {
                    // 图片
                    if ($v['keyword'] == 'media_id') {
                        $menu[$key]['keyword'] = 'media_id';
                    }
                    // 图文
                    else if ($v['keyword'] == 'view_limited') {
                        $menu[$key]['keyword'] = 'view_limited';
                    }
                    // 文本
                    else{
                        $menu[$key]['keyword'] = 'click';
                    }
                }
            }
            // $res = controller("weixin/weixin","lib")->dealWithMenu($menu);
            // var_dump($res);die;

            $param['brandclass_id'] = '';
            $param['shop_code'] = session('shop_code');
            $param['menu'] = json_encode($menu);
            // var_dump($param);die;
            $mc = new \app\common\lib\mcInterface();
            $result = $mc->setWxMenu($param);
            // 如果成功了，记录一个日志
            if ($result['code']==200) {
                history_log($param,[],0,session('staff_id'),session('staff_name'));
                $returnData['code']= 200;
                $returnData['msg'] = session('shop_name').'设定公众号号菜单成功';
                $returnData['data']= $result;
            }else{
                $returnData['code']= $result['code'];
                $returnData['msg'] = $result['msg'];
                $returnData['data']= $result;
            }
        }
        return $returnData;
    }

    /**
     * 方法描述  初始化微信菜单操作
     * @return mixed
     * @author lilong
     */
    public function setWxmenu(){
        $param['brandclass_id'] = session('brandclass_id');

        $mc = new \app\common\lib\mcInterface();
        $result =  $mc->getWxSetWxmenu($param);

        return json(['status'=>$result && $result['errmsg']=='ok'?1:$result['errcode'],'msg'=>$result['errmsg']]);
    }
    /*获取微信接口调用凭证access_token
         *
         */
    public function getAccessToken()
    {
        // $url = "5a603e4ea5c0c";
        // $data = [];
        // $res = sx_call($url, $data);
        // if ($res['code'] == 200) {
        //     $accessData = $res['data'];
        // }
        // return $accessData;
        $wxInfo = db('crm_s_wx_system')->find();
        $mc = new \app\common\lib\mcInterface();
        
        $accessParam['appid']  = $wxInfo['appid'];
        $accessParam['secret'] = $wxInfo['secret'];
        $access_token = $mc->getAccessToken($accessParam);
        $accessData['access_token'] = $access_token;
        return $accessData;
    }

    public function menuSet($content)
    {
        $accessTokenData = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $accessTokenData['access_token'];
        // var_dump($accessTokenData['access_token']);
        // var_dump($content);
        // die;
        $result = http_request($url, 'POST', $content);
        $res = json_decode($result['response'], true);
        return $res;
    }

    /*已定义菜单查询
     *@param String  $brandclass_id 品牌id
     */
    public function getMenu()
    {
        $accessTokenData = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token=' . $accessTokenData['access_token'];
        $result = http_request($url, 'GET');
        $res = json_decode($result['response'], true);
        return $res;
    }

    /*已定义菜单删除
     *@param String  $brandclass_id 品牌id
     */
    public function delWXMenu()
    {
        $accessTokenData = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=' . $accessTokenData['access_token'];
        $result = http_request($url, 'GET');
        $res = json_decode($result['response'], true);
        return $res;
    }
    /**
     * 获取素材列表
     * @param  offset     从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
     * @param  count      返回素材的数量，取值在1到20之间
     * @param  type       素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）
     * 
     * @return array  
     *
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getWxSource(){
        $param = input();
        $type = trim($param['type']);
        if (!$type) {
            $type = 'image';
        }
        $page = (int)$param['page'] ? (int)$param['page'] : 1;
        $count = 20;
        $offset= (($page-1)*$count)-1;
        if ($offset<0) {
            $offset=0;
        }

        $params['page']  = $page;
        $params['type']  = $type;
        $params['offset']= $offset;
        $params['count'] = $count;
        $params['brandclass_id'] = session('brandclass_id');

        $mc = new \app\common\lib\mcInterface();
        return $mc->getWxSource($params);
    }
    /*----------------------自定义菜单-----end---------------*/

    /*---------------------- 自动回复 ----- start ---------------*/
        /**
         * 自动回复列表
         *
         * @param  page       页码
         * @param  limit      单页数量 默认两百
         * @param  auto_name  自动回复的关键词或者规则名称
         * @param  
         * 
         * @return array  
         *
         * @author lilong<lilong@suxuantech.cn>
         */
        public function getAutoAnswerJson(){
            $result['msg']  = '';
            $result['code'] = 0;
            $result['count']= 0;
            $result['data'] = array();
            // 微信-会话配置权限
            $right = check_right('menu1565072157');
            if (!$right) {
                return json($result);
            }
            $param= input();

            $mc = new \app\common\lib\mcInterface();
            $res = $mc->getWxAutoAnswerList($param);
            $result['count']= $res['count'];
            $result['data'] = $res['data'];

            return json($result);
        }
        /**
         * 获取微信公众号自动回复
         *
         * @param  
         * 
         * @return array  
         *
         * @author lilong<lilong@suxuantech.cn>
         */
        public function geWxtAutoAnswer(){
            // 微信-会话配置权限
            $right = check_right('menu1565072157');
            if (!$right) {
                $result['code'] = 99;
                $result['msg']  = '没有微信‘会话配置’权限，请确认';
                $result['data'] = '';
                return json($result);
            }

            // $params['brandclass_id'] = session('brandclass_id');
            // $params['staff_id'] = session('staff_id');
            // $params['staff_name'] = session('staff_name');

            $mc = new \app\common\lib\mcInterface();
            $shopInfo = $mc->getShopInfo(['shop_code'=>session('shop_code')]);
            $params['wx_appid'] = $shopInfo['0']['wx_appid'];

            return $mc->geWxtAutoAnswer($params);
        }
        /*
         * 回复详情
         * @param id
         * */
        public function getAnswerDetail(){
            $id = input('id');

            $mc = new \app\common\lib\mcInterface();
            $info = $mc->getAnswerDetail(["id"=>$id]);

            $info['keywords'] = unserialize($info['keywords']);
            $info['contents'] = unserialize($info['contents']);

            return array('code'=>200,'data'=>$info);
        }
        /**
         * 新增/编辑 自动回复页面
         *
         * @param  aid  编辑时需要主键id
         * 
         * @return array  
         *
         * @author lilong<lilong@suxuantech.cn>
         */
        public function addAuto(){
            $param= input();
            $wxsysInfo = db('crm_s_wx_system')->select();
            $this->assign('wxsysInfo', $wxsysInfo);
            // 如果有answer id
            if ((int)$param['aid']) {
                $answerInfo = db('crm_s_wx_autoanswer')->where('id', (int)$param['aid'])->find();
                if ($answerInfo['auto_keyword']) {
                    $keyword = json_decode($answerInfo['auto_keyword']);
                    foreach ($keyword as $key => $value) {
                        $keyword[$key]['key_type'] = '';
                        $keyword[$key]['key_word'] = '';
                    }
                }
                $this->assign('answerInfo', $answerInfo);
            }
            return $this->fetch();
        }
        /**
         * 新增/编辑 自动回复 方法
         *
         * @param  aid  编辑时需要主键id
         * 
         * @return array  
         *
         * @author lilong<lilong@suxuantech.cn>
         */
        public function addAutoAction(){
            $param = input();
            $inData= [];
            // 微信公众号
            $wxsys = (int)trim($param['wxsys']);
            if (!$wxsys) {
                $return['code']= '99';
                $return['msg'] = '请选择微信公众号';
                $return['data']= $param['wxsys'];
                return $return;
            }else{
                $wxInfo = db('crm_s_wx_system')->where('id', $wxsys)->find();
                if (!$wxInfo) {
                    $return['code']= '100';
                    $return['msg'] = '请选择正确的微信公众号';
                    $return['data']= $param['wxsys'];
                    return $return;
                }else{
                    $inData['wxsys_id'] = $wxInfo['id'];
                    $inData['wxsys_name'] = $wxInfo['name'];
                    $inData['wxsys_appid'] = $wxInfo['appid'];
                }
            }
            // 回复分类
            $auto_type = (int)trim($param['auto_type']);
            if ($auto_type>3 || $auto_type<1) {
                $return['code']= '101';
                $return['msg'] = '请选择正确的回复分类';
                $return['data']= $param['auto_type'];
                return $return;
            }else{
                $inData['auto_type'] = $auto_type;
            }
            // 回复名称
            $auto_name = trim($param['auto_name']);
            if (!$auto_name) {
                $return['code']= '102';
                $return['msg'] = '请输入回复名称';
                $return['data']= $param['auto_name'];
                return $return;
            }else{
                $inData['auto_name'] = $auto_name;
            }
            // 关键词
            $keyword = $param['keyword'];
            if (!$keyword) {
                $return['code']= '103';
                $return['msg'] = '请输入关键词';
                $return['data']= $param['keyword'];
                return $return;
            }else{
                var_dump($keyword);
            }
            die;
            // 回复内容
            $auto_answer_type = (int)trim($param['auto_answer_type']);
            if ($auto_answer_type>5 || $auto_answer_type<1) {
                $return['code']= '105';
                $return['msg'] = '请选择正确的回复内容类型';
                $return['data']= $param['auto_answer_type'];
                return $return;
            }else{
                $inData['auto_answer_type'] = $auto_answer_type;
            }
            $auto_answer = trim($param['auto_answer']);
            if (!$auto_answer) {
                $return['code']= '106';
                $return['msg'] = '请输入回复内容';
                $return['data']= $param['auto_answer'];
                return $return;
            }else{
                $inData['auto_answer'] = $auto_answer;
            }
            $id = (int)$param['aid'];
            db()->startTrans();
            try {
                // // 编辑
                // if ($id) {
                    
                // }
                // // 新增
                // else{

                // }
                db()->commit();
                $return['code']= 200;
                $return['msg'] = '操作成功';
                $return['data']= '';
            } catch (\Exception $e) {
                db()->rollback();
                $return['code']= 201;
                $return['msg'] = '操作成功';
                $return['data']= $e->getMessage();
            }
            
            return $return;
        }
    public function getWxsendSystemMessage(){
        $param['id'] = db_config('wx_talk_id');

        $mc = new \app\common\lib\mcInterface();
        $res = $mc->getWxsendSystemMessage($param);
        textlog('获取微信 最新消息  res==》'.json_encode($res));
        $message['send_type']      = 1;
        $message['send_title']     = '会话提醒';
        $message['send_msg']       = '已有用户发来消息，请前去会话，<a href="/weixin/weixin/wxTalkList" target="_blank" style="color: red;">点击前去</a>';
        $message['customer_id']    = 0;
        $message['receive_status'] = 0;
        $message['operation_type'] = 2;
        $message['operation']      = [];
        $message['time_out']       = 240;

        if ($res[0]){
            foreach ($res as $key => $value) {
                if ($value['staff_id']) {
                    $message['receive_id']     = $value['staff_id'];
                    $message['receive_name']   = $value['staff_name'];
                    sendSystemMessage($message);
                }else{
                    $staff_id = db_config('wx_talk_remind_staffids');

                    $staffinfo = $mc->getStaffByIds($staff_id);
                    
                    // 给设定的管理员发送消息 （弹窗，带上会话列表的链接）
                    foreach($staffinfo as $key=>$val){
                        $message['receive_id']     = $val['id'];
                        $message['receive_name']   = $val['staffname'];
                        sendSystemMessage($message);
                    }
                }
                db_config('wx_talk_id',$value['id']);
            }

        }

    }


    //聊天记录 时间显示判断
    public function WxMsgTime($arr)
    {
        if ($arr) {
            $time = '';
            $t = date('Y-m-d'); 
            foreach ($arr as $key => $value) {
                if ($time) {
                    if (intval(strtotime($value['time']) - strtotime($time)) > 60) {
                        $arr[$key]['time_x'] = substr($value['time'],0,10) == $t ? date("H:i",strtotime($value['time'])) : date("Y年m月d日 H:i",strtotime($value['time']));
                    }
                }else{
                    $arr[$key]['time_x'] = substr($value['time'],0,10) == $t ? date("H:i",strtotime($value['time'])) : date("Y年m月d日 H:i",strtotime($value['time']));
                }
                $time = $value['time'];
            }
        }
        return $arr;
    }
    /*---------------------- 自动回复 ----- start ---------------*/
    // //微信表情
    // public function getWxBiaoQing()
    // {
    //     $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_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_72.png","[瓢虫]"=>"smiley_73.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"];
    //     return $tupian_arr;
    // }
    // //微信表情  字符串 转换成表情
    // public function getWxBiaoqingTupian($data)
    // {
    //     $tupian_arr = $this->getWxBiaoQing();

    //     preg_match_all ("/\[.*?\]/i", $data, $bq);
    //     if (count($bq[0]) > 0) {
    //         foreach ($bq[0] as $k => $v) {
    //             // print_r($tupian_arr[$v]);
    //             if ($tupian_arr[$v]) {
    //                 $data = str_replace($v,'<img style="width: 25px;" type="emoji" src="/wx/img/'.$tupian_arr[$v].'" msg="'.$v.'">',$data);
    //             }
    //         }
    //     }
    //     return $data;
    // }

}