<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/11/2
 * Time: 上午9:16
 */

namespace common\helpers\user;


use common\components\ActiveRecord;
use common\helpers\Cache;
use common\helpers\Tool;
use common\models\BaUser;
use common\models\BaUserInfo;
use common\models\Countries;
use common\models\PerfMonth;
use common\models\PerfPeriod;
use common\models\Period;
use common\models\DeclarationLevel;
use common\models\EmployLevel;
use common\models\OpenBank;
use common\models\Region;
use common\models\User;
use common\models\UserBonus;
use common\models\UserInfo;
use common\models\UserNetwork;
use common\models\UserWallet;
use Yii;
use yii\base\Exception;

class Info {

    /**
     * 获取用户ID
     * @param $userName
     * @return mixed
     */
    public static function getUserIdByUserName($userName) {
        $user = UserInfo::findOneAsArray('USER_NAME=:USER_NAME AND DELETED=0', [':USER_NAME' => $userName], 'USER_ID');
        return $user ? $user['USER_ID'] : null;
    }

    /**
     * 获取会员名通过ID
     * @param $userId
     * @return mixed|null
     */
    public static function getUserNameByUserId($userId) {
        $user = UserInfo::findOneAsArray('USER_ID=:USER_ID AND DELETED=0', [':USER_ID' => $userId], 'USER_NAME');
        return $user ? $user['USER_NAME'] : null;
    }

    /**
     * 获取用户EMAIL
     * @param $userName
     * @return mixed
     */
    public static function getEmailByUserId($userId) {
        $user = UserInfo::findOneAsArray('USER_ID=:USER_ID AND DELETED=0', [':USER_ID' => $userId], 'USER_NAME');
        return $user ? $user['EMAIL'] : null;
    }

    /**
     * 获取会员姓名通过ID
     * @param $userId
     * @return null
     */
    public static function getUserRealNameByUserId($userId) {
        $user = User::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'REAL_NAME');
        return $user ? $user['REAL_NAME'] : null;
    }

    /**
     * 获取会员邮箱通过ID
     * @param $userId
     * @return null
     */
    public static function getUserEmailByUserId($userId) {
        $user = User::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'EMAIL');
        return $user ? $user['EMAIL'] : null;
    }

    /**
     * 获取会员国家通过ID
     * @param $userId
     * @return null
     */
    public static function getUserCountryByUserId($userId) {
        $user = User::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'COUNTRY_ID');
        return $user ? $user['COUNTRY_ID'] : null;
    }

    /**
     * 获取会员语言通过ID
     * @param $userId
     * @return null
     */
    public static function getUserLanguageByUserId($userId) {
        $user = User::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'LANGUAGE_ID');
        return $user ? $user['LANGUAGE_ID'] : null;
    }

    /**
     * 获取手机号通过ID
     * @param $userId
     * @return null
     */
    public static function getUserMobileByUserId($userId) {
        $user = User::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'MOBILE');
        return $user ? $user['MOBILE'] : null;
    }

    /**
     * 通过用户ID获取用户的编号和名称
     * @param $userId
     * @return array|null
     */
    public static function getBaseUserById($userId) {
        return User::findOneAsArray('ID=:ID', [':ID' => $userId], 'ID,USER_NAME,REAL_NAME');
    }

    /**
     * 通过用户ID获取用户的编号和名称
     * @param $username
     * @return array|null
     */
    public static function getBaseUserByUserName($username) {
        return User::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $username]);
    }

    /**
     * 当前期数的会员信息
     * @param $userId
     * @return array|\yii\db\ActiveRecord|null
     * @throws Exception
     */
    public static function baseInfoNowPeriod($userId) {
        $data = User::find()->where('ID=:ID', [':ID' => $userId])->asArray()->one();
        if (!$data) throw new Exception('Member does not exist'.$userId);//会员不存在
        $infoData = UserInfo::find()->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->select('ZC_PV,CON_UID,REC_UID,CON_NUM,REC_NUM,NETWORK_DEEP,RELATION_DEEP,SYSTEM_ID,REG_TYPE,REG_NAME,CREDIT_CODE,PREMISES,LEGAL_PERSON,CLOSE_LOGIN,IS_BIND_MAIN,HIGHEST_EMP_LV,HIGHEST_EMP_LV_PERIOD,SHOULD_REG_TYPE,IS_SYSTEM_LEADER,ALLOW_TRANSFER,TRANSFER_PROP,IS_GROUP_LEADER,GROUP_LEADER_AT,SHOW_EMP_LV')->asArray()->one();
        if ($infoData) {
            $data = array_merge($data, $infoData);
        }
        if (!$data['DEC_LV']) $data['DEC_LV'] = DeclarationLevel::getDefaultLevelId();
        if (!$data['LAST_DEC_LV']) $data['LAST_DEC_LV'] = DeclarationLevel::getDefaultLevelId();
        if (!$data['EMP_LV']) $data['EMP_LV'] = EmployLevel::getDefaultLevelId();
        return $data;
    }

    /**
     * 获取会员信息,通过用户编号
     * @param $userId
     * @return array|\yii\db\ActiveRecord|null
     * @throws Exception
     */
    public static function baseInfoByUserName($userName) {
        $data = User::find()->where('USER_NAME=:USER_NAME', [':USER_NAME' => $userName])->asArray()->one();
        if (!$data) throw new Exception('Member does not exist：'.$userName);//会员不存在
        $userId  = $data['ID'];
        $infoData = UserInfo::find()
        ->where('USER_ID=:USER_ID', [':USER_ID' => $userId])
        ->select('ZC_PV,CON_UID,REC_UID,CON_NUM,REC_NUM,NETWORK_DEEP,RELATION_DEEP,SYSTEM_ID,REG_TYPE,REG_NAME,
        CREDIT_CODE,PREMISES,LEGAL_PERSON,CLOSE_LOGIN,IS_BIND_MAIN,HIGHEST_EMP_LV,HIGHEST_EMP_LV_PERIOD,
        SHOULD_REG_TYPE,IS_SYSTEM_LEADER,ALLOW_TRANSFER,TRANSFER_PROP,IS_GROUP_LEADER,GROUP_LEADER_AT,SHOW_EMP_LV')
        ->asArray()
        ->one();
        if ($infoData) {
            $data = array_merge($data, $infoData);
        }
        if (!$data['DEC_LV']) $data['DEC_LV'] = DeclarationLevel::getDefaultLevelId();
        if (!$data['LAST_DEC_LV']) $data['LAST_DEC_LV'] = DeclarationLevel::getDefaultLevelId();
        if (!$data['EMP_LV']) $data['EMP_LV'] = EmployLevel::getDefaultLevelId();
        return $data;
    }

    public static function baseInfoZhByUserName($userName) {
        $baseInfo = self::baseInfoByUserName($userName);
        // 状态处理
        $baseInfo['STATUS_NAME'] = Tool::paramConvert(Yii::$app->params['userStatus'])[$baseInfo['STATUS']]['label'];
        //登录状态
        $baseInfo['LOGIN_STATUS_NAME'] = $baseInfo['ALLOW_LOGIN'] == 0 ? '禁止登录' : '允许登录';
        // 子公司
        $baseInfo['SUB_COM_NAME'] = '';
        $baseInfo['PROVINCE_NAME'] = $baseInfo['PROVINCE'] ? Region::getCnName($baseInfo['PROVINCE']) : '';
        $baseInfo['CITY_NAME'] = $baseInfo['CITY'] ? Region::getCnName($baseInfo['CITY']) : '';
        $baseInfo['COUNTY_NAME'] = $baseInfo['COUNTY'] ? Region::getCnName($baseInfo['COUNTY']) : '';
        $baseInfo['BANK_PROVINCE_NAME'] = $baseInfo['BANK_PROVINCE'] ? Region::getCnName($baseInfo['BANK_PROVINCE']) : '';
        $baseInfo['BANK_CITY_NAME'] = $baseInfo['BANK_CITY'] ? Region::getCnName($baseInfo['BANK_CITY']) : '';
        $baseInfo['BANK_COUNTY_NAME'] = $baseInfo['BANK_COUNTY'] ? Region::getCnName($baseInfo['BANK_COUNTY']) : '';
        $baseInfo['OPEN_BANK_NAME'] = $baseInfo['OPEN_BANK'] ? OpenBank::getCnName($baseInfo['OPEN_BANK']) : '';
        // 获取会员体系
        $baseInfo['SYSTEM_NAME'] = '';
        // 获取会员级别名称
        $baseInfo['DEC_LV_NAME'] = Cache::getDecLevelConfig()[$baseInfo['DEC_LV']]['LEVEL_NAME'];
        $baseInfo['LAST_DEC_LV_NAME'] = Cache::getDecLevelConfig()[$baseInfo['LAST_DEC_LV']]['LEVEL_NAME'];
        $baseInfo['EMP_LV_NAME'] = Cache::getEmpLevelConfig()[$baseInfo['EMP_LV']]['LEVEL_NAME'];
        $baseInfo['HIGHEST_EMP_LV_NAME'] = '';
        // 获取会员报单级别
        $baseInfo['DEC_ROLE_NAME'] = '无';
        //民族
        $baseInfo['NATION_NAME'] = \Yii::$app->params['nation'][$baseInfo['NATION']]['name']??'';
        // 国家
        $baseInfo['COUNTRY_NAME'] = Countries::getById($baseInfo['COUNTRY_ID'])['NAME'] ?? '';

        return $baseInfo;
    }

    /**
     * 基本信息
     * @param $userId
     * @param $periodNum
     * @return array|\yii\db\ActiveRecord|null
     * @throws Exception
     */
    public static function baseInfo($userId, $periodNum = null) {
        if($periodNum == null){
            return self::baseInfoNowPeriod($userId);
        } else {
            // 获取当前期数
            $tableName = '{{%USER_ALL_'.$periodNum.'}}';
            if(ActiveRecord::isExistsTable($tableName, 'dbNetPoint')){
                if($data = \Yii::$app->dbNetPoint->createCommand("SELECT * FROM $tableName WHERE ID=:ID")->bindValues([':ID'=>$userId])->queryOne()) {
                    if (!$data['DEC_LV']) $data['DEC_LV'] = DeclarationLevel::getDefaultLevelId();
                    if (!$data['LAST_DEC_LV']) $data['LAST_DEC_LV'] = DeclarationLevel::getDefaultLevelId();
                    if (!$data['EMP_LV']) $data['EMP_LV'] = EmployLevel::getDefaultLevelId();
                    if (!$data['HIGHEST_EMP_LV']) $data['HIGHEST_EMP_LV'] = EmployLevel::getDefaultLevelId();
                    return $data;
                }else{
                    return self::baseInfoNowPeriod($userId);
                }
            } else {
                return self::baseInfoNowPeriod($userId);
            }
        }
    }

    /**
     * 基本信息含中文地区和中文子公司
     * @param $userId
     * @param $periodNum
     * @return array|\yii\db\ActiveRecord|null
     * @throws Exception
     */
    public static function baseInfoZh($userId, $periodNum = null) {
        $baseInfo = self::baseInfo($userId, $periodNum);
        // 状态处理
        $baseInfo['STATUS_NAME'] = Tool::paramConvert(Yii::$app->params['userStatus'])[$baseInfo['STATUS']]['label'];
        //登录状态
        $baseInfo['LOGIN_STATUS_NAME'] = $baseInfo['ALLOW_LOGIN'] == 0 ? '禁止登录' : '允许登录';
        // 子公司
        $baseInfo['SUB_COM_NAME'] = '';
        $baseInfo['PROVINCE_NAME'] = $baseInfo['PROVINCE'] ? Region::getCnName($baseInfo['PROVINCE']) : '';
        $baseInfo['CITY_NAME'] = $baseInfo['CITY'] ? Region::getCnName($baseInfo['CITY']) : '';
        $baseInfo['COUNTY_NAME'] = $baseInfo['COUNTY'] ? Region::getCnName($baseInfo['COUNTY']) : '';
        $baseInfo['BANK_PROVINCE_NAME'] = $baseInfo['BANK_PROVINCE'] ? Region::getCnName($baseInfo['BANK_PROVINCE']) : '';
        $baseInfo['BANK_CITY_NAME'] = $baseInfo['BANK_CITY'] ? Region::getCnName($baseInfo['BANK_CITY']) : '';
        $baseInfo['BANK_COUNTY_NAME'] = $baseInfo['BANK_COUNTY'] ? Region::getCnName($baseInfo['BANK_COUNTY']) : '';
        $baseInfo['OPEN_BANK_NAME'] = $baseInfo['OPEN_BANK'] ? OpenBank::getCnName($baseInfo['OPEN_BANK']) : '';
        // 获取会员体系
        $baseInfo['SYSTEM_NAME'] = '';
        // 获取会员级别名称
        $baseInfo['DEC_LV_NAME'] = Cache::getDecLevelConfig()[$baseInfo['DEC_LV']]['LEVEL_NAME'];
        $baseInfo['LAST_DEC_LV_NAME'] = Cache::getDecLevelConfig()[$baseInfo['LAST_DEC_LV']]['LEVEL_NAME'];
        $baseInfo['EMP_LV_NAME'] = Cache::getEmpLevelConfig()[$baseInfo['EMP_LV']]['LEVEL_NAME'];
        $baseInfo['HIGHEST_EMP_LV_NAME'] = '';
        // 获取会员报单级别
        $baseInfo['DEC_ROLE_NAME'] = '无';
        //民族
        $baseInfo['NATION_NAME'] = \Yii::$app->params['nation'][$baseInfo['NATION']]['name']??'';
        return $baseInfo;
    }

    /**
     * 基本信息及余额
     * @param $userId
     * @param $periodNum
     * @return array
     */
    public static function baseInfoWithBalance($userId, $periodNum = null) {
        $baseInfo = self::baseInfoZh($userId, $periodNum);

        if ($baseInfo) {
            $userBonus = self::BalanceInfo($userId);
        }
        return array_merge($baseInfo, $userBonus);
    }

    /**
     * 获取余额信息
     * @param $userId
     * @return array|int[]|null
     */
    public static function BalanceInfo($userId) {
        $userBonus = [
            'BONUS' => 0,
            'BONUS_FREEZE' => 0,
            'CF' => 0,
            'LX' => 0,
            'QY_TOTAL' => 0,
            'YC_TOTAL' => 0,
            'FX_TOTAL' => 0,
            'LS_TOTAL' => 0,
            'CF_TOTAL' => 0,
            'LX_TOTAL' => 0,
            'FL_TOTAL' => 0,
            'BT_TOTAL' => 0,
            'FW_TOTAL' => 0,
            'CASH' => 0,
        ];

        if ($userBonusResult = UserBonus::findOneAsArray(['USER_ID' => $userId])) {
            $userBonus = $userBonusResult;
        }
        if ($userCashResult = UserWallet::findOneAsArray(['USER_ID' => $userId])) {
            $userBonus['CASH'] = $userCashResult['CASH'];
        }

        return $userBonus;
    }

    /**
     * 基本信息带着网络和节点信息
     * @param $userId
     * @param $periodNum
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function baseInfoWithNet($userId, $periodNum = null) {
        $baseInfo = self::baseInfoZh($userId, $periodNum);
        $baseInfo['CON_USER_NAME'] = '';
        $baseInfo['CON_REAL_NAME'] = '';
        $baseInfo['LOCATION'] = '';
        $baseInfo['REC_USER_NAME'] = '';
        $baseInfo['REC_REAL_NAME'] = '';
        $baseInfo['DEC_USER_NAME'] = '';
        $baseInfo['DEC_REAL_NAME'] = '';
        $baseInfo['DEC_DEC_LV'] = '';
        $baseInfo['DEC_DEC_LV_NAME'] = '';
        if ($baseInfo) {
            if (isset($baseInfo['CON_UID']) && $baseInfo['CON_UID']) {
                // 安置网上级
                //$netParentUserInfo = UserNetwork::getFirstParentUserInfo($userId);
                $netParentBaseInfo = self::baseInfo($baseInfo['CON_UID']);
                $networkParent = UserNetwork::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId]);
                //$baseInfo['CON_UID'] = $baseInfo['CON_UID'];
                $baseInfo['CON_USER_NAME'] = $netParentBaseInfo['USER_NAME'] ?? '';
                $baseInfo['CON_REAL_NAME'] = $netParentBaseInfo['REAL_NAME'] ?? '';
                $baseInfo['LOCATION'] = $networkParent['RELATIVE_LOCATION'] ?? 1;
            }

            if (isset($baseInfo['REC_UID']) && $baseInfo['REC_UID']) {
                // 推荐网上级
                //$relationParentUserInfo = UserRelation::getFirstParentUserInfo($userId);
                $relationParentBaseInfo = self::baseInfo($baseInfo['REC_UID']);
                //$baseInfo['REC_UID'] = $relationParentUserInfo['USER_ID'];
                $baseInfo['REC_USER_NAME'] = $relationParentBaseInfo['USER_NAME'];
                $baseInfo['REC_REAL_NAME'] = $relationParentBaseInfo['REAL_NAME'];
            }
            if (isset($baseInfo['DEC_ID']) && $baseInfo['DEC_ID']) {
                $decBaseInfo = self::baseInfoZh($baseInfo['DEC_ID']);
                $baseInfo['DEC_USER_NAME'] = $decBaseInfo['USER_NAME'];
                $baseInfo['DEC_REAL_NAME'] = $decBaseInfo['REAL_NAME'];
                $baseInfo['DEC_DEC_LV'] = $decBaseInfo['DEC_LV'];
                $baseInfo['DEC_DEC_LV_NAME'] = $decBaseInfo['DEC_LV_NAME'];
                $baseInfo['DEC_DEC_ROLE_NAME'] = $decBaseInfo['DEC_ROLE_NAME'];
                $baseInfo['DEC_DEC_ROLE_ID'] = $decBaseInfo['DEC_ROLE_ID'];
            }
        }

        return $baseInfo;
    }

    /**
     * 基本信息含网络和余额
     * @param $userId
     * @param $periodNum
     * @return array
     */
    public static function baseInfoWithNetAndBalance($userId, $periodNum = null) {
        return array_merge(self::baseInfoWithNet($userId), self::BalanceInfo($userId));
    }

    /**
     * 通过用户名获取用户信息从INFO表
     * @param $userName
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getUserByUserNameFromUserInfoTable($userName) {
        return UserInfo::findOneAsArray(['USER_NAME' => $userName]);
    }

    /**
     * 获取报单级别
     * @param $userId
     * @param null $periodNum
     * @return mixed
     * @throws \yii\db\Exception
     */
    public static function getDecLv($userId, $periodNum = null) {
        if ($periodNum === null) {
            $data = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'DEC_LV');
            $decLv = $data['DEC_LV'];
        } else {
            $period = Period::instance();
            $yearMonth = $period->getYearMonth($periodNum);
            $data = PerfPeriod::find()->yearMonth($yearMonth)->select('LAST_DEC_LV')->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID' => $userId, ':PERIOD_NUM' => $periodNum])->asArray()->one();
            $decLv = $data ? $data['LAST_DEC_LV'] : DeclarationLevel::getDefaultLevelId();
        }
        return $decLv;
    }

    /**
     * 获取聘级
     * @param $userId
     * @param null $periodNum
     * @return mixed
     * @throws \yii\db\Exception
     */
    public static function getEmpLv($userId, $periodNum = null) {
        if ($periodNum === null) {
            $data = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'EMP_LV');
            $empLv = $data['EMP_LV'];
        } else {
            $period = Period::instance();
            $yearMonth = $period->getYearMonth($periodNum);
            $data = PerfMonth::find()->yearMonth($yearMonth)->select('LAST_EMP_LV')->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $userId, ':CALC_MONTH' => $yearMonth])->asArray()->one();
            $empLv = $data ? $data['LAST_EMP_LV'] : EmployLevel::getDefaultLevelId();
        }
        return $empLv;
    }

    /**
     * 获取最高聘级
     * @param $userId
     * @return mixed
     */
    public static function getHighEmpLv($userId){
        $data = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'HIGHEST_EMP_LV');
        $empLv = $data ? $data['HIGHEST_EMP_LV'] : EmployLevel::getDefaultLevelId();
        return $empLv;
    }

    /**
     * 获取报单级别名称
     * @param $userId
     * @param null $periodNum
     * @return mixed
     * @throws \yii\db\Exception
     */
    public static function getDecLvName($userId, $periodNum = null) {
        if (!$decLv = self::getDecLv($userId, $periodNum)) {
            $decLv = DeclarationLevel::getDefaultLevelId();
        }
        return Cache::getDecLevelConfig()[$decLv]['LEVEL_NAME'];
    }

    /**
     * 获取聘级名称
     * @param $userId
     * @param null $periodNum
     * @return mixed
     * @throws \yii\db\Exception
     */
    public static function getEmpLvName($userId, $periodNum = null) {
        if (!$empLv = self::getEmpLv($userId, $periodNum)) {
            $empLv = EmployLevel::getDefaultLevelId();
        }
        return Cache::getEmpLevelConfig()[$empLv]['LEVEL_NAME'];
    }

    /**
     * 获取民族对应的代码
     * @param $str
     * @return int|string
     */
    public static function getNationCode($str) {
        $str = preg_replace('/族$/', '', $str);
        $allNation = \Yii::$app->params['nation'];
        foreach ($allNation as $key => $nation) {
            if ($str . '族' == $nation['name']) {
                return $key;
            }
        }
        return 0;
    }

    /**
     * 生成用户名
     * @param string $prefix
     * @param int $length
     * @return string
     */
    public static function generateUserName(string $prefix = 'HZ', int $length = 10) {
        $result = Tool::randomString($length, $prefix).array_rand([0,1,2,3,5,6,7,8,9],1);
        if (User::find()->where('USER_NAME=:USER_NAME', [':USER_NAME' => $result])->exists()) {
            return self::generateUserName($prefix, $length);
        }
        return $result;
    }

    /**
     * 新增加的 生成前端姓名里用户名
     * @param string $prefix
     * @param int $length
     * @return string
     */
    public static function generateWebUserName(string $prefix = 'HZ', int $length = 10) {
        $result = Tool::randomString($length, $prefix).array_rand([0,1,2,3,5,6,7,8,9],1);
        if (substr($result ,-1) == '4'){
            return self::generateWebUserName($prefix, $length);
        }
        if (User::find()->where('USER_NAME=:USER_NAME', [':USER_NAME' => $result])->exists()) {
            return self::generateWebUserName($prefix, $length);
        }
        if (BaUser::find()->where('USER_NAME=:USER_NAME', [':USER_NAME' => $result])->exists()) {
            return self::generateWebUserName($prefix, $length);
        }
        return $result;
    }

    public static function generateWebName(string $countryId, int $length = 9) {
        // 名字前缀取国家简码
        $country = Countries::getById($countryId);
        $prefix = $country['CODE'] ?: 'NG';

        $result = Tool::randomString($length, $prefix).array_rand([0,1,2,3,5,6,7,8,9],1);
        if (substr($result ,-1) == '4'){
            return self::generateWebUserName($prefix, $length);
        }
        if (User::find()->where('USER_NAME=:USER_NAME', [':USER_NAME' => $result])->exists()) {
            return self::generateWebUserName($prefix, $length);
        }
        if (BaUser::find()->where('USER_NAME=:USER_NAME', [':USER_NAME' => $result])->exists()) {
            return self::generateWebUserName($prefix, $length);
        }
        return $result;
    }

    /**
     * 定位会员的子公司
     * @param $userArea
     * @return array|bool
     */
    public static function location($userArea){
        if(!is_array($userArea)){
            $userArea = json_decode($userArea, true);
        }
        if(!$userArea || !isset($userArea[0])){
            return false;
        }
        //获取会员的所在省份
        $userProvince = $userArea[0];
        $list = [];
        if(!$list){
            return false;
        }
        $matched = [];
        $userCity = isset($userArea[1]) ? intval($userArea[1]) : 0;
        $userCounty = isset($userArea[2]) ? intval($userArea[2]) : 0;
        foreach($list as $row){
            $manageRange = json_decode($row['MANAGE_RANGE'], true);
            foreach($manageRange as $manage){
                // $manage = ["370000","371000","371082"] or ["210000",""];
                $pro = isset($manage[0]) ? intval($manage[0]) : 0;
                $city = isset($manage[1]) ? intval($manage[1]) : 0;
                $county = isset($manage[2]) ? intval($manage[2]) : 0;
                if($userProvince == $pro && $userCity == $city && $userCounty == $county){
                    $matched = $row;
                    break;
                }
                if($userProvince == $pro && $userCity == $city && $county == 0){
                    $matched = $row;
                    break;
                }
                if($userProvince == $pro && $city == 0 && $county == 0){
                    $matched = $row;
                    break;
                }
            }
        }
        unset($userCounty, $userCity, $userArea, $userProvince, $list);
        return $matched;
    }

    /**
     * 通过id获取身份证号
     * @param $userId
     * @return null
     */
    public static function getIdCardByUserId($userId) {
        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'ID_CARD');
        return $user ? $user['ID_CARD'] : null;
    }

    /**
     * 通过id获取状态
     * @param $userId
     * @return null
     */
    public static function getStatusByUserId($userId){
        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'STATUS');
        return $user ? $user['STATUS'] : null;
    }

    /**
     * 通过id获取期数
     * @param $userId
     * @return null
     */
    public static function getPeriodNumByUserId($userId) {
        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'PERIOD_AT');
        return $user ? $user['PERIOD_AT'] : null;
    }

    /**
     * 是否实名认证
     * @param $userId
     * @return bool
     */
    public static function isVerified($userId) {
        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'VERIFIED');
        if ($user && $user['VERIFIED'] == 1) return true;
        return false;
    }

    /**
     * 根据商城设置获取密码
     * @param $idCard
     * @param $userName
     * @param bool $payPwd
     * @return bool|string
     */
    public static function passwordGenerator($idCard,$userName,$payPwd=false) {
        $systemConfig = Cache::getSystemConfig();
        if($payPwd){
            $config = $systemConfig['payPasswordRule'];
        }else{
            $config = $systemConfig['passwordRule'];
        }
        $rule = $config['VALUE'];  //id_s_6 , id_p_8, user_name 后台设置，分别为身份证的后6位，前8位或者用户名
        switch ($rule) {
            case 'id_s_6':
                $password = substr($idCard, -6);
                break;
            case 'id_p_8':
                $password = substr($idCard, 0, 8);
                break;
            case 'user_name':
                $password = $userName;
                break;
            default:
                $password = '111111';
        }
        return $password;
    }

    /**
     * 当时会员级别状态等
     * @param $userId
     * @return array|null
     */
    public static function getLastInfo($userId){
        $data = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'LAST_DEC_LV AS DEC_LV,EMP_LV,LAST_EMP_LV,STATUS');
        return $data;
    }

    /**
     * 是否合作会员
     * @param $userId
     * @return bool
     */
    public static function isUnion($userId){
        $data = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'IS_UNION');
        if ($data && $data['IS_UNION'] == 1) return true;
        return false;
    }

    /**
     * 获取Ba用户ID

     * @param $userName
     * @return mixed
     */
    public static function getBaUserIdByUserName($userName) {
        $user = BaUserInfo::findOneAsArray('USER_NAME=:USER_NAME AND DELETED=0', [':USER_NAME' => $userName], 'USER_ID');
        return $user ? $user['USER_ID'] : null;
    }

    /**
     * 获取会员名通过ID
     * @param $userId
     * @return mixed|null
     */
    public static function getBaUserNameByUserId($userId) {
        $user = BaUserInfo::findOneAsArray('USER_ID=:USER_ID AND DELETED=0', [':USER_ID' => $userId], 'USER_NAME');
        return $user ? $user['USER_NAME'] : null;
    }

    /**
     * 获取用户EMAIL
     * @param $userName
     * @return mixed
     */
    public static function getBaEmailByUserId($userId) {
        $user = BaUserInfo::findOneAsArray('USER_ID=:USER_ID AND DELETED=0', [':USER_ID' => $userId], 'USER_NAME');
        return $user ? $user['EMAIL'] : null;
    }

    /**
     * 获取会员姓名通过ID
     * @param $userId
     * @return null
     */
    public static function getBaUserRealNameByUserId($userId) {
        $user = BaUser::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'REAL_NAME');
        return $user ? $user['REAL_NAME'] : null;
    }

    /**
     * 获取会员邮箱通过ID
     * @param $userId
     * @return null
     */
    public static function getBaUserEmailByUserId($userId) {
        $user = BaUser::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'EMAIL');
        return $user ? $user['EMAIL'] : null;
    }

    /**
     * 获取手机号通过ID
     * @param $userId
     * @return null
     */
    public static function getBaUserMobileByUserId($userId) {
        $user = BaUser::findOneAsArray('ID=:ID AND DELETED=0', [':ID' => $userId], 'MOBILE');
        return $user ? $user['MOBILE'] : null;
    }

    /**
     * 通过用户ID获取用户的编号和名称
     * @param $userId
     * @return array|null
     */
    public static function getBaBaseUserById($userId) {
        return BaUser::findOneAsArray('ID=:ID', [':ID' => $userId], 'ID,USER_NAME,REAL_NAME');
    }

    /**
     * 通过用户ID获取用户的编号和名称
     * @param $username
     * @return array|null
     */
    public static function getBaBaseUserByUserName($username) {
        return BaUser::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $username]);
    }
}
