<?php
declare (strict_types = 1);

namespace app\model\system;

use library\basic\BaseModel;
use library\traits\JwtAuthModelTrait;
use library\traits\ModelTrait;
use think\facade\Cache;
use think\Model;

class Admin extends BaseModel
{
    use ModelTrait;
    use JwtAuthModelTrait;


    /**
     * 后台管理人员登录
     * @param $username
     * @param $pwd
     * @return array|bool|Model|null
     */
    public static function login($username, $pwd){
        $adminInfo = self::get(compact('username'));
        if(empty($adminInfo)) return self::setErrorInfo('登录的账号不存在');
        if (!$adminInfo['status']) return self::setErrorInfo('账户以后被停用!');
        
        if (!password_verify($pwd, $adminInfo['password'])) return self::setErrorInfo('账号或密码错误，请重新输入');
        //发生事件
        event('SystemAdminLoginAfter', [$adminInfo]);
        return $adminInfo;
    }

    /**
     * 管理添加，修改
     * @param $post
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function saveAdmin($post) {
        $save = [
            'name'     => $post['name'],
            'role_id'  => $post['role_id'],
            'avatar'   => $post['avatar'],
            'status'   => $post['status'],
            'nickname' => empty($post['nickname'])?'':$post['nickname'],
        ];
        //是否密码写入
        if(!empty($post['password'])) {
            $save['password'] = password_hash($post['password'],PASSWORD_BCRYPT);
        }
        if($post['id']) {
            $info = self::where("username",$post['username'])->find();
            if(!empty($info) && $info['id'] != $post['id'] ) {
                return self::setErrorInfo('登录的账号已存在');
            }
            //判断密码
            if(empty($save['password'])) {
                unset($post['password']);
            }
            self::where('id',$post['id'])->save($save);
        } else {
            $save['time'] = time();
            $save['last_time'] = time();
            $save['username'] = $post['username'];
            $count = self::where("username",$post['username'])->count();
            if($count > 0) {
                return self::setErrorInfo('登录的账号已存在');
            }

            if(empty($save['password'])) {
                return self::setErrorInfo('请输入登录密码');
            }
            self::insert($save);
        }

        return true;
    }


    /**
     * 验证密码
     * @param $id 管理ID
     * @param $pwd 旧密码
     * @return bool
     */
    public static function checkPassowrd($id,$pwd) {
        $adminInfo = self::get(compact('id'));
        if(empty($adminInfo)) return self::setErrorInfo('登录的账号不存在');
        if (!password_verify($pwd, $adminInfo['password'])){
            return false;
        }
        return true;
    }


    /**
     * 生成token存放令牌 | 存放redis
     * @param Admin $adminInfo
     * @param $type
     * @return array|bool
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function createToken(Admin $adminInfo,$type)
    {
        $tokenInfo = $adminInfo->getToken($type, []);
        $exp = (int)bcadd((string)($tokenInfo['params']['exp'] - $tokenInfo['params']['iat']), "60", 0);
        try {
            $key = md5($tokenInfo['token']);
            $res = Cache::store('redis')->set($key, ['token' => $tokenInfo['token'], 'exp' => $exp], (int)$exp);
        } catch (\Throwable $e) {
            return self::setErrorInfo('保存token失败');
        }
        return $tokenInfo;
    }
}
