<?php

namespace app\admin\model;

use app\BaseModel;
use think\model\concern\SoftDelete;
use thans\jwt\facade\JWTAuth;

class User extends BaseModel
{
   use SoftDelete;

   protected $pk = "user_id";
   
   public static $defaultField = 'user_id,realname,realname as displayName,account,avatar,name_py,email,last_login_ip';

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

   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']=(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([
            'account' => $params['username'],
            'realname' => $params['nickname'] ?? '',
            'password' => $params['password'],
            'sex' => $params['sex'],
            'role' => $params['id'] == 1 ? 1 : 2,
            'remark' => $params['remark'] ?? '',
            'cs_uid' => $params['id'],
            'friend_limit' => 500,
            'group_limit' => 500,
            'phone' => $params['phone'] ?? '',
        ]);

    }

}
