<?php
namespace app\admin\controller;

/**
 * 管理系统系统设置类
 */
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'];
                }

                $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);
                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);
        $this->assign(
            [
                'advertisement' => $advertisement,
                'replySystem'   => $replySystem,
                'replyServer'   => $replyServer,
                'status'        => config('kf_status'),
            ]
        );

        return $this->fetch();

    }//end basics()


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

            try {
                // 修改会话超时.
                $updateOvertimeData['systemconfig_data'] = $param['overtime'];
                $updateOvertimeWhere['systemconfig_id']  = 1;
                model('Systemconfig')->updateSystemconfig($updateOvertimeWhere, $updateOvertimeData);
                // 修改访客静默.
                $upUptdData['systemconfig_data'] = $param['unoperated'];
                $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);

                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()
    {
        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(!empty($param['searchText'])){
                $user = db('users')->where('user_name', $param['searchText'])->find();
                $temp = $temp->where('kf_id', $user['id']);
                $countTmp = $countTmp->where('kf_id', $user['id']);
            }

            //日期
            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 = $temp->where('start_time','>',strtotime($start));
            }
            //开始时间为空
            if(empty($start) && !empty($end)){
                $temp = $temp->where('start_time','<',strtotime($end . ' 23:59:59'));
                $countTmp = $temp->where('start_time','<',strtotime($end . ' 23:59:59'));
            }
            //开始时间/结束时间都为空(默认查七天)
            if(empty($start) && empty($end)){
                $temp = $temp->where('start_time','<',time())->where('start_time','>',time()-604800);
                $countTmp = $temp->where('start_time','<',time())->where('start_time','>',time()-604800);
            }

            //客服
            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 = $temp->where('group_id', $group_id);
            }

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

            //所有客服
            $users = db('users')->select();
            //满意度
            $evaluate = db('evaluate')->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['start_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'];
                    }
                }

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

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

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

            return json($return);

        }
        //所有客服
        $users = db('users')->select();
        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 name="user_id" id="user_id" class="form-control">'.$option.'</select>';
        }
        //所有客服组
        $groups = db('groups')->select();
        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 name="group_id" id="group_id" class="form-control">'.$option.'</select>';
        }

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

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


    // 历史会话记录详情
    public function detail($id)
    {
        $chat = db('chat_log')->where('servicelog_id',$id)->order('time_line')->select();
        $html = '';
        for($i=0;$i<count($chat);$i++){
            $chat[$i]['time_line'] = date('H:i',$chat[$i]['time_line']);
            if(!empty(strstr($chat[$i]['to_id'], 'KF'))){
                $html = $html . '<div style="margin-top:15px;width: 30%;"><div>'.$chat[$i]['from_name'].'&nbsp&nbsp&nbsp'.$chat[$i]['time_line'].'</div>';
                $html = $html . '<p style="margin-top:5px;" class="form-content">'.$chat[$i]['content'].'</p></div>';
            }else{
                $html = $html . '<div style="margin-top:15px;width: 30%;margin-left:70%;text-align:right;"><div>'.$chat[$i]['from_name'].'&nbsp&nbsp&nbsp'.$chat[$i]['time_line'].'</div>';
                $html = $html . '<p style="margin-top:5px;" class="form-content">'.$chat[$i]['content'].'</p></div>';
            }

        }
        $servicelog = db('service_log')->where('servicelog_id',$id)->find();
        //满意度
        $evaluate = db('evaluate')->where('evaluate_id',$servicelog['evaluate_id'])->find();
        $evaluate = $evaluate['evaluate_name'];

        //$alarm报警信息
        $alarm =  db('alarm')->where('servicelog_id',$id)->find();
        $ul = '';
        if(!empty($alarm)){
            $ul = $ul . '<ul class="alarm"><li>触犯警报</li>';
            if($alarm['alarm_userSensitive'] != 0){
                $ul = $ul . '<li class="alarm_info">访客敏感词</li>';
            }
            if($alarm['alarm_serverSensitive'] != 0){
                $ul = $ul . '<li class="alarm_info">客服敏感词</li>';
            }
            if($alarm['alarm_corresponding'] != 0){
                $ul = $ul . '<li class="alarm_info">相应超时</li>';
            }
            if($alarm['alarm_cvtOvertime'] != 0){
                $ul = $ul . '<li class="alarm_info">会话超时</li>';
            }
            $ul = $ul . '</ul>';
        }

        //用户信息
        $account = db('accounts')->where('id',$servicelog['user_id'])->find();
        $this->assign([
            'html' => $html,
            'ul' => $ul,
            '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> ';

        return $operate;
    }
}
