<?php

namespace App\Http\Controllers\Account;

use App\Facade\Site;
use App\Consts\ErrorConst;
use App\Exceptions\ApiException;
use App\Libs\ApiResponse;
use App\Libs\Utils;
use App\Services\Account\AccountService;
use App\Transformer\Account\AccountTransformer;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;

class AccountController extends BaseController
{
    use ApiResponse;
    protected $accountService;

    public function __construct(
        AccountService $accountService
    ) {
        $this->accountService = $accountService;
    }

    public function index(Request $request)
    {
        return view('index');
    }

    /**
     * 登录
     *
     * @param Request $request
     * @return mixed
     * @throws ApiException
     */
    public function login(Request $request)
    {
        $all      = $request->all();
        $account  = trim(getProp($all, 'account'));
        $passwd = trim(getProp($all, 'passwd'));
        if (strlen($account) < 1 || strlen($passwd) < 1) {
            Utils::throwError(ErrorConst::PARAM_ERROR_CODE);
        }

        // 登录
        $user = $this->accountService->login($account, $passwd);
        return $this->success($user);
    }

    /**
     * 退出登录
     *
     * @return mixed
     */
    public function logout()
    {
        // 当前登录用户
        $token = Site::getToken();

        // 退出
        $result = $this->accountService->logout($token);
        return $this->success(['success' => $result ? 1 : 0]);
    }
}
