<?php
/**
 *
 *User:Administrator
 *Date:2021/10/8
 */

namespace app\api\business;

use app\api\model\Jcdw;
use app\api\model\Jgry;
use app\common\lib\auth\JwtAuth;
use app\common\model\mysql\Ry;
use app\api\exception\ApiException;
use think\facade\Cache;

class LoginBus
{
    public function login($username,$password)
    {
        //从人员表中查询数据
        $jgry_info=(new Jgry())->getUserInfoByRybh($username);
        //从检测单位表中查询数据
        $jcdw_info=(new Jcdw())->getInfoByLoginName($username);
        //用户名都不存在则抛出异常
        if (!$jgry_info && !$jcdw_info) {
            throw new ApiException(config('status.err_user_not_exist'));
        }
        //在ry表中查询到数据，则验证用户名和密码
        if (isset($jgry_info['rybh']) && $jgry_info['kl']==$password) {
            $data=[
                'id' => $jgry_info['id'],
                'groupname'=>$jgry_info['groupname'],
                'rymc'=>$jgry_info['rymc'],
                'name'=>'',
                'rybh'=>$jgry_info['rybh'],
                'qydm'=>$jgry_info['qydm'],
            ];
        }
        //在jcdw表中查询到数据，则验证用户名和密码
        if (isset($jcdw_info['login_name']) && $jcdw_info['pwd'] == $password) {
            //return '正确2';
            $data=[
                'id' => $jcdw_info['id'],
                'groupname'=>$jcdw_info['groupname'],
                'rymc'=>$jcdw_info['login_name'],
                'name'=>$jcdw_info['name'],
                'rybh'=>'',
                'qydm'=>$jcdw_info['qydm'],
            ];
        }



        //实例化JwtAuth，生成token
        $jwt_auth=JwtAuth::getInstance();
        $token = $jwt_auth
            ->setGroupname($data['groupname'])
            ->setRymc($data['rymc'])
            ->setName($data['name'])
            ->setRybh($data['rybh'])
            ->setQydm($data['qydm'])
            ->setUid($data['id'])
            ->encode()
            ->getToken();

        //将ip存到redis中，通过middleware验证 todo
        $real_ip = request()->ip();
        Cache::store('redis')->set($real_ip,$token,1 * 24 * 3600);

        //data数组添加两条数据
        $data['token']=$token;
        $data['re_ip']=$real_ip;
        return $data;
    }


}