<?php
namespace app\admin\server\index;

use app\admin\model\SystemAdmin;
use Tinywan\Jwt\JwtToken;

class LoginServer
{
    /**
     * Notes:管理端登录
     * @param string $user_name
     * @param string $password
     * @param string $captcha
     * @return array
     * User: yym
     * Date: 2022/8/2
     */
    public static function login(string $user_name, string $password, string $captcha)
    {
        $access_token = array();
        $token = static::loginIn($user_name, $password);
        $access_token['expires_time'] = $token['expires_in'];
        $access_token['token']        = $token['access_token'];
        $access_token['userInfo']     = $token['userInfo'];
        return $access_token;
    }

    /**
     * Notes:手机号验证码登录处理
     * @param string $user_name
     * @param string $password
     * @return array
     * @throws \Exception
     * User: yym
     * Date: 2022/8/2
     */
    private static function loginIn(string $user_name, string $password)
    {
        SystemAdmin::affairBegin();
        try {
            $token = array();
            $info  = SystemAdmin::getInfo($user_name);
            if(!empty($info))
            {
                if($info['admin_pwd'] != md5(sha1($password)))
                {
                    throw new \Exception('账号/密码错误~');
                }
                switch ($info['admin_status'])
                {
                    case SystemAdmin::DISABLED://已禁用
                        throw new \Exception('您的账号已禁用，请联系管理员~');
                        break;
                }
                $extend = array(
                    'id' => $info['admin_id']
                );
                $token   = JwtToken::generateToken($extend);
            }else{
                throw new \Exception('账号不存在');
            }
            $update = array(
                'admin_last_ip' => get_ip(),
                'admin_last_time' => date("Y-m-d H:i:s", time()),
                'admin_login_count' => bcadd((string)$info['admin_login_count'],'1'),
                'admin_update_time' => date('Y-m-d H:i:s', time())
            );
            SystemAdmin::updateInfo($info['admin_id'], $update);
            SystemAdmin::affairCommit();
            unset($info['admin_pwd']);
            $token['userInfo'] = $info;
            return $token;
        }catch (\Exception $exception){
            SystemAdmin::affairRollback();
            throw new \Exception($exception->getMessage());
        }

    }

    /**
     * Notes:退出登录
     * @param string $token
     * @return bool
     * User: yym
     * Date: 2022/8/3
     */
    public static function loginOut(string $token)
    {
        if(empty($token))
        {
            return true;
        }
        JwtToken::delKey(1, $token);
        return true;
    }
}
