<?php

declare(strict_types=1);

namespace app\wander\controller\control;

use app\common\model\account\User;
use app\common\model\Base;
use app\Request;
use think\facade\Db;
use think\facade\Log;
use think\response\Json;
use ZipStream\ZipStream;

/**
 * Class Account
 * @package app\wander\controller\wander
 */
class Account
{
    /**
     * @param Request $request
     * @return Json
     *
     * @api {post} control/account/auth 登录
     * @apiGroup Wander
     * @apiName sort1
     * @apiVersion 1.0.0
     *
     * @apiDescription 登录用户
     *
     * @apiParam {string} username  账号
     * @apiParam {string} password  密码
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"errCode":0,"errMsg":""}
     *
     * @apiErrorExample {json} Error-Response:
     * {"errCode":5001,"errMsg":"接口异常"}
     *
     */
    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(-20, '用户不存在'));
        } elseif (!empty($userInfo['password']) && !empty($password) && $userInfo['password'] !== Base::encodePassword($userInfo['salt'], $password)) {
            return payload(error(-21, '密码错误'));
        } elseif ((!empty($userInfo['password']) && empty($password)) || (empty($userInfo['password']) && !empty($password))) {
            return payload(error(-22, '密码错误'));
        }
        if (empty($userInfo['status']) || $userInfo['status'] != 'normal') {
            return payload(error(-23,'账号被禁用'));
        }
        session('exam_control', $userInfo['id']);
        return payload();
    }
}