<?php
namespace app\admin\controller;

use app\admin\model\Office;
use think\cache\driver\Redis;

/**
 * 管理系统系统设置类
 */
class System extends Base
{


    /**
     * 基础设置
     *
     * @access public
     */
    public function basics()
    {
        // 表单提交.
        if (request()->isPost()) {
            $param = input('post.');

            try {
                // 修改系统欢迎语.
                if (empty($param['advertisement_img']) === false) {
                    $updateAstData['advertisement_img'] = $param['advertisement_img'];
                }

                if (empty($param['logo_img']) === false) {
                    $updateinfo['logo'] = $param['logo_img'];
                }
                $updateinfo['enterprise_name'] = $param['enterprise_name'];

                $updateAstData['advertisement_url']    = $param['advertisementUrl'];
                $updateAstData['advertisement_status'] = $param['status'];
                model('Advertisement')->updateAst($updateAstData);
                /*// 修改系统欢迎语.
                $updateSysData['word'] = $param['systemWord'];
                $updateSysWhere['id']  = 1;
                model('Reply')->updateReply($updateSysWhere, $updateSysData);*/
                // 修改客服欢迎语.
                $updateSevData['word'] = $param['serverWord'];
                $updateSevWhere['id']  = 2;
                model('Reply')->updateReply($updateSevWhere, $updateSevData);
                if(!empty($updateinfo)){
                    db('settings')->where('id',1)->update($updateinfo);
                }
                return json(['code' => 1, 'data' => '', 'msg' => '设置成功']);
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }//end try
        }//end if

        // 获取广告.
        $advertisement = model('Advertisement')->findAst();
        /*// 获取系统欢迎语.
        $replySystemWhere['id'] = 1;
        $replySystem            = model('Reply')->findReply($replySystemWhere);*/
        // 获取客服欢迎语.
        $replyServerWhere['id'] = 2;
        $replyServer            = model('Reply')->findReply($replyServerWhere);
        // 获取logo.
        $settings = db('settings')->find();
        $this->assign(
            [
                'advertisement' => $advertisement,
                //'replySystem'   => $replySystem,
                'replyServer'   => $replyServer,
                'settings'   => $settings,
                'status'        => config('kf_status'),
            ]
        );

        return $this->fetch();

    }//end basics()

    /**
     * 系统欢迎语
     *
     * @access public
     */
    public function welcoming()
    {
        if (request()->isAjax()) {
            $replySystemWhere['type'] = 1;
            $result                   = model('Reply')->selectReply($replySystemWhere);
            foreach($result as $key=>$vo){
                // 生成操作按钮
                $result[$key]['operate'] = $this->makeBotton($vo['id']);
                $result[$key]['word'] = htmlspecialchars_decode($vo['word']);
            }
            $return['rows'] = $result;
            return json($return);
        }

        return $this->fetch();

    }//end welcoming()

    /**
     * 修改系统欢迎语
     *
     * @access public
     */
    public function editWelcome()
    {
        if(request()->isAjax()){
            $param = input('post.');
            $where['id'] = $param['id'];
            $data['sort'] = $param['sort'];
            $data['word'] = htmlspecialchars($param['word']);

            try{
                model('Reply')->updateReply($where, $data);
            }catch(\Exception $e){
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '编辑成功']);
        }

        $id                     = input('param.id');
        $replySystemWhere['id'] = $id;
        $replySystem            = model('Reply')->findReply($replySystemWhere);

        $this->assign([
            'replySystem' => $replySystem,
        ]);
        return $this->fetch('editwelcome');

    }//end editWelcome()

    /**
     * 新增系统欢迎语
     *
     * @access public
     */
    public function delWelcome()
    {
        if (request()->isAjax()) {
            $id = input('param.id');
            $where['id'] = $id;

            try {
                model('Reply')->delReply($where);
            } catch (\Exception $e) {
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '删除成功']);
        }
    }

    /**
     * 新增系统欢迎语
     *
     * @access public
     */
    public function addWelcome()
    {
        if(request()->isAjax()){
            $param = input('post.');
            $data['sort'] = $param['sort'];
            $data['word'] = htmlspecialchars($param['word']);
            $data['status'] = 1;
            $data['type'] = 1;

            try{
                model('Reply')->addReply($data);
            }catch(\Exception $e){
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '新增成功']);
        }

        return $this->fetch('addwelcome');

    }//end addWelcome()


    /**
     * 会话设置
     *
     * @access public
     */
    public function conversation()
    {
        // 表单提交.
        if (request()->isPost()) {
            $param = input('post.');

            try {
                // 修改会话超时.
                $updateOvertimeData['systemconfig_data']    = $param['overtime'];
                $updateOvertimeData['systemconfig_content'] = $param['overtimeInfo'];
                $updateOvertimeWhere['systemconfig_id']     = 1;
                model('Systemconfig')->updateSystemconfig($updateOvertimeWhere, $updateOvertimeData);
                // 修改访客静默.
                $upUptdData['systemconfig_data']    = $param['unoperated'];
                $upUptdData['systemconfig_content'] = $param['unoperatedInfo'];
                $upUptdWhere['systemconfig_id']     = 2;
                model('Systemconfig')->updateSystemconfig($upUptdWhere, $upUptdData);
                // 质检会话时长设置.
                $upAllTimeData['systemconfig_data'] = $param['verifyAllTime'];
                $upAllTimeWhere['systemconfig_id']  = 3;
                model('Systemconfig')->updateSystemconfig($upAllTimeWhere, $upAllTimeData);
                // 质检会话响应时长设置.
                $upReturnTimeData['systemconfig_data'] = $param['verifyReturnTime'];
                $upReturnTimeWhere['systemconfig_id']  = 4;
                model('Systemconfig')->updateSystemconfig($upReturnTimeWhere, $upReturnTimeData);
                // 满意度评价回合限制.
                $upRoundData['systemconfig_data'] = $param['round'];
                $upRoundWhere['systemconfig_id']  = 5;
                model('Systemconfig')->updateSystemconfig($upRoundWhere, $upRoundData);
                // 客服接待人数设置.
                $upMSWhere['systemconfig_enName'] = 'KFMaxServices';
                $upMSData['systemconfig_data']    = $param['max_service'];
                model('Systemconfig')->updateSystemconfig($upMSWhere, $upMSData);
                // 最大排队人数设置.
                $upMWWhere['systemconfig_enName'] = 'maxWait';
                $upMWData['systemconfig_data']    = $param['kfConfig_maxWait'];
                model('Systemconfig')->updateSystemconfig($upMWWhere, $upMWData);

                return json(['code' => 1, 'data' => '', 'msg' => '设置成功']);
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }//end try
        }//end if

        // 获取设置.
        $systemconfig = model('Systemconfig')->selectSystemconfig();
        $this->assign(
            [
                'systemconfig' => $systemconfig,
                'status'       => config('kf_status'),
            ]
        );

        return $this->fetch();

    }//end conversation()


    // 自动回复设置
    public function reply()
    {
        if(request()->isPost()){

            $param = input('post.');
            if(empty($param['word'])){
                return json(['code' => -1, 'data' => '', 'msg' => '回复内容不能为空']);
            }

            try{
                db('reply')->where('id', 1)->update($param);
            }catch(\Exception $e){
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '设置成功']);
        }

        $info = db('reply')->where('id', 1)->find();
        $this->assign([
            'info' => $info,
            'status' => config('kf_status')
        ]);

        return $this->fetch();
    }

    // 历史会话记录
    public function wordsLog()
    {
//        $toExcel = input('param.toExcel', 0);

        if(request()->isAjax()){
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            // 默认显示最近7天
            $start = input('param.start');
            $end = input('param.end');

            $user_id = input('param.user_id');
            $group_id = input('param.group_id');
            $temp = db('service_log');
            $countTmp = db('service_log');
            if(strlen($param['searchText'])){
                $temp = $temp->whereLike('user_name', '%'.$param['searchText'].'%');
                $countTmp = $countTmp->whereLike('user_name', '%'.$param['searchText'].'%');
            }

            //日期
            if(!empty($start) && !empty($end) && $start <= $end){
                $temp = $temp->whereBetween('start_time', [strtotime($start), strtotime($end . ' 23:59:59')]);
                $countTmp = $countTmp->whereBetween('start_time', [strtotime($start), strtotime($end . ' 23:59:59')]);
            }
            //结束时间为空
            if(!empty($start) && empty($end)){
                $temp = $temp->where('start_time','>',strtotime($start));
                $countTmp = $countTmp->where('start_time','>',strtotime($start));
            }
            //开始时间为空
            if(empty($start) && !empty($end)){
                $temp = $temp->where('start_time','<',strtotime($end . ' 23:59:59'));
                $countTmp = $countTmp->where('start_time','<',strtotime($end . ' 23:59:59'));
            }

            //客服
            if($user_id != 0){
                $temp = $temp->where('kf_id', $user_id);
                $countTmp = $countTmp->where('kf_id', $user_id);
            }

            //客服组
            if($group_id != 0){
                $temp = $temp->where('group_id', $group_id);
                $countTmp = $countTmp->where('group_id', $group_id);
            }

            $result = $temp->limit($offset, $limit)->order('start_time', 'desc')->select();

            //所有客服
            $users = db('users')->select();
            //所有客服组
            $groups = db('groups')->select();
            //满意度
            $evaluate = db('evaluate')->select();
            //$alarm报警信息
            $alarm =  db('alarm')->select();
            foreach($result as $key=>$vo){
                if($result[$key]['intime'] != 0){
                    $result[$key]['intime'] = date('Y-m-d H:i:s', $vo['intime']);

                    $date = explode(' ',$result[$key]['intime']);
                    $year = explode('-',$result[$key]['intime']);
                    if($date[0] == date('Y-m-d',time())){
                        $result[$key]['intime'] = '<span style="float: right;">'.$date[1].'</span>';
                    }else if($date[0] == date('Y-m-d',strtotime("-1 day"))){
                        $result[$key]['intime'] = '<span style="float: right;">'.'昨天 '.$date[1].'</span>';
                    }else{
                        if($year[0] == date('Y',time())){
                            $result[$key]['intime'] = '<span style="float: right;">'.date('m-d H:i:s',strtotime($result[$key]['intime'])).'</span>';
                        }
                    }

                }else{
                    $result[$key]['intime'] = '-';
                }
                if($result[$key]['start_time'] != 0){
                    $result[$key]['start_time'] = date('Y-m-d H:i:s', $vo['start_time']);

                    $date = explode(' ',$result[$key]['start_time']);
                    $year = explode('-',$result[$key]['start_time']);
                    if($date[0] == date('Y-m-d',time())){
                        $result[$key]['start_time'] = '<span style="float: right;">'.$date[1].'</span>';
                    }else if($date[0] == date('Y-m-d',strtotime("-1 day"))){
                        $result[$key]['start_time'] = '<span style="float: right;">'.'昨天 '.$date[1].'</span>';
                    }else{
                        if($year[0] == date('Y',time())){
                            $result[$key]['start_time'] = '<span style="float: right;">'.date('m-d H:i:s',strtotime($result[$key]['start_time'])).'</span>';
                        }
                    }

                }else{
                    $result[$key]['start_time'] = '-';
                }
                if($result[$key]['end_time'] != 0){
                    $result[$key]['end_time'] = date('Y-m-d H:i:s', $vo['end_time']);

                    $date = explode(' ',$result[$key]['end_time']);
                    $year = explode('-',$result[$key]['end_time']);
                    if($date[0] == date('Y-m-d',time())){
                        $result[$key]['end_time'] = '<span style="float: right;">'.$date[1].'</span>';
                    }else if($date[0] == date('Y-m-d',strtotime("-1 day"))){
                        $result[$key]['end_time'] = '<span style="float: right;">'.'昨天 '.$date[1].'</span>';
                    }else{
                        if($year[0] == date('Y',time())){
                            $result[$key]['end_time'] = '<span style="float: right;">'.date('m-d H:i:s',strtotime($result[$key]['end_time'])).'</span>';
                        }
                    }

                }else{
                    $result[$key]['end_time'] = '-';
                }
                //客服名称
                for($i=0;$i<count($users);$i++){
                    if($result[$key]['kf_id'] == $users[$i]['id']){
                        $result[$key]['kefu_name'] = $users[$i]['user_name'];
                    }
                }

                //满意度
                for($j=0;$j<count($evaluate);$j++){
                    if($result[$key]['evaluate_id'] == $evaluate[$j]['evaluate_id']){
                        $result[$key]['evaluate_name'] = $evaluate[$j]['evaluate_name'];
                    }
                }

                //客服所在组
                for($a=0;$a<count($groups);$a++){
                    if($result[$key]['group_id'] == $groups[$a]['id']){
                        $result[$key]['group_name'] = $groups[$a]['name'];
                    }
                }

                //会话时长/响应时长
                for($b=0;$b<count($alarm);$b++){
                    if($result[$key]['servicelog_id'] == $alarm[$b]['servicelog_id']){
                        //会话时长
                        $conversation_min = intval($alarm[$b]['alarm_cvtOvertime']/60);
                        $conversation_s = $alarm[$b]['alarm_cvtOvertime']%60;
                        $result[$key]['conversation'] = $conversation_min.'分'.$conversation_s.'秒';
                        //响应时长
                        $response_min = intval($alarm[$b]['alarm_corresponding']/60);
                        $response_s = $alarm[$b]['alarm_corresponding']%60;
                        $result[$key]['response'] = $response_min.'分'.$response_s.'秒';
                    }
                }

                if($vo['servicelog_close_type'] == 0){
                    $result[$key]['servicelog_close_type'] = '未知';
                }
                if($vo['servicelog_close_type'] == 1){
                    $result[$key]['servicelog_close_type'] = '无效会话';
                }
                if($vo['servicelog_close_type'] == 2){
                    $result[$key]['servicelog_close_type'] = '双方静默';
                }
                if($vo['servicelog_close_type'] == 3){
                    $result[$key]['servicelog_close_type'] = '客服关闭';
                }
                if($vo['servicelog_close_type'] == 4){
                    $result[$key]['servicelog_close_type'] = '客服掉线';
                }
                if($vo['servicelog_close_type'] == 5){
                    $result[$key]['servicelog_close_type'] = '转出';
                }
                if($vo['servicelog_close_type'] == 6){
                    $result[$key]['servicelog_close_type'] = '用户关闭';
                }

                // 生成操作按钮
                if(0 != $vo['servicelog_id']){
                    $result[$key]['operate'] = $this->makeBtn($vo['servicelog_id']);
                }
            }

            $return['total'] = $countTmp->count();  //总数据
            $return['rows'] = $result;

//            if (!$toExcel) {
//                return json($return);
//            } else {
//                $head = ['工单id', '访客进线时间', '接待客服', '所在组', '访客账号', '开始时间', '结束时间', '会话时长', '响应时长', '关闭原因', '满意度'];
//                $key = ['servicelog_id', 'intime', 'kefu_name', 'group_name', 'user_name', 'start_time', 'end_time', 'conversation', 'response', 'servicelog_close_type', 'evaluate_name'];
//                (new Office())->outdata('工作报表数据导出', $result, $head, $key);
//                return true;
//            }

            return json($return);

        }
        //所有客服
        $users = db('users')->select();
        $useroption = '';
        if(!empty($users)){
            $option = '<option value="0">全部客服</option>';
            for($i=0;$i<count($users);$i++){
                $option = $option.'<option value="'.$users[$i]['id'].'">'.$users[$i]['user_name'].'</option>';
            }
            $useroption = '<select class="selector_user" lay-verify="required" lay-filter="user_id" style="height: 30px;">'.$option.'</select>';
        }
        //所有客服组
        $groups = db('groups')->select();
        $groupoption = '';
        if(!empty($groups)){
            $option = '<option value="0">全部客服组</option>';
            for($j=0;$j<count($groups);$j++){
                $option = $option.'<option value="'.$groups[$j]['id'].'">'.$groups[$j]['name'].'</option>';
            }
            $groupoption = '<select class="selector_group" lay-verify="required" lay-filter="group_id" style="height: 30px;">'.$option.'</select>';
        }

        $this->assign([
            'useroption' => $useroption,
            'groupoption' => $groupoption
        ]);

        return $this->fetch('wordslog');
    }

    function matching($str, $a, $b)
    {
        $pattern = '/('.$a.')(.*)(?)('.$b.')/'; //正则规则匹配支付串中任何一个位置字符串
        //$pattern = '/(#\[)(.*)(?)(\]\/)/';
        preg_match_all($pattern,$str,$m);
        //preg_match_all($pattern, $str, $m);   //返回一个匹配结果
        //print_r($m);die;  //到时候在这里书写返回值就好了 .die;
    }

    // 历史会话记录详情
    public function detail($id, $type='')
    {
        $chat = db('chat_log')->where('servicelog_id',$id)->order('time_line')->select();
        $html = '';
        for($i=0;$i<count($chat);$i++){
            $content = json_decode($chat[$i]['content'], true);
            $chat[$i]['time_line'] = date('H:i',$chat[$i]['time_line']);
            if(!empty($content['text'])){
                $content['content'] = '&nbsp&nbsp'.$content['text'].'&nbsp&nbsp';
            }
            if(!empty($content['img'])){
                $content['content'] = '<img width="100%" src="'.$content['img'].'"/>';
            }
            if(!empty(strstr($chat[$i]['to_id'], 'KF'))){
                /*$preg1 = "/^#[*]$/";
                $preg= '/xue[\s\S]*?om/i';
                preg_match_all($preg1,"#[哈哈]/",$res);
                var_dump($res);*/
                $this->matching("#[哈哈]/","#\[","\]\/");
                //$this->getFacesIcon();
                $html = $html . '<div style="margin-top:15px;width:75%"><div>'.$chat[$i]['from_name'].'&nbsp&nbsp&nbsp'.$chat[$i]['time_line'].'</div>';
                $html = $html . '<div style="margin-top:5px;display:inline-block;*display:inline;*zoom:1;word-break:break-all;word-wrap:break-word" class="form-content">'.$content['content'].'</div></div>';
            }else{
                $html = $html . '<div style="margin-top:15px;width:75%;margin-left:25%;text-align:right;"><div>'.$chat[$i]['from_name'].'&nbsp&nbsp&nbsp'.$chat[$i]['time_line'].'</div>';
                $html = $html . '<div style="margin-top:5px;display:inline-block;*display:inline;*zoom:1;text-align:left;word-break:break-all;word-wrap:break-word" class="form-content">'.$content['content'].'</div></div>';
            }

        }
        $redis = new Redis;
        if ($type === 'onLine') {
            $servicelog = json_decode($redis->handler()->Hget('SERVICELOG', $id), true);
        } else {
            $servicelog = db('service_log')->where('servicelog_id',$id)->find();
        }
        //满意度
        $evaluate = db('evaluate')->where('evaluate_id',$servicelog['evaluate_id'])->find();
        $evaluate = '<img width="40px" style="margin-top:15px;" src="'.$evaluate['evaluate_url'].'"/>';

        //$alarm报警信息
        if ($type === 'onLine') {
            $alarm = json_decode($redis->handler()->Hget('SERVICELOG', $id), true);
        } else {
            $alarm =  db('alarm')->where('servicelog_id',$id)->find();
        }

        //会话超时标准
        $verifyAllTime =  db('systemconfig')->where('systemconfig_name','质检会话时长设置')->find();
        //会话响应时长标准
        $verifyReturnTime =  db('systemconfig')->where('systemconfig_name','质检会话响应时长设置')->find();
        $span = '';
        if(!empty($alarm)){
            if($alarm['alarm_userSensitive'] != 0){
                $span = $span . '<span class="alarm_info">访客敏感词</span>';
            }
            if($alarm['alarm_serverSensitive'] != 0){
                $span = $span . '<span class="alarm_info">客服敏感词</span>';
            }
            if($alarm['alarm_corresponding'] > $verifyReturnTime['systemconfig_data']){
                $span = $span . '<span class="alarm_info">响应超时</span>';
            }
            if($alarm['alarm_cvtOvertime'] > $verifyAllTime['systemconfig_data']){
                $span = $span . '<span class="alarm_info">会话超时</span>';
            }
            if($alarm['alarm_respond'] == 1){
                $span = $span . '<span class="alarm_info">客服未回应</span>';
            }
        }

        //用户信息
        $account = db('accounts')->where('id',$servicelog['user_id'])->find();
        $label = db('accountslabel')->where('id', $account['label_id'])->find();
        $account['label'] = $label['name'];
        $this->assign([
            'html' => $html,
            'span' => $span,
            'evaluate' => $evaluate,
            'servicelog' => $servicelog,
            'account' => $account
        ]);
        return $this->fetch();
    }

    // 生成按钮
    private function makeBtn($id)
    {
        $operate = '<a href="' . url('system/detail', ['id' => $id]) . '">';
//        $operate .= '<button type="button" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 详情</button></a> ';
        $operate .= '<button type="button" class="btn btn-primary btn-sm"> 详情</button></a> ';

        return $operate;
    }

    public function getFacesIcon($facesIcon) {
        $data = ["[微笑]", "[嘻嘻]", "[哈哈]", "[可爱]", "[可怜]", "[挖鼻]", "[吃惊]", "[害羞]", "[挤眼]", "[闭嘴]", "[鄙视]",
            "[爱你]", "[泪]", "[偷笑]", "[亲亲]", "[生病]", "[太开心]", "[白眼]", "[右哼哼]", "[左哼哼]", "[嘘]", "[衰]",
            "[委屈]", "[吐]", "[哈欠]", "[抱抱]", "[怒]", "[疑问]", "[馋嘴]", "[拜拜]", "[思考]", "[汗]", "[困]", "[睡]",
            "[钱]", "[失望]", "[酷]", "[色]", "[哼]", "[鼓掌]", "[晕]", "[悲伤]", "[抓狂]", "[黑线]", "[阴险]", "[怒骂]",
            "[互粉]", "[心]", "[伤心]", "[猪头]", "[熊猫]", "[兔子]", "[ok]", "[耶]", "[good]", "[NO]", "[赞]", "[来]",
            "[弱]", "[草泥马]", "[神马]", "[囧]", "[浮云]", "[给力]", "[围观]", "[威武]", "[奥特曼]", "[礼物]", "[钟]",
            "[话筒]", "[蜡烛]", "[蛋糕]"];
        $key = array_search($facesIcon, $data);
        return $key;
    }

    public function toexcel()
    {
        $param = input('param.');

        $limit = $param['pageSize'];
        $offset = ($param['pageNumber'] - 1) * $limit;

        $start = $param['start'];
        $end = $param['end'];
        $where = [];
        if($param['user_id'] != 0){
            $where['kf_id'] = $param['user_id'];
        }
        if($param['group_id'] != 0){
            $where['group_id'] = $param['group_id'];
        }
        if(!empty($param['username'])){
            $where['user_name'] = $param['username'];
        }
        $result = db('service_log')->whereBetween('start_time', [strtotime($start), strtotime($end . ' 23:59:59')])->where($where)->limit($offset, $limit)->order('start_time', 'desc')->select();

        //所有客服
        $users = db('users')->select();
        //所有客服组
        $groups = db('groups')->select();
        //满意度
        $evaluate = db('evaluate')->select();
        //$alarm报警信息
        $alarm =  db('alarm')->select();
        foreach($result as $key=>$vo){
            if($result[$key]['intime'] != 0){
                $result[$key]['intime'] = date('Y-m-d H:i:s', $vo['intime']);
            }else{
                $result[$key]['intime'] = '-';
            }
            if($result[$key]['start_time'] != 0){
                $result[$key]['start_time'] = date('Y-m-d H:i:s', $vo['start_time']);
            }else{
                $result[$key]['start_time'] = '-';
            }
            if($result[$key]['end_time'] != 0){
                $result[$key]['end_time'] = date('Y-m-d H:i:s', $vo['end_time']);
            }else{
                $result[$key]['end_time'] = '-';
            }
            //客服昵称
            for($i=0;$i<count($users);$i++){
                if($result[$key]['kf_id'] == $users[$i]['id']){
                    $result[$key]['kefu_name'] = $users[$i]['user_name'];
                }
            }

            //满意度
            $result[$key]['evaluate_name'] = '';
            for($j=0;$j<count($evaluate);$j++){
                if($result[$key]['evaluate_id'] == $evaluate[$j]['evaluate_id']){
                    $result[$key]['evaluate_name'] = $evaluate[$j]['evaluate_name'];
                }
            }

            //客服所在组
            for($a=0;$a<count($groups);$a++){
                if($result[$key]['group_id'] == $groups[$a]['id']){
                    $result[$key]['group_name'] = $groups[$a]['name'];
                }
            }

            //会话时长/响应时长
            $result[$key]['conversation'] = '';
            $result[$key]['response'] = '';
            for($b=0;$b<count($alarm);$b++){
                if($result[$key]['servicelog_id'] == $alarm[$b]['servicelog_id']){
                    //会话时长
                    $conversation_min = intval($alarm[$b]['alarm_cvtOvertime']/60);
                    $conversation_s = $alarm[$b]['alarm_cvtOvertime']%60;
                    $result[$key]['conversation'] = $conversation_min.'分'.$conversation_s.'秒';
                    //响应时长
                    $response_min = intval($alarm[$b]['alarm_corresponding']/60);
                    $response_s = $alarm[$b]['alarm_corresponding']%60;
                    $result[$key]['response'] = $response_min.'分'.$response_s.'秒';
                }
            }

            if($vo['servicelog_close_type'] == 0){
                $result[$key]['servicelog_close_type'] = '未知';
            }
            if($vo['servicelog_close_type'] == 1){
                $result[$key]['servicelog_close_type'] = '访客静默';
            }
            if($vo['servicelog_close_type'] == 2){
                $result[$key]['servicelog_close_type'] = '会话超时';
            }
            if($vo['servicelog_close_type'] == 3){
                $result[$key]['servicelog_close_type'] = '客服关闭';
            }
            if($vo['servicelog_close_type'] == 4){
                $result[$key]['servicelog_close_type'] = '客服掉线';
            }
            if($vo['servicelog_close_type'] == 5){
                $result[$key]['servicelog_close_type'] = '转接';
            }

            //工单聊天详情
            $chat_log = db('chat_log')->where('servicelog_id',$vo['servicelog_id'])->order('time_line', 'desc')->select();
            $result[$key]['detail'] = '';
            for($c=0;$c<count($chat_log);$c++){
                $content = json_decode($chat_log[$c]['content'], true);
                $chat_log[$c]['time_line'] = date('Y-m-d H:i:s',$chat_log[$c]['time_line']);
                $result[$key]['detail'] = $result[$key]['detail'].' '.$chat_log[$c]['time_line'].' '.$chat_log[$c]['from_name'];
                if(!empty($content['text'])){
                    $content['content'] = $content['text'];
                }
                if(!empty($content['img'])){
                    $content['content'] = '<img width="100%" src="'.$content['img'].'"/>';
                }
                $result[$key]['detail'] = $result[$key]['detail'].' '.$content['content'];
            }

        }
        $head = ['工单id', '访客进线时间', '接待客服', '所在组', '访客账号', '开始时间', '结束时间', '会话时长', '响应时长', '关闭原因', '满意度','来源ip','来源网站','来源系统','来源浏览器','聊天详情'];
        $key = ['servicelog_id', 'intime', 'kefu_name', 'group_name', 'user_name', 'start_time', 'end_time', 'conversation', 'response', 'servicelog_close_type', 'evaluate_name','user_ip','website','system','browse','detail'];
        (new Office())->outdata('工单数据导出', $result, $head, $key);
        return true;
    }

    // 生成按钮
    private function makeBotton($id)
    {
        $operate = '<a href="' . url('editWelcome', ['id' => $id]) . '">';
        $operate .= '<button type="button" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 编辑</button></a> ';

        $operate .= '<a href="javascript:delWelcome(' . $id . ')"><button type="button" class="btn btn-danger btn-sm">';
        $operate .= '<i class="fa fa-trash-o"></i> 删除</button></a> ';
        return $operate;
    }

}
