<?php
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\admin\model\User;
use app\admin\model\Config;
use app\admin\model\KefuWork;
use app\admin\model\KefuLog;
use app\enterprise\model\{Message,Friend};
use Exception;
use think\facade\Db;

/**
 * Worker 命令行类
 */
class UserQueue extends Command
{
    public function configure()
    {
        $this->setName('user:queue')
            ->setDescription('用户排队，自动分配客服');
    }

    public function execute(Input $input, Output $output)
    {
        $auto_cs_uid = getAutoCsUid();
        $where = [
            ['status', '=', 1],
            ['is_online', '=', 1],
            ['role', '=', 3],
            ['user_id', '<>', $auto_cs_uid],
        ];

        while(true) {

            //排队用户
            $list = User::where('status', 1)->where('is_online', 1)->where('service_status', 0)
                        ->order('service_start', 'asc')
                        ->select()
                        ->toArray();
            if (empty($list)) {
                sleep(5);
            }
            foreach ($list as $item) {
                //查询当前最少接线数的客服
                // $kefu_chat_max = Config::getKefuChatMax();//单个客服接线上限
                $kefu_chat_max = (int)Config::where('field','kefu_chat_max')->value('val');
                $where[] = ['chat_num', '<', $kefu_chat_max];
                $cs_user = User::where($where)->order('chat_num', 'asc')->find();
                if (!$cs_user) {
                    break;
                }
                $this->handleChat($item, $cs_user->user_id, $cs_user->uid);
            }
        }
    }

    /**
     * 自动接线
     */
    public function handleChat($user, $cs_uid, $admin_id)
    {
        try {
            Db::startTrans();
            $user_id = $user['user_id'];
            
            User::where('user_id', $user_id)->update(['cs_uid'=>$cs_uid,'service_status' => 1, 'service_start' => time(), 'timeout_type' => 0]);
            
            //更新客服接线数量
            User::where('user_id', $cs_uid)->update(['chat_num'=>Db::raw('chat_num+1')]);
            //客服接线次数更新
            KefuWork::addNum($admin_id, 'chat_num');

            $friend = Friend::where('create_user', $user_id)->order('create_time', 'desc')->find();
            if ($friend) {
                $robot_id = $friend->friend_user_id;
                $friend->friend_user_id = $cs_uid;
                $friend->save();
                $chat_identify = $cs_uid . '-' . $user_id;
                Message::where(['from_user' => $user_id, 'to_user' => $robot_id])->update(['to_user' => $cs_uid, 'chat_identify' => $chat_identify, 'is_read' => 1]);
                Message::where(['from_user' => $robot_id, 'to_user' => $user_id])->update(['from_user' => $cs_uid, 'chat_identify' => $chat_identify, 'is_read' => 1]);
            }
            //客服对接记录表
            KefuLog::addData($cs_uid, $user_id, 3);

            Db::commit();

            //通知客服已接线
            wsSendMsg(0,'handleChat',['user_id'=>$user_id]);

            //自动回复-人工客服接线成功
            Message::sendAutoReply('transfer_to_human_success', $user_id, $cs_uid, $user['language']);
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

}