<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\api\controller;

use app\api\ApiController;
use app\api\middleware\Auth;
use app\home\validate\UserCheck;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Session;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Request;


class HomeLogin extends ApiController
{
    protected $middleware = [
    	Auth::class => ['except' => ['login_submit']]
    ];

    /**
     * @param $user_id
     * @return string
     */
    public function getToken($user_id){
        $time = time(); //当前时间
		$conf = $this->jwt_conf;
        $token = [
            'iss' => $conf['iss'], //签发者 可选
            'aud' => $conf['aud'], //接收该JWT的一方，可选
            'iat' => $time, //签发时间
            'nbf' => $time-1 , //(Not Before)：某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
            'exp' => $time+$conf['exptime'], //过期时间,这里设置2个小时
            'data' => [
                //自定义信息，不要定义敏感信息
                'userid' =>$user_id,
            ]
        ];
        return JWT::encode($token, $conf['secrect'], 'HS256'); //输出Token  默认'HS256'
    }

    //提交登录
    public function login_submit()
    {
        $param = get_params();
        try {
            validate(UserCheck::class)->check($param);
        } catch (ValidateException $e) {
            $this->apiError($e->getError());
        }
        $admin = Db::name('Admin')->where(['username' => $param['username']])->find();
        if (empty($admin)) {
            $admin = Db::name('Admin')->where(['mobile' => $param['username']])->find();
            if (empty($admin)) {
                $this->apiError('用户名或手机号码错误');
            }
        }
        $param['pwd'] = set_password($param['password'], $admin['salt']);
        if ($admin['pwd'] !== $param['pwd']) {
            $this->apiError('用户或密码错误');
        }
        if ($admin['status'] != 1) {
            $this->apiError('该用户禁止登录,请与管理者联系');
        }
        $data = [
            'last_login_time' => time(),
            'last_login_ip' => request()->ip(),
            'login_num' => $admin['login_num'] + 1,
        ];
        $res = Db::name('Admin')->where(['id' => $admin['id']])->update($data);
        if ($res) {
            $logdata = [
                'uid' => $admin['id'],
                'type' => 'login',
                'action' => '登录',
                'subject' => '系统',
                'param_id'=>$admin['id'],
                'param'=>'[]',
                'ip' => request()->ip(),
                'create_time' => time()
            ];
            Db::name('AdminLog')->strict(false)->field(true)->insert($logdata);
            $token = self::getToken($admin['id']);
            $this->apiSuccess('登录成功', ['token' => $token]);
        }
        $this->apiError('登录失败');
    }

    //退出登录
    public function login_out()
    {
        // 前端删除存储的token
        $this->apiSuccess('退出成功');
    }

}