<?php
namespace app\service\controller;

use think\cache\driver\Redis;

/**
 * 客服系统会话历史类
 */
class History extends Common
{


    /**
     * 获取当前所有会话
     *
     * @access public
     * @return array JsonString
     */
    public function allConversation()
    {
        // 验证token.
        $tokenStatus = $this->verifyToken();
        $code        = -2;
        $msg         = '错误';
        if ($tokenStatus === false) {
            $msg = 'token错误';
            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
        }

        try {
            // 获取用户信息.
            $getUserInfo = $this->getUserInfo();
            if ($getUserInfo['user_overview'] != 1) {
                $msg = '您没有权限查看';
                return json(['code' => 1, 'data' => [], 'msg' => $msg]);
            }

            $groups     = model('Groups')->selectGroups();
            $redis      = new Redis;
            $kefuInfo   = $redis->handler()->hGetall('KFINFO');
            $servicelog = $redis->handler()->hGetall('SERVICELOG');
            foreach ($groups as $k => $v) {
                $data[$k]           = (object) [
                    'label' => $v['name'],
                ];
                $n                  = 0;
                $data[$k]->children = [];
                foreach ($kefuInfo as $va) {
                    $kefuInfoData = json_decode($va, true);
                    if ($kefuInfoData['group'] == $v['id']) {
                        $data[$k]->children[$n] = (object) [
                            'label' => $kefuInfoData['name'],
                        ];
                        $m = 0;
                        $data[$k]->children[$n]->children = [];
                        foreach ($servicelog as $val) {
                            $servicelogData = json_decode($val, true);
                            if (('KF'.$servicelogData['kf_id']) == $kefuInfoData['id']) {
                                $data[$k]->children[$n]->children[$m] = (object) [
                                    'label'         => $servicelogData['user_name'],
                                    'servicelog_id' => $servicelogData['servicelog_id'],
                                ];
                            }

                            $m++;
                        }

                        $n++;
                    }
                }//end foreach
            }//end foreach

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

    }//end allConversation()


    /**
     * 获取会话历史
     *
     * @access public
     * @return array JsonString
     */
    public function historyList()
    {
        // 验证token.
        $tokenStatus = $this->verifyToken();
        $code        = -2;
        $msg         = '错误';
        if ($tokenStatus === false) {
            $msg = 'token错误';
            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
        }

        try {
            // 获取用户信息.
            $getUserInfo     = $this->getUserInfo();
            $serviceLogField = [
                'user_id',
                'user_name',
                'user_avatar',
                'user_ip',
                'start_time',
                'end_time',
                'name',
                'website',
                'system',
                'browse',
                'a.status',
                'evaluate_id',
                'intime',
                'servicelog_id',
            ];
            // 关联信息.
            $serviceLogJoin['groups b'] = 'a.group_id = b.id';
            $serviceLogWhere['kf_id']   = $getUserInfo->id;
            // 分页.
            $currentPage = input('post.currentPage', '1');
            $pageSize    = input('post.pageSize', '10');
            $start       = input('post.start');
            $end         = input('post.end');
            $userName    = input('post.user_name');
            $startTime   = strtotime(date('Y-m-d').'-6 day');
            $endTime     = strtotime(date('Y-m-d').'+1 day');
            if (strlen($start) && strlen($end) ) {
                $startTime = strtotime($start);
                $endTime   = strtotime($end.'+1 day');
            }

            if (strlen($userName)) {
                $serviceLogWhere['user_name'] = ['like', '%' . $userName . '%'];
            }

            $serviceLogWhere['start_time'] = [
                'between',
                [
                    $startTime,
                    $endTime,
                ],
            ];
            $offset = (($currentPage - 1) * $pageSize);
            // 获取用户信息.
            $serviceLog      = model('ServiceLog')->selectServiceLog(
                $serviceLogField,
                $offset,
                $pageSize,
                $serviceLogWhere,
                $serviceLogJoin
            );
            $countServiceLog = model('ServiceLog')->countServiceLog($serviceLogWhere);
            $evaluate        = model('Evaluate')->getEvaluate();
            foreach ($serviceLog as $k => $v) {
                foreach ($evaluate as $va) {
                    if ($v->evaluate_id == $va->evaluate_id) {
                        $serviceLog[$k]->evaluate_name = $va->evaluate_name;
                    }
                }
            }

            $result['total']       = $countServiceLog;
            $result['countPage']   = (ceil(($result['total']) / $pageSize));
            $result['currentPage'] = $currentPage;
            $result['list']        = $serviceLog;
            $result['pageSize']    = $pageSize;

            return json(['code' => 1, 'data' => $result, 'msg' => '成功']);
        } catch (\Exception $e) {
            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
        }//end try

    }//end historyList()


    /**
     * 获取会话历史详细
     *
     * @access public
     * @return array JsonString
     */
    public function historyInfo()
    {
        // 验证token.
        $tokenStatus = $this->verifyToken();
        $code        = -2;
        $msg         = '错误';
        if ($tokenStatus === false) {
            $msg = 'token错误';
            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
        }

        try {
            // 获取用户信息.
            $servicelogId = input('get.servicelog_id');
            $chatLogField = ['*'];
            // 关联信息.
            $chatLogWhere['servicelog_id'] = $servicelogId;
            // 分页.
            $currentPage = input('get.currentPage', '1');
            $pageSize    = input('get.pageSize', '10');
            $offset      = (($currentPage - 1) * $pageSize);
            // 获取用户信息.
            $chatLog      = model('ChatLog')->selectChatLog($chatLogField, $offset, $pageSize, $chatLogWhere);
            $countChatLog = model('ChatLog')->countChatLog($chatLogWhere);
            // 查询报警信息.
            $alarmField                    = [
                'evaluate_id',
                'alarm_corresponding',
                'alarm_cvtOvertime',
                'alarm_userSensitive',
                'alarm_serverSensitive',
                'alarm_respond',
            ];
            $alarmWhere['b.servicelog_id'] = $servicelogId;
            $serviceLogJoin['service_log b'] = 'a.servicelog_id = b.servicelog_id';
            $alarm = model('Alarm')->findAlarm($alarmField, $alarmWhere, $serviceLogJoin);
            // 查询系统设置.
            $systemconfig = model('Systemconfig')->selectSystemconfig($alarmField, $alarmWhere, $serviceLogJoin);
            // 响应超时.
            $verifyReturnTime = 0;
            // 会话超时.
            $cvtOvertime = 0;
            foreach ($systemconfig as $v) {
                if ($v['systemconfig_enName'] == 'verifyReturnTime') {
                    if ($v['systemconfig_data'] < $alarm['alarm_corresponding']) {
                        $verifyReturnTime = 1;
                    }
                }

                if ($v['systemconfig_enName'] == 'verifyAllTime') {
                    if ($v['systemconfig_data'] < $alarm['alarm_cvtOvertime']) {
                        $cvtOvertime = 1;
                    }
                }
            }

            $service_log = db('service_log')->where('servicelog_id',$servicelogId)->find();
            $account = db('accounts')
                ->alias('a')
                ->join('accountslabel b', 'a.label_id = b.id')
                ->field('a.id,account_name,nick_name,account_email,account_phone,address,remark,name as label')
                ->where('a.id',$service_log['user_id'])
                ->find();
            $account['user_ip'] = $service_log['user_ip'];
            $account['system'] = $service_log['system'];
            $account['browse'] = $service_log['browse'];


            $result['total']       = $countChatLog;
            $result['countPage']   = (ceil(($result['total']) / $pageSize));
            $result['currentPage'] = $currentPage;
            $result['list']        = $chatLog;
            $result['pageSize']    = $pageSize;
            $result['account']    = $account;
            $result['alarm']       = [
                'evaluate_id'      => $alarm['evaluate_id'],
                'verifyReturnTime' => $verifyReturnTime,
                'cvtOvertime'      => $cvtOvertime,
                'serverSensitive'  => $alarm['alarm_serverSensitive'] ? 1 : 2,
                'userSensitive'    => $alarm['alarm_userSensitive'] ? 1 : 2,
                'respond'          => $alarm['alarm_respond'],
            ];

            return json(['code' => 1, 'data' => $result, 'msg' => '成功']);
        } catch (\Exception $e) {
            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
        }//end try

    }//end historyInfo()


    /**
     * 获取用户会话历史详细
     *
     * @access public
     * @return array JsonString
     */
    public function userHistory()
    {
        // 验证token.
        $tokenStatus = $this->verifyToken();
        $code        = -2;
        $msg         = '错误';
        if ($tokenStatus === false) {
            $msg = 'token错误';
            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
        }

        try {
            // 获取用户ID.
            $accountId    = input('get.account_id');
            $chatLogField = ['*'];
            // 关联信息.
            $chatLogWhere['from_id'] = $accountId;
            $chatLogWhereOr['to_id'] = $accountId;
            // 分页.
            $currentPage = input('get.currentPage', '1');
            $pageSize    = input('get.pageSize', '10');
            $offset      = (($currentPage - 1) * $pageSize);
            // 获取用户信息.
            $chatLog      = model('ChatLog')->userChatLog(
                $chatLogField,
                $chatLogWhere,
                $chatLogWhereOr,
                $offset,
                $pageSize
            );
            $countChatLog = model('ChatLog')->userChatLogCount($chatLogWhere, $chatLogWhereOr);

            $result['total']       = $countChatLog;
            $result['countPage']   = (ceil(($result['total']) / $pageSize));
            $result['currentPage'] = $currentPage;
            $result['list']        = $chatLog;
            $result['pageSize']    = $pageSize;

            return json(['code' => 1, 'data' => $result, 'msg' => '成功']);
        } catch (\Exception $e) {
            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
        }//end try

    }//end userHistory()


}
