<?php
namespace app\service\controller;

/**
 * 客服系统首页类
 */
class Index extends Common
{


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

        try {
            $getUserToken = input('server.HTTP_userToken');
            $usersField   = [
                'a.id',
                'user_name',
                'user_avatar',
                'b.name',
            ];
            // 关联信息.
            $join['groups b']    = 'a.group_id = b.id';
            $usersWhere['token'] = $getUserToken;
            // 获取用户信息.
            $usersInfo = model('users')->findInfo($usersField, $usersWhere, $join);

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

    }//end userInfo()


    /**
     * 获取用户快捷语
     *
     * @access public
     * @return array JsonString
     */
    public function userWords()
    {
        // 验证token.
        $tokenStatus = $this->verifyToken();
        $code        = -2;
        $msg         = '错误';
        if ($tokenStatus === false) {
            $msg = 'token错误';
            return json(['code' => $code, 'data' => [], 'msg' => $msg]);
        }

        try {
            // 获取用户信息.
            $getUserInfo = $this->getUserInfo();
            // 获取快捷语.
            $wordsField               = [
                'id',
                'content',
                'title',
            ];
            $sysWordsWhere['status']  = 1;
            $sysWordsWhere['user_id'] = 0;
            // 查询系统快捷语.
            $sysWords = model('words')->selectWords($wordsField, $sysWordsWhere);
            // 查询用户私有快捷语条件.
            $userWordsWhere['user_id'] = $getUserInfo->id;
            // 查询用户私有快捷语.
            $userWords = model('words')->selectWords($wordsField, $userWordsWhere);
            $result    = [
                'sysWords'  => $sysWords,
                'userWords' => $userWords,
            ];

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

    }//end userWords()


    /*public function index()
    {
        $getUserInfo = $this->getUserInfo();

        // 客服信息
        $userInfo = db('users')->where('id', 1)->find();

        $this->assign([
            'uinfo' => $userInfo,
            'word' => db('words')->select(),
            'groups' => db('groups')->where('status', 1)->select(),
            'status' => db('kf_config')->where('id', 1)->find()
        ]);

        return $this->fetch();
    }*/


    // 获取服务用户列表
    // 此方法是为了防止客服工作期间错误的刷新工作台，导致服务人员消失的问题
    public function getUserList()
    {
        if(request()->isAjax()){

            // 此处只查询过去 三个小时 内的未服务完的用户
            $userList = db('service_log')
                ->where(function ($query) {
                    $query = $query->where('status', 1);
                    $query = $query->whereOr('status', 3);
                    return $query;
                })
                ->select();

            return json(['code' => 1, 'data' => $userList, 'msg' => 'ok']);
        }
    }

    // 获取聊天记录
    public function getChatLog()
    {
        if(request()->isAjax()){

            $param = input('param.');

            $limit = 10; // 一次显示10 条聊天记录
            $offset = ($param['page'] - 1) * $limit;

            $logs = db('chat_log')->where(function($query) use($param){
                    $query->where('from_id', $param['uid'])->where('to_id', 'KF' . cookie('l_user_id'));
            })->whereOr(function($query) use($param){
                $query->where('from_id', 'KF' . cookie('l_user_id'))->where('to_id', $param['uid']);
            })->limit($offset, $limit)->order('id', 'desc')->select();

            $total =  db('chat_log')->where(function($query) use($param){
                $query->where('from_id', $param['uid'])->where('to_id', 'KF' . cookie('l_user_id'));
            })->whereOr(function($query) use($param){
                $query->where('from_id', 'KF' . cookie('l_user_id'))->where('to_id', $param['uid']);
            })->count();

            foreach($logs as $key=>$vo){

                $logs[$key]['type'] = 'user';
                $logs[$key]['time_line'] = date('Y-m-d H:i:s', $vo['time_line']);

                if($vo['from_id'] == 'KF' . cookie('l_user_id')){
                    $logs[$key]['type'] = 'mine';
                }
            }

            return json(['code' => 1, 'data' => $logs, 'msg' => intval($param['page']), 'total' => ceil($total / $limit)]);
        }
    }

    // ip 定位
    public function getCity()
    {
        $ip = input('param.ip');

        $ip2region = new \Ip2Region();
        $info = $ip2region->btreeSearch($ip);

        $city = explode('|', $info['region']);

        if(0 != $info['city_id']){
            return json(['code' => 1, 'data' => $city['2'] . $city['3'] . $city['4'], 'msg' => 'ok']);
        }else{

            return json(['code' => 1, 'data' => $city['0'], 'msg' => 'ok']);
        }
    }


    //获取访客端入口
    public function getGuestEnter()
    {
        //访客端入口
        $guestenter = db('guestenter')->order('sort','asc')->select();
        //自动邀请设置信息
        $settings = db('settings')->field('id,margin_top,stop_time,copywriting')->find();

        $guestenter[] = $settings;

        if(!empty($guestenter)){
            return json(['code' => 1, 'data' => $guestenter, 'msg' => '成功']);
        }else{
            return json(['code' => -1, 'data' => '', 'msg' => '失败']);
        }
    }


    /**
     * 获取未读公告
     * @access public
     * @return array JsonString
     */
    public function unreadnotice()
    {
        $user_id = input('post.user_id');
        //获取未读公告
        try{
            $admins = db('admins')->select();
            $readnotice = db('servicenotice')->field('id,uid,title,atext,sendtime,admin_id')->where('readtime',0)->where('uid',$user_id)->where('sendtime','<',date('Y-m-d H:i:s',time()))->order('sendtime','desc')->select();
            for($i=0;$i<count($readnotice);$i++){
                for($j=0;$j<count($admins);$j++)
                    if($readnotice[$i]['admin_id'] == $admins[$j]['id']){
                        $readnotice[$i]['admin_name'] = $admins[$j]['user_name'];
                    }
            }
            return json(['code' => 1, 'data' => $readnotice, 'msg' => '成功']);
        } catch (\Exception $e) {
            return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
        }

    }

    /**
     * 获取已读公告
     * @access public
     * @return array JsonString
     */
    public function readnotice()
    {
        $user_id = input('post.user_id');
        //获取已读公告
        try{
            $admins = db('admins')->select();
            $unreadnotice = db('servicenotice')->field('id,uid,title,atext,sendtime,admin_id')->where('readtime','<>',0)->where('uid',$user_id)->order('sendtime','desc')->select();
            for($i=0;$i<count($unreadnotice);$i++){
                for($j=0;$j<count($admins);$j++)
                if($unreadnotice[$i]['admin_id'] == $admins[$j]['id']){
                    $unreadnotice[$i]['admin_name'] = $admins[$j]['user_name'];
                }
            }
            return json(['code' => 1, 'data' => $unreadnotice, 'msg' => '成功']);
        } catch (\Exception $e) {
            return json(['code' => -3, 'data' => '', 'msg' => $e->getMessage()]);
        }

    }

    /**
     * 修改公告阅读状态
     * @access public
     * @return array JsonString
     */
    public function updatenotice()
    {
        $servicenotice_id = input('post.servicenotice_id');

        $data = db('servicenotice')->where('id',$servicenotice_id)->find();
        if(empty($data)){
            return json(['code' => -1, 'data' => '', 'msg' => '公告不存在']);
        }

        try{
            //修改公告阅读状态
            db('servicenotice')->where('id',$servicenotice_id)->update(['readtime' => time()]);
            return json(['code' => 1, 'data' => '', 'msg' => '公告阅读状态修改成功']);
        } catch (\Exception $e) {
            return json(['code' => -3, 'data' => '', 'msg' => $e->getMessage()]);
        }

    }
}
