<?php
namespace App\Domains\Auth\Http\Controllers;

use App\Core\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AdminAuthController extends Controller
{
    protected $request;
    protected $auth;

    /**
     * 构造函数，自动注入.
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->auth = app('auth:admin');
    }

    /**
     * 登录
     *
     * @return \Illuminate\Http\Response
     */
    public function login()
    {
        $rule = [
            'username' => ['required', 'username', 'display_length:2,12'],
            'password' => ['required', 'string'],
            'remember' => ['in:0,1'],
        ];


        $message = [
            'username.required' => '请输入用户名',
            'username.username' => '用户名不正确',
            'username.display_length' => '用户名不正确',
            'password.required' => '请输入密码',
            'password.string' => '密码不正确',
        ];

        Validator::validate($this->request->all(), $rule, $message);

        $username = $this->request->get('username');
        $password = $this->request->get('password');
        $remember = $this->request->get('remember', 0);

        $token = $this->auth->login($username, $password, $remember);

        return res($token, '登录成功', 200, [
            'new-token' => $token
        ]);
    }


    /**
     * 登出
     *
     * @return \Illuminate\Http\Response
     */
    public function logout()
    {
        $this->auth->logout();
        return res(true, '登出成功');
    }

    /**
     * 账户信息
     *
     * @return \Illuminate\Http\Response
     */
    public function info()
    {
        $account = app('dipper')->initAccount();

        $permissions = $account->getAllPermissions();

        $account->setRelations([
            'roles' => $account->getRoleNames(),
            'permissions' => $permissions->toTree(),
        ]);

        return res(['account' => $account], '账号信息', 201);
    }
}
