<?php

namespace app\controller\admin\auth;

use app\BaseController;
use app\service\admin\LoginService;
use think\exception\ValidateException;

class LoginController extends BaseController
{
    public function captcha()
    {
        $captcha = file_get_contents("https://v2.eleadmin.com/api/captcha");
        $captchaData = json_decode($captcha, true);

        return $this->writeSuccess('登录成功', [
            'base64'=> $captchaData['data']['base64'] ?? '',
            'text'=> $captchaData['data']['text'] ?? '',
        ]);
    }
    public function index()
    {
        $username = $this->request->post('username', '');
        $password = $this->request->post('password', '');
        $remember = $this->request->post('remember', false);
        $code = $this->request->post('code', '');

        $loginService = new LoginService();
        try {
            $result = $loginService->login($this->request, $this->request->getClient(), $username, $password, $code, $remember);
        } catch (ValidateException $e) {
            return $this->writeError($e->getError());
        }

        return $this->writeSuccess('登录成功', ['user' => $result['user'], 'access_token' => $result['access_token']]);
    }
}
