<?php

namespace app\admin\model;

use think\Model;
use app\admin\model\Role as RoleModel;
use app\apicom\model\JWT;
use think\facade\Db;
use util\RedisUtil;
/**
 * 后台用户模型
 * @package app\admin\model
 */
class User extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'admin_user';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 对密码进行加密
    public function setPasswordAttr($value)
    {
        return password_hash(strval($value),PASSWORD_DEFAULT);
    }

    // 获取注册ip
    public function setSignupIpAttr()
    {
        return getClientIp();
    }

    /**
     * 用户登录
     * @param string $username 用户名
     * @param string $password 密码
     * @param bool $rememberme 记住登录
     * @author 路人甲乙
     * @return bool|mixed
     */
    public static function login($username = '', $password = '', $rememberme = false)
    {
        $username = trim($username);
        $password = trim($password);
        // 匹配登录方式
        if (preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/", $username)) {
            // 邮箱登录
            $map['email']    = $username;
        } elseif (preg_match("/^1\d{10}$/", $username)) {
            // 手机号登录
            $map['mobile']   = $username;
        } else {
            // 用户名登录
            $map['username'] = $username;
        }
        $map['status'] = 1;
        // 查找用户
        $user = self::where($map)->find()->toArray();
        
        if (!$user) return ['status'=>0, 'message'=>'用户不存在或被禁用'];
        // 检查是否分配用户组
        if ($user['role'] == 0) {
            return ['status'=>0, 'message'=>'禁止访问，原因：未分配角色！'];
        }
        // 检查是可登录后台
        if (!RoleModel::where('id', $user['role'])->value('access')) {
            return ['status'=>0, 'message'=>'禁止访问，原因：用户所在角色禁止访问后台！'];
        }
        
        //print_r(password_hash($password,PASSWORD_DEFAULT));return;
        if ($user && password_verify($password, $user['password'])) {
            // 更新登录信息
            $user['create_time'] = time();
            $user['update_time'] = time();
            $user['last_time']   = time();
            $user['last_login_ip'] = getClientIp();
            if ($res = self::strict(false)->save($user)) {
                 $token = array(
                    "aid"  => $user['id'],
                    "pid"  => $user['pid'],
                    "name" => $user['username'],
                    "nick" => $user['nickname'],
                    "role" => $user['role'],
                    'time' => time(),
                );
                $jwt = JWT::encode($token,LOCAL_TRADING_TOKEN);
                RedisUtil::cacheAdminToken($jwt, $token);
                $datas['aid']   = $user['id'];
                $datas['token'] = $jwt;
                $datas['name']  = $user['username'];
                $datas['nick']  = $user['nickname'];
                // 自动登录
                //$login = $this->autoLogin($user, $rememberme);
                return ['status'=>1, 'message'=>'登陆成功！','data'=>$datas];
            } else {
                // 更新登录信息失败
                return ['status'=>0, 'message'=>'登录信息更新失败，请重新登录'];
            }
        } else {
            return ['status'=>0, 'message'=>'密码错误！'];
        }
    }

    /**
     * 自动登录
     * @param object $user 用户对象
     * @param bool $rememberme 是否记住登录，默认7天
     * @author 路人甲乙
     * @return bool|int
     */
    public function autoLogin($user, $rememberme = false)
    {
        // 记录登录SESSION和COOKIES
        $auth = array(
            'uid'             => $user['id'],
            'group'           => $user['group'],
            'role'            => $user['role'],
            'role_name'       => Db::name('admin_role')->where('id', $user['role'])->value('name'),
            'avatar'          => $user['avatar'],
            'username'        => $user['username'],
            'nickname'        => $user['nickname'],
            'last_login_time' => $user['last_login_time'],
            'last_login_ip'   => getClientIp(),
        );
        session('user_auth', $auth);
        session('user_auth_sign', data_auth_sign($auth));

        // 保存用户节点权限
        if ($user['role'] != 1) {
            $menu_auth = Db::name('admin_role')->where('id', session('user_auth.role'))->value('menu_auth');
            $menu_auth = json_decode($menu_auth, true);
            if (!$menu_auth) {
                session('user_auth', null);
                session('user_auth_sign', null);
                return false;
            }
        }

        // 记住登录
        if ($rememberme) {
            $signin_token = $user['username'].$user['id'].$user['last_login_time'];
            cookie('uid', $user['id'], 24 * 3600 * 7);
            cookie('signin_token', data_auth_sign($signin_token), 24 * 3600 * 7);
        }

        return $user['id'];
    }
}
