<?php

namespace app\controller;

use app\model\AuthRule;
use app\model\LoginLog;
use app\model\Member;
use app\service\Jwt;

class ApiManager extends Base
{
    public function index()
    {
//        $jwtData = [
//            'member_id'     => "11",
//        ];
//        $token =  Jwt::generate($jwtData);

        $token = input("token/s","");
        $userInfo = Jwt::parse($token);//token中携带的简易用户信息
        if(empty($userInfo)||!array_key_exists("member_id",$userInfo)){
            return $this->json(4001,"无效请求");
        }
        $member = Member::getById($userInfo["member_id"]);
        if(empty($member)){
            return $this->json(4001,"用户不存在");
        }

        //执行登录
        $rulesList = AuthRule::userRolesList($member['group_id']);
        $rulesIdStr = '';
        if (!empty($rulesList)) {
            $rulesId = $rulesList['allRulesId'];
            $rulesIdStr = implode(',', $rulesId);
        }
        $authSession = [
            'userId' => $member['id'],
            'userName' => $member['username'],
            'groupId' => $member['group_id'],
            'rules' => $rulesIdStr,
            'cates' => $member['cates']
        ];

        //记录最后登陆时间
        $ip = request()->ip();
        $time = time();
        Member::updateById($member['id'], [
            'login_time' => $time,
            'login_ip' => $ip
        ]);
        LoginLog::create([
            'member_id' => $member['id'],
            'name' => $member['username'],
            'ip' => $ip,
            'create_time' => $time
        ]);
        session('auth', $authSession);

        return $this->redirect("/manager");
    }

}