<?php

namespace app\model;

/**
 * @property int user_id
 * @property string user_no
 * @property string nick_name
 * @property string email
 * @property string phone_number
 * @property string login_password
 * @property string salt
 * @property string trade_password
 * @property string invite_code
 * @property string country_code
 * @property int status
 * @property int parent_id
 * @property int origin_user_id
 * @property int agent_id
 * @property int parent_ids
 * @property int is_real
 * @property int head_img_id
 * @property string last_login_time
 * @property string reg_ip
 * @property int sex
 * @property string create_time
 * @property string update_time
 */
class UserModel extends BaseModel
{

    protected $name = 'users';
    protected $pk = 'user_id';

    const STATUS_ON = 1; // 用户启用状态
    const STATUS_FORBID = 2; // 用户禁用状态
    const STATUS_BLACK = 3; // 用户黑名单

    public static $statusMap = [
        self::STATUS_ON => '正常',
        self::STATUS_FORBID => '禁止登录',
        self::STATUS_BLACK => '黑名单',
    ];

    const IS_TEST_USER_NO = 1; // 正常用户
    const IS_TEST_USER_YES = 2; // 测试用户

    public static $isTestUserMap = [
        self::IS_TEST_USER_NO => '正常用户',
        self::IS_TEST_USER_YES => '测试用户'
    ];

    const LEVER_STATUS_NO = 1; // 未申请
    const LEVER_STATUS_APPLY = 2; // 申请中
    const LEVER_STATUS_PASSED = 3; // 通过
    const LEVER_STATUS_FAIL = 4; // 拒绝

    /**
     * @desc 邮箱是否已经被注册
     * @param $email
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public static function checkEmailExists($email): bool
    {
        $count = self::where('email', $email)->count();
        return $count > 0;
    }

    /**
     * @desc 判断手机号是否已经被注册
     * @param $phone
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public static function checkPhoneExists($phone): bool
    {
        $count = self::where('phone_number', $phone)->count();
        return $count > 0;
    }

    /**
     * @desc 根据邮箱获取用户id
     * @param $email
     * @return int|mixed
     */
    public static function getUserIdByEmail($email)
    {
        $userId = self::where('email', $email)->value('user_id');
        return $userId ?? 0;
    }

    /**
     * @desc 根据用户id获取登陆密码
     * @param $id
     * @return mixed
     */
    public static function getPasswordById($id)
    {
        return self::where('user_id', $id)->value('login_password');
    }

    /**
     * @desc 根据用户id获取邮箱
     * @param $id
     * @return mixed
     */
    public static function getEmailById($id)
    {
        return self::where('user_id', $id)->value('email');
    }

    /**
     * @desc 根据国家码和手机号获取用户id
     * @param $nation
     * @param $phone
     * @return int|mixed
     */
    public static function getUserIdByNationAndPhone($nation, $phone)
    {
        $userId = self::where('country_code', $nation)
            ->where('phone_number', $phone)
            ->value('user_id');
        return $userId ?? 0;
    }
    /**
     * @desc 根据用户id 查询指定字段
     * @param $fields
     * @param $userId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getFieldsByUserId($fields, $userId): array
    {
        $self = self::where('user_id', $userId)->field($fields)->find();
        if(empty($self)){
            return [];
        }
        return $self->toArray();
    }
    /**
     * @desc 获取邀请码用户
     * @param $inviteCode
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getUserByInviteCode($inviteCode): array
    {
        $self = self::where('invite_code', $inviteCode)->field('user_id')->find();

        if(empty($self)){
            return [];
        }
        return $self->toArray();
    }

    public static function updateFieldsByUserId($fields, $userId)
    {
        $self = self::where('user_id', $userId)->find();
        foreach ($fields as $key=>$value) {
            $self->$key = $value;
        }
        $self->update_time = date('Y-m-d H:i:s');
        $self->save();
    }

    /**
     * @desc 更新登陆密码
     * @param $password
     * @param $userId
     * @return void
     */
    public static function updatePassword($password, $salt, $userId)
    {
        self::update(['login_password' => $password, 'salt' => $salt], ['user_id' => $userId]);
    }

    /**
     * @desc 邮箱用户注册
     *
     * @param $email
     * @param $userNo
     * @param $inviteCode
     * @param $parentId
     * @param $password
     * @param $ip
     * @return int
     */
    public static function emailRegister($email, $userNo, $inviteCode, $parentId, $password, $ip, $salt, $isTestUser, $agentId): int
    {
        $self = new self;
        $self->email = $email;
        $self->user_no = $userNo;
        $self->invite_code = $inviteCode;
        $self->parent_id = $parentId;
        $self->agent_id = $agentId;
        $self->login_password = $password;
        $self->salt = $salt;
        $self->reg_ip = $ip;
        $self->is_test_user = $isTestUser;

        $self->nick_name = 'user_'.explode('@', $email)[0];
        $self->create_time = date('Y-m-d H:i:s');
        $self->update_time = date('Y-m-d H:i:s');

        // 查询父级
        $parentIds = '';
        $originUserId = 0;
        if($parentId > 0){
            $parentUser = self::where('user_id', $parentId)->findOrEmpty();
            if($parentUser){
                $parentIds = $parentUser['parent_ids']? $parentUser['parent_ids'].','.$parentId : $parentId;
                // 如果祖先id = 0 说明这个父级就是祖先id
                $originUserId = $parentUser['origin_user_id'] == 0? $parentId : $parentUser['origin_user_id'];
            }
        }

        $self->origin_user_id = $originUserId;
        $self->parent_ids = $parentIds;

        $self->save();
        return $self->user_id;
    }

    /**
     * @desc 手机号注册
     * @param $nation
     * @param $phone
     * @param $userNo
     * @param $inviteCode
     * @param $parentId
     * @param $password
     * @param $ip
     * @param $salt
     * @return int
     */
    public static function phoneRegister($nation, $phone, $userNo, $inviteCode, $parentId, $password, $ip, $salt, $isTestUser, $agentId): int
    {
        $self = new self;
        $self->country_code = $nation;
        $self->phone_number = $phone;
        $self->user_no = $userNo;
        $self->invite_code = $inviteCode;
        $self->parent_id = $parentId;
        $self->agent_id = $agentId;
        $self->login_password = $password;
        $self->salt = $salt;
        $self->reg_ip = $ip;
        $self->is_test_user = $isTestUser;

        $name = 'user_'.substr($phone, -4);
        $self->nick_name = $name;
        $self->create_time = date('Y-m-d H:i:s');
        $self->update_time = date('Y-m-d H:i:s');

        // 查询父级
        $parentIds = '';
        $originUserId = 0;
        if($parentId > 0){
            $parentUser = self::where('user_id', $parentId)->findOrEmpty();
            if($parentUser){
                $parentIds = $parentUser['parent_ids']? $parentUser['parent_ids'].','.$parentId : $parentId;
                // 如果祖先id = 0 说明这个父级就是祖先id
                $originUserId = $parentUser['origin_user_id'] == 0? $parentId : $parentUser['origin_user_id'];
            }
        }

        $self->origin_user_id = $originUserId;
        $self->parent_ids = $parentIds;


        $self->save();
        return $self->user_id;
    }

    /**
     * @desc 设置交易密码
     * @param $password
     * @param $salt
     * @param $userId
     * @return void
     */
    public static function setPayPassword($password, $salt, $userId)
    {
        self::update(['trade_password' => $password, 'salt' => $salt], ['user_id' => $userId]);
    }
}