<?php

namespace app\admin\service\auth;

use app\model\SysRole;
use app\model\SysUser;
use support\Db;
use support\Request;
use Tinywan\Jwt\JwtToken;

class AuthService
{
    public static function login($params)
    {
        DB::beginTransaction();
        try {
            $user = SysUser::findByLoginName($params['username']);
            if (!$user || $user->user_login_pass != md5(sha1($params['password']))) {
                throw new \Exception('账号 / 密码错误');
            }
            // 禁用用户
            if ($user->user_status == 'DISABLED') {
                throw new \Exception('当前账户已禁用，请联系管理员');
            }
            switch ($user->user_status) {
                case 'DISABLED':
                    throw new \Exception('当前账户已禁用，请联系管理员');
                    break;
                case 'PENDING':
                    // 待激活用户登录后自动激活
                    $user->user_status = 'ACTIVED';
                    if (!$user->save()) {
                        throw new \Exception('用户状态修改失败');
                    }
                    break;
                default:
                    break;
            }
            $extend = [
                'id' => $user->user_id,
                'client' => 'admin',
                'name'=> $user->user_name,
                'join_user_dept_id' => $user->join_user_dept_id
            ];
            $token = JwtToken::generateToken($extend);

            $user->user_login_status = "ONLINE";
            $user->save();

            // 提交事务
            DB::commit();
            // 写操作日志
            _syslog("登录", "管理员【" . $params['username'] . "】登录系统; ID：" . $user->user_id, false, ['username'=>$params['username']], $user->user_id);

            return json_success('', $token);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();

            return json_fail($e->getMessage());
        }
    }

    /**
     * @Desc 刷新token
     * @Author Gorden
     * @Date 2024/2/21 17:10
     *
     * @return \support\Response
     */
    public static function refreshToken()
    {
        $token = JwtToken::refreshToken();

        return json_success('Token已刷新', $token);
    }

    public static function userInfo(Request $request)
    {
        $user = SysUser::select('user_id', 'join_user_role_id', 'join_user_dept_id', 'user_status', 'user_category', 'user_name', 'user_login_name', 'user_mobile', 'user_remark', 'user_extend_json', 'user_addtimes')
            ->where('user_id', $request->adminId)
            ->first()
            ->toArray();

        $user['roleName'] = '';
        if (!empty($user['join_user_role_id'])) {
            $role = SysRole::where('role_id', $user['join_user_role_id'])->first();
            if (!empty($role->role_name)) {
                $user['roleName'] = $role->role_name;
            }
        }

        return json_success('', $user);
    }
}