<?php
/**
 * Created by PhpStorm.
 * User: Titan 名字就是密码
 * Date: 2019/6/4
 * Time: 11:56
 */

namespace app\index\model;


use think\Model;

class User extends Model
{

    protected $table = 'admin';
    public function login($username,$password,$ip)
    {
        if(!$username){
            $this->error = "用户名不能为空";
            return false;
        }
        if(!$password){
            $this->error = "用户密码不能为空";
        }
        $map["username"] = $username;
        $map["password"] = $password;
        $userInfo = $this->where($map)->find();
        $result2 = $this->where(['id'=>1])->find();              //获取普通管理员信息
        if(!$userInfo){
            //用户名和密码不正确就对错误次数进行更新
            $err_num = $result2['error_num'];   //获取出来错误的次数
            $err_num++;                         //对错误数量进行更新
            $error_data=[
                'error_num'=>$err_num           //错误次数
            ];
            $result1 = $this->where(['id'=>1])->update($error_data);   //更新数据  (主要更新错误次数)
            if($result1){
                $this->error = "用户名或密码错误";
                return false;
            }else{
                $this->error = "服务内部错误";
                return false;
            }

        }

        if($userInfo['id'] == 2){

            return $this->getToken($userInfo);
        }
        if($result2['error_num']>=3){
            $this->error = "管理员权限已经锁定";
            return false;
        }
        if($userInfo['ip'] || ($userInfo['is_reg']==1)){
            $this->error = "已有用户登录";
            return false;
        }

        $update_data=[
            'ip' =>$ip,        //登录的ip
            'is_reg'=>1,       //登录的状态(1为登录,0为未登录)
            'error_num'=>0     //错误的数量重新置为0
        ];
        $result1 = $this->where($map)->update($update_data);   //更新数据
        if($result1){
            return $this->getToken($userInfo);
        }

    }

    public function getToken($userInfo)
    {
        // 保存缓存
        session_start();
        $info['userinfo'] = $userInfo;
        $info['nickname'] = $userInfo['nickname'];
        $info['sessionId'] = session_id();
        $authKey = md5($userInfo['username'].$userInfo['password'].$info['sessionId']);
        $info['authKey'] = $authKey;
        cache('Auth_'.$authKey, null);
        cache('Auth_'.$authKey, $info,7200);
        return $info;
    }
}