<?php

declare(strict_types=1);

namespace app\wander\controller;

use app\BaseController;
use app\common\model\account\User;
use app\common\model\Base;
use app\Request;
use think\response\Json;

/**
 * Class Account
 * @package app\wander\controller
 */
class Session extends BaseController
{
    /**
     * @param Request $request
     * @return Json
     */
    public function auth(Request $request)
    {
        $input = $request->post();
        $params = Base::existsParams($input, ['username']);
        if (is_error($params)) {
            return payload($params);
        }
        $password = isset($input['password']) ? $input['password'] : '';
        $userInfo = User::fetch(['uid' => $params['username']]);
        if (empty($userInfo)) {
            return payload(error(-10, '用户不存在'));
        } elseif (!empty($userInfo['password']) && !empty($password) && $userInfo['password'] !== Base::encodePassword($userInfo['salt'], $password)) {
            return payload(error(-11, '密码错误'));
        } elseif ((!empty($userInfo['password']) && empty($password)) || (empty($userInfo['password']) && !empty($password))) {
            return payload(error(-12, '密码错误'));
        }
        if (empty($userInfo['status']) || ($userInfo['status'] != 'normal')) {
            return payload(error(-13, '账号被禁用'));
        }
        session('exam_dock', $userInfo['id']);
        return payload();
    }
}
