<?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;
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();
        return $mc->getWxKfStaffToJSON($param);

        // $count = count($result);
        // if ($count) {
        //     foreach ($result as $key => $value) {
        //         # code...
        //     }
        // }else{
        //     $result['data'] = array();
        //     $result['count'] = 0;
        // }
    }

    // 客服列表页面
    public function kfStaffSystem()
    {
        $dep = getDepartments();
        $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.');
        $param['brandclass_id'] = session('brandclass_id');
        $param['photo'] = imgToBase64(ROOT_PATH.DS.'public'.DS.$param['photo']);

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

    }

    //修改客服人员
    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()
    {
        // $kfList = db('crm_s_wx_kf_staff')->select();

        $mc = new \app\common\lib\mcInterface();
        $kfList = $mc->getWxKfStaff();

        $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'] = '';

        //判断自身是否是管理员
        $work_type=explode(',',trim(session('main_work_type').','.session('work_type'),','));
        $positionDatas=controller('crm/Setting','lib')->get_position_list(array('position_code'=>session('main_position_code')));
        if($positionDatas[0]['work_type']==SYSTEM_AUTH_ADMIN || in_array(SYSTEM_AUTH_ADMIN,$work_type)){// menu1565071368 分配客服权限
            $gly = 1;
        }

        $mc = new \app\common\lib\mcInterface();
        if (check_right('menu1564540006') || $gly == 1) {
            $dat = $mc->wxTalkListJSON1($param);

            $res = $dat['res'];

            $count = $dat['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'] = date('y-m-d H:i', $value['subscribe_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);
            }

        } elseif (check_right('menu1564539988')) { //个人
            $param['staff_id'] = session('staff_id');
            $dat = $mc->wxTalkListJSON2($param);

            $res = $dat['res'];

            $count = $dat['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'] = date('y-m-d H:i', $value['subscribe_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('/');
        }


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

    // 分配客服
    public function allotKf()
    {
        if (!check_right('menu1565071368')) {
            $dat = ["code"=>100,"msg"=>"您们有此操作权限"];
        }else{
            $param = input('');

            $mc = new \app\common\lib\mcInterface();
            $dat = $mc->getWxAllotKf($param);
        }

        return json($dat);
    }

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

        $mc = new \app\common\lib\mcInterface();
        $dat = $mc->getKfTalk($param);
        $info = $dat['info'];
        $res = $dat['res'];

        array_unshift($res, $info);
        if (count($res) > 0) {
            foreach ($res as $key => $value) {
                $res[$key]['text'] = msubstr(preg_replace("/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i"," ",DeleteHtml($value['text'])),0,7);
            }
        }
        // var_dump($res);die;
        $this->assign('users', $res);
        $this->assign('kf_id', $info['kf_id']);
        // echo db()->getLastSql();
        // var_dump($res);die;

        // 获取第一个客户的聊天记录
        $firstTalk = $this->getTalkByOpenid(array('openid' => $res['0']['openid'],'brandclass_id' => session('brandclass_id')));

        $tid = end(array_column($firstTalk, 'id'));
        $this->assign('tid', $tid);

        $firstTalk = my_sort($firstTalk,"id");
        $firstTalk = $this->WxMsgTime($firstTalk);
        $this->assign('firstTalk', $firstTalk);

        // 右侧 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 = [];
        }

        $this->assign('tupian_arr',$mc->getWxTupian());

        $this->assign('cInfo', $cInfo);

        $max_msg_id = cache('max_msg_id') ? cache('max_msg_id') : 0;
        $this->assign('max_msg_id', $max_msg_id);
        return $this->fetch();
    }

    // 发送消息
    public function wxkfTalk()
    {
        $params = input();
        $params['brandclass_id'] = session('brandclass_id');

        $mc = new \app\common\lib\mcInterface();
        return $mc->getWxKfTalk($params);
    }

    // 根据客户openid 获取该客户的 聊天记录 客户切换，获取聊天记录
    public function getTalkByOpenid($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);
    }

    //获取最新消息
    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);
    }
    /*----------- 微信会话列表 ------------- 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;
        }
    }
    /**
     * 方法描述  初始化微信菜单操作
     * @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();
        $access_token = $mc->getAccessToken($wxInfo['appid'],$wxInfo['secret'],0);
        $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();
            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;
    // }

}