<?php

namespace app\admin\model;

use app\BaseModel;
use think\model\concern\SoftDelete;
use thans\jwt\facade\JWTAuth;
use app\enterprise\model\{Message,Friend};

class User extends BaseModel
{
    use softDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = null;
    protected $table = 'bot_users';
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    //时间是日期格式
    protected $autoWriteTimestamp = true;
   protected $pk = "id";
   
   public static $defaultField = 'user_id,realname,realname as displayName,account,avatar,name_py,email,last_login_ip';

   protected $json = ['setting'];
   protected $jsonAssoc = true;

   /**
     * @notes 生成用户编码
     * @param string $prefix
     */
    public static function createUserSn($prefix = '', $length = 8)
    {
        $rand_str = '';
        for ($i = 0; $i < $length; $i++) {
            $rand_str .= mt_rand(1, 9);
        }
        $user_id = $prefix . $rand_str;
        if (User::where(['user_id' => $user_id])->find()) {
            return self::createUserSn($prefix, $length);
        }
        return $user_id;
    }

   public static function getCsId($admin_id) {
      return self::where('from', 0)->where('uid', $admin_id)->value('user_id');
   }

   public static function getAdminId($user_id) {
      return self::where('from', 0)->where('user_id', $user_id)->value('uid');
   }
   public function getAvatarAttr($value,$data)
    {
        return avatarUrl($data['avatar'],$data['realname'],$data['user_id']);
    }

    public function getSettingAttr($value)
    {
        if (!$value) return null;
        $setting = $value;
        $setting['hideMessageName']= $setting['hideMessageName']=='true' ? true : false;
        $setting['hideMessageTime']= $setting['hideMessageTime']=='true' ? true : false;
        $setting['avatarCricle']= $setting['avatarCricle']=='true' ? true : false;
        $setting['isVoice']= $setting['isVoice']=='true' ? true : false;
        $setting['sendKey']=1;//(int)$setting['sendKey'];
        return $setting;
    }

   /**
     * 刷新用户token 之前token将被拉黑
     * 修改用户数据后 调用该方法 并返回前台更新token
     * @param array $info 用户信息
     * @param string $terminal 客户端标识
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function refreshToken($info,$terminal, $admin = [])
    {
        $info      = str_encipher(json_encode($info),true, config('app.aes_token_key'));
        $authToken = 'bearer '.JWTAuth::builder(['info' => $info, 'terminal' => $terminal, 'admin' => $admin]);
        return $authToken;
    }

    //添加客服用户
    public static function addCs($params) {
        self::create([
            'user_id' => User::createUserSn(),
            'account' => $params['username'],
            'realname' => $params['nickname'] ?? '',
            'avatar' => $params['avatar'] ?? '',
            'password' => $params['password'],
            'sex' => $params['sex'],
            'role' => $params['role'],
            'remark' => $params['remark'] ?? '',
            'cs_uid' => $params['id'],
            'friend_limit' => 500,
            'group_limit' => 500,
            'phone' => $params['phone'] ?? '',
            'from' => 0,
            'uid' => $params['id'],
        ]);
    }

    //客服离线后自动结束所有客服会话
    public static function KefuOffline($kefu_user_id, $admin_id) {

        wsSendMsg(0,'isOnline',['id'=>$kefu_user_id,'is_online'=>0]);
        //更新客服状态
        User::where('user_id', $kefu_user_id)->update(['is_online'=>0, 'offline_time'=>time(), 'is_finished' => 1, 'chat_num' => 0]);
        //更新客服接线的用户
        $cs_uid = getAutoCsUid();

        $list = User::where('cs_uid', $kefu_user_id)->select()->toArray();
        foreach($list as $item) {
            //是否弹层提醒
            $is_warning = $item['service_status'] == 1 || $item['service_status'] == 2 ? 1 : 0;

            $service_status = $item['is_online'] == 1 ? 0 : -1 ;
            //更新用户会话状态
            User::where('user_id', $item['user_id'])->update(['cs_uid' => $cs_uid, 'service_status' => $service_status, 'service_start' => time(), 'timeout_type' => 0]);

            $user_id = $item['user_id'];
            $old_cs_uid = $item['cs_uid'];

            $friend = Friend::where('create_user', $user_id)->order('create_time', 'desc')->find();
            if ($friend) {
                $friend->friend_user_id = $cs_uid;
                $friend->save();
                
                $chat_identify = $cs_uid . '-' . $user_id;
                Message::where(['from_user' => $user_id, 'to_user' => $old_cs_uid])->update(['to_user' => $cs_uid, 'chat_identify' => $chat_identify, 'is_read' => 1]);
                Message::where(['from_user' => $old_cs_uid, 'to_user' => $user_id])->update(['from_user' => $cs_uid, 'chat_identify' => $chat_identify, 'is_read' => 1]);
            }

            //客服对接记录表
            KefuLog::addData($cs_uid, $user_id, 3);

            //通知关闭聊天框
            wsSendMsg($old_cs_uid,'closeChat',['user_id'=>$user_id, 'realname' => $item['realname'], 'is_warning' => $is_warning]);
        }
        //结束客服忙碌时间
        KefuTime::endData($admin_id, 1);
        //结束客服在线时间
        KefuTime::endData($admin_id, 2);
            
        //结束客服接线时间
        KefuTime::endData($admin_id, 3, $kefu_user_id);
        
        //通知客服已结束
        wsSendMsg(0,'handleChat',['user_id'=>0]);
    }

}
