<?php

namespace MpApi\Controller;

use Think\Controller;
use Firebase\JWT\JWT;

class LoginController extends Controller
{
	private $shop_id;

	/**
	 * @Description: 登陆接口
	 * @Return: 
	 */
	public function login()
	{
		header("Access-Control-Allow-Origin: " . C('LimitApi')); //请求域名限制
		header('Access-Control-Allow-Headers:Token'); //token请求头

		if (!$_POST['username']) {
			echo json_encode(array('status' => 0, 'msg' => '用户名不能为空'), JSON_UNESCAPED_UNICODE);
			exit;
		}
		if (!$_POST['password']) {
			echo json_encode(array('status' => 0, 'msg' => '密码不能为空'), JSON_UNESCAPED_UNICODE);
			exit;
		}

		$adminuserDb = D('adminuser');
		$where['name'] = $_POST['username'];
		$where['del'] = '0';
		$adminInfo = $adminuserDb->where($where)->field('name,uname,pwd,qx,shop_id,photo,lasttime')->find();
		if ($adminInfo) {
			if (MD5(MD5($_POST['password'])) == $adminInfo['pwd']) {
				//登陆成功
				$this->shop_id = $adminInfo['shop_id'];
				$data['lasttime'] = time();
				$adminuserDb->where($where)->save($data); //最后登录时间写入数据库
				//从program表拿用户头像
				$adminInfo['photo'] = json_decode($adminInfo['photo'])[0]; //反序列化 取到头像名称
				switch ($adminInfo['qx']) {
					case 4:
						$adminInfo['power'] = 'admin';
						break;
					case 5:
						$adminInfo['power'] = 'editor';
						break;
				}
				//删除多余信息
				unset($adminInfo['pwd']);
				//创建token
				$token = $this->makeToken();
				//登陆成功 返回token
				echo json_encode(array('status' => 1, 'msg' => '登陆成功', 'adminInfo' => $adminInfo, 'token' => $token), JSON_UNESCAPED_UNICODE);
			} else {
				//密码错误
				echo json_encode(array('status' => 0, 'msg' => '登陆失败'), JSON_UNESCAPED_UNICODE);
				exit;
			}
		} else {
			//账号不存在或已注销
			echo json_encode(array('status' => 0, 'msg' => "登陆失败"), JSON_UNESCAPED_UNICODE);
			exit;
		}
	}
	/**
	 * @Description: 构建token
	 * @Return: token
	 */
	private function makeToken()
	{
		$jwtKey = C('jwtKey'); // jwt密钥
		$currtime = time();
		// 要存储在 JWT 中的数据
		$data = [
			'iat' => $currtime,    	// 签发时间（时间戳）
			'iss' => 'jwt_admin',      // 签发者
			'nbf' => $currtime,    // 在此时间之前不可用 (这里是2秒以内)
			'exp' => strtotime('tomorrow'), //过期时间 到第二天凌晨
			'jti' => md5(uniqid('JWT') . $currtime),
			'sub' => 'http://localhost:8080',
			'shop_id' => $this->shop_id,
		];
		// 使用密钥和 HS256 算法对数据进行编码生成 JWT
		return JWT::encode($data, $jwtKey, 'HS256');
	}
}
