<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展 
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
namespace app\adminapi\service\login;

use app\adminapi\service\auth\AdminService;
use app\adminapi\service\login\CaptchaService;
use app\dict\sys\AppTypeDict;
use app\Request;
use core\base\BaseService;
use core\util\TokenAuth;

class LoginService extends BaseService
{
    /**
     * 登录
     * @param string $account  账号
     * @param string $password 密码
     * @param string $captcha  验证码（可选）
     * @param string $captchaKey 验证码唯一标识（可选）
     * @return array|false
     */
    public function login($account, $password, $captcha = '', $captchaKey = ''){
        // 检查是否需要验证码
        if (CaptchaService::isEnabled()) {
            if (empty($captcha)) {
                self::setError('请输入验证码');
                return false;
            }
            // 校验验证码
            $captchaService = new CaptchaService();
            if (!$captchaService->verify($captcha, $captchaKey)) {
                self::setError(CaptchaService::getError());
                return false;
            }
        }
        $adminInfo = (new AdminService())->byAccountGetAdminInfo($account);
        if ($adminInfo->isEmpty()) {
            self::setError('账号不存在');
            return false;
        }

        if (!check_password($password, $adminInfo->password)) {
            self::setError('密码错误');
            return false;
        }

        if ($adminInfo->is_disable) {
            self::setError('账号已被禁用,请联系管理员');
            return false;
        }

        $adminInfo->login_time = time();
        $adminInfo->login_ip = request()->ip();
        $adminInfo->save();

        $tokenInfo = TokenAuth::createToken($adminInfo->id,AppTypeDict::ADMIN,[
            'admin_id' => $adminInfo->id,
            'account' => $adminInfo->account,
        ],config('app.admin_token_expire_time',2592000));

        // 记录登录日志
        $operationLogModel = new \app\adminapi\model\OperationLog();
        $operationLogModel->save([
            'admin_id' => $adminInfo->id,
            'admin_name' => $adminInfo['name'],
            'action' => '登录',
            'account' => $adminInfo->account,
            'url' => request()->url(true),
            'type' => 'POST',
            'params' => json_encode(['account' => $account, 'password' => '******'], true),
            'ip' => request()->ip(),
            'result' => json_encode(['code' => 1, 'msg' => '登录成功'], true),
        ]);

        return [
            'name' => $adminInfo['name'],
            'avatar' => $adminInfo['avatar'],
            'role_name' => $adminInfo['role_name'],
            'token' => $tokenInfo['token'],
        ];


    }

    public function logout($adminId){
        TokenAuth::clearToken($adminId,AppTypeDict::ADMIN,$this->request->getAdminToken());
        return true;
    }
}