<?php


namespace addons\webman\common;

use addons\webman\Admin;
use addons\webman\model\AdminDepartment;
use ExAdmin\ui\component\Component;
use ExAdmin\ui\contract\LoginAbstract;
use ExAdmin\ui\response\Message;
use ExAdmin\ui\response\Response;
use ExAdmin\ui\support\Container;
use ExAdmin\ui\support\Token;
use support\Cache;

class Login extends LoginAbstract
{

    /**
     * 登陆页
     * @return Component
     */
    public function index(): Component
    {
        $view = Request()->header('App-Name') == 'agent' ? 'agent.vue' : 'login.vue';
        return admin_view(plugin()->webman->getPath(). '/views/' . $view)->attrs([
            'webLogo' => admin_sysconf('web_logo'),
            'webName' => admin_sysconf('web_name'),
            'webMiitbeian' => admin_sysconf('web_miitbeian'),
            'webCopyright' => admin_sysconf('web_copyright'),
            'deBug' => env('APP_DEBUG'),
            'agent_login' => admin_trans('login.agent_login'),
            'admin_login' => admin_trans('login.admin_login'),
            'enter_account' => admin_trans('login.enter_account'),
            'enter_password' => admin_trans('login.enter_password'),
            'enter_verify' => admin_trans('login.enter_verify'),
            'login' => admin_trans('login.login'),
            'password_verify' => admin_trans('login.password_verify'),
        ]);
    }

    /**
     * 登陆页
     * @return Component
     */
    public function agent(): Component
    {
        return admin_view(plugin()->webman->getPath(). '/views/agent.vue')->attrs([
            'webLogo' => admin_sysconf('web_logo'),
            'webName' => admin_sysconf('web_name'),
            'webMiitbeian' => admin_sysconf('web_miitbeian'),
            'webCopyright' => admin_sysconf('web_copyright'),
            'deBug' => env('APP_DEBUG'),
            'agent_login' => admin_trans('login.agent_login'),
            'admin_login' => admin_trans('login.admin_login'),
            'enter_account' => admin_trans('login.enter_account'),
            'enter_password' => admin_trans('login.enter_password'),
            'enter_verify' => admin_trans('login.enter_verify'),
            'login' => admin_trans('login.login'),
            'password_verify' => admin_trans('login.password_verify'),
        ]);
    }

    /**
     * 登录验证
     * @param array $data 提交数据
     * @return Message
     */
    public function check(array $data): Message
    {
        $validator = validator($data, [
            'username' => 'required',
            'source' => 'required',
            'password' => 'required|min:5'
        ], [
            'username.required' => admin_trans('login.account_not_empty'),
            'password.required' => admin_trans('login.password_not_empty'),
            'source.required' => admin_trans('login.source_not_empty'),
            'password.min' => admin_trans('login.password_min_length'),
        ]);
        if ($validator->fails()) {
            return message_error($validator->errors()->first());
        }
        $cacheKey = request()->getRealIp() . date('Y-m-d');
        $errorNum = Cache::get($cacheKey);
        if ($errorNum > 3 && !Container::getInstance()->captcha->check($data['verify'], $data['hash'])) {
            return message_error(admin_trans('login.captcha_error'));
        }
        $model = plugin()->webman->config('database.user_model');
        $type = AdminDepartment::TYPE_DEPARTMENT;
        if ($data['source'] == 'agent') {
            $type = AdminDepartment::TYPE_CHANNEL;
        }
        $user = $model::where('username', $data['username'])->where('type', $type)->first();
        if (!$user || !password_verify($data['password'], $user->password)) {
            Cache::set($cacheKey, $errorNum + 1);
            return message_error(admin_trans('login.error'));
        }
        return message_success(admin_trans('login.success'))->data([
            'token' => Token::encode($user->toArray()),
        ]);
    }
    /**
     * 获取验证码
     * @return Response
     */
    public function captcha(): Response
    {
        $cacheKey = request()->getRealIp() . date('Y-m-d');
        $errorNum = Cache::get($cacheKey);
        $captcha = Container::getInstance()->captcha->create();
        $captcha['verification'] = $errorNum > 3;
        return Response::success($captcha);
    }
    /**
     * 退出登录
     * @return Message
     */
    public function logout(): Message
    {
        Token::logout();
        $permissionKey = 'ADMIN_PERMISSIONS_' . Admin::id();
        Cache::delete($permissionKey);
        return message_success(admin_trans('login.logout'));
    }
}
