<?php

namespace app\index\controller;

use app\BaseController;
use app\common\api\UserApi;

/**
 * Description of Login
 *
 * @author sgq
 */
class Auth extends BaseController {

    /**
     * 登录
     * @return type
     */
    public function login() {
        $msg = "";
        if ($this->request->isPost()) {
            $username = $this->request["username"];
            $pwd = $this->request["password"];
            $usertype = $this->request["usertype"];
            $user = new UserApi($username, $pwd, $usertype);
            if (!$userinfo = $user->getUserInfo()) {
                $msg = "用户不存在";
            }
            if (!$user->checkPwd()) {
                $msg = "用户名或者密码错误";
            }
            $url = "/admin";
            switch ($usertype) {
                case 1:
                    //验证错误
                    break;
                case 2:
                    //验证错误
                    $url = "/enterprise";
                    break;
                case 3:
                    //验证错误
                    $url = "/person";
                    break;
            }
            if (!$msg) {
                $user->setSession();
                if (session("user")) {
                    return redirect($url);
                }
            }
        }
        return view("", ["msg" => $msg]);
    }

    /**
     * 退出
     * @return type
     */
    public function logout() {
        session("user", null);
        return redirect("/index/auth/login");
    }

    /**
     * 验证密码
     */
    public function valid_password() {
        if ($user = session("user")) {
            $username = $user["account"];
            $usertype = $user["usertype"];
            $pwd = $this->request["password"];
            $user = new UserApi($username, $pwd, $usertype);
            if (!$user->checkPwd()) {
                return json()->data(["status" => 1, "msg" => "密码错误"]);
            } else {
                return json(["code" => 200]);
            }
        } else {
            return json()->data(["status" => 2]);
        }
    }

}
