<?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\DeclarationLevel;
use common\models\EmployLevel;
use common\models\Region;
use common\models\User;
use common\models\UserInfo;
use yii\base\Exception;

class Info {

    /**
     * @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;
    }

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

    /**
     * @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;
    }

    /**
     * @param $userId
     * @return array|null
     */
    public static function getBaseUserById($userId) {
        return User::findOneAsArray('ID=:ID', [':ID' => $userId], 'ID,USER_NAME,REAL_NAME');
    }

    /**
     * @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('会员不存在'.$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
     * @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'] = \Yii::$app->params['userStatus'][$baseInfo['STATUS']]['label'];
        $baseInfo['LOGIN_STATUS_NAME'] = $baseInfo['ALLOW_LOGIN'] == 0 ? '禁止登录' : '允许登录';
        $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['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 $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 $userId
     * @return null
     */
    public static function getIdCardByUserId($userId) {
        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'ID_CARD');
        return $user ? $user['ID_CARD'] : null;
    }

    /**
     * @param $userId
     * @return null
     */
    public static function getStatusByUserId($userId){
        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'STATUS');
        return $user ? $user['STATUS'] : 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'];
        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 = '123456';
        }
        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,STATUS');
        return $data;
    }
}