<?php

namespace app\controller\common;

use app\extra\basic\Base;
use app\middleware\AuthMiddleware;
use app\model\system\SystemUser;
use Hzdad\Codecheck\Codecheck;
use LinFly\Annotation\Route\Controller;
use LinFly\Annotation\Route\Route;
use Shopwwi\WebmanAuth\Auth;
use support\Request;
use support\Response;
use think\facade\Db;
use Tinywan\Captcha\Captcha;
use LinFly\Annotation\Route\Middleware;


#[Controller(prefix: "/api/login")]
class Login extends Base
{

    /**
     * 登陆
     * @param Request $request
     * @return Response
     */
    #[Route(path: "user",methods: "post")]
    public function setLogin(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "username.require"  => trans("empty.user"),
                "password.require"  => trans("empty.passwd"),
                "code.require"      => trans("empty.code"),
                "key.require"       => trans("empty.data"),
            ],"post");
            if (!is_array($param)) return error($param);
            if (Captcha::check($param['code'],$param['key']) === false) return errorTrans("error.captcha");
            $map = ["is_deleted" => 0,"username" => $param['username']];
            [$state,$msg,$user] = $this->checkLogin($map,2,$param);
            if (!$state) return error($msg);
            return successTrans("success.login",get_object_vars((new Auth)->guard("admin")->login($user)));
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


    /**
     * 登录验证处理
     * @param array $map
     * @param int $type
     * @param array $param
     * @return array
     */
    protected function checkLogin(array $map = [],int $type = 1,array $param = []): array
    {
        $user = (new SystemUser)->where($map)->findOrEmpty();
        if ($user->isEmpty()) return [0,trans("error.user-empty"),[]];
        if ($user['status'] <> 1) return [0,trans("error.user-status"),[]];
        if ($type == 2) {
            if (md5($param['password'].$user['salt']) <> $user['password']) return [0,trans("error.passwd"),[]];
        }
        $user->login_at = getDateFull();
        $user->login_ip = request()->getRealIp();
        $user->login_num = Db::raw("login_num+1");
        $user->save();
        return [1,'success',$user->toArray()];
    }

    /**
     * @return Response
     */
    #[Route(path: "profile",methods: "get"),Middleware(AuthMiddleware::class)]
    public function getLoginUser(): Response
    {
        try {
            $userData = (new Auth)->guard("admin")->user()->toArray();
            if (isset($userData['password'])) unset($userData['password']);
            return successTrans("success.data",[
                "username"  => $userData['username'],
                "truename"  => $userData['truename'],
                "agent_id"  => $userData['agent_id'],
                "super"     => $userData['is_super'],
                "type"      => $userData['type']
            ]);
        } catch (\Throwable $exception){
            return error($exception->getMessage());
        }
    }

}