<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/8/2
 * Time: 上午10:38
 */
namespace common\helpers\bonus;

use common\helpers\Cache;
use common\models\Config;
use common\models\PerfMonth;
use common\models\Period;
use common\models\DeclarationLevel;
use common\models\DecRole;
use common\models\DeductReconsume;
use common\models\EmployLevel;
use common\models\StarCrownLevel;
use common\models\User;
use common\models\UserPerf;
use Yii;
use common\models\UserInfo;
use yii\helpers\Json;

class CalcCache {
    const LIMIT = 10000;

    const REDIS_KEY_PREFIX_USER = 'calc:user_';
    const REDIS_KEY_PREFIX_USER_ACTIVE = 'calc:userActive_';
    const REDIS_KEY_PREFIX_USER_INFO = 'calc:userInfo_';
    const REDIS_KEY_PREFIX_USER_BONUS = 'calc:userBonus_';
    const REDIS_KEY_PREFIX_PERIOD_MONTH_CALC_BONUS = 'calc:periodMonthCalcBonus_';
    const REDIS_KEY_PREFIX_USER_PERF = 'calc:userPerf_';
    const REDIS_KEY_PREFIX_SURPLUS_PERF = 'calc:spPerf_';
    const REDIS_KEY_PREFIX_NOW_PERIOD_PERF = 'calc:nowPeriodPerf_';
    const REDIS_KEY_PREFIX_LAST_MONTH_PERF = 'calc:lastMonthPerf_';
    const REDIS_KEY_PREFIX_NOW_MONTH_PERF = 'calc:nowMonthPerf_';
    const REDIS_KEY_PREFIX_NOW_MONTH_LAST_PERIOD_RECONSUME_POINTS = 'calc:nowMonthLastPeriodReconsumePoints_';
    const REDIS_KEY_PREFIX_EMP_NUM_PERF = 'calc:empLevelNum_';
    const REDIS_KEY_PREFIX_BONUS = 'calc:bonus_';
    const REDIS_KEY_PREFIX_FW_BONUS = 'calc:fw:bonus_';
    const REDIS_KEY_PREFIX_TOURISM_BONUS = 'calc:tourism:bonus_';
    const REDIS_KEY_PREFIX_VILLA_BONUS = 'calc:villa:bonus_';
    const REDIS_KEY_PREFIX_GARAGE_BONUS = 'calc:garage:bonus_';
    const REDIS_KEY_PREFIX_HAS_PERF_USER = 'calc:hasPerfUser_';
    const REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER = 'calc:hasMonthPerfUser_';
    const REDIS_KEY_PREFIX_HAS_STANDARD_MONTH_PERF_USER = 'calc:hasStandardMonthPerfUser_';
    const REDIS_KEY_PREFIX_HAS_BD_USER = 'calc:hasBDUser_';
    const REDIS_KEY_PREFIX_HAS_INCOME_USER = 'calc:hasIncomeUser_';
    const REDIS_KEY_PREFIX_HAS_BONUS_USER = 'calc:hasBonusUser_';
    const REDIS_KEY_PREFIX_HAS_FW_BONUS_USER = 'calc:hasFwBonusUser_';
    const REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER = 'calc:hasMonthBonusUser_';
    const REDIS_KEY_PREFIX_HAS_PERF_USER_POOL = 'calc:hasPerfUserPool_';
    const REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER_POOL = 'calc:hasMonthPerfUserPool_';
    const REDIS_KEY_PREFIX_HAS_STANDARD_MONTH_PERF_USER_POOL = 'calc:hasStandardMonthPerfUserPool_';
    const REDIS_KEY_PREFIX_HAS_BD_USER_POOL = 'calc:hasBDUserPool_';
    const REDIS_KEY_PREFIX_HAS_INCOME_USER_POOL = 'calc:hasIncomeUserPool_';
    const REDIS_KEY_PREFIX_HAS_BONUS_USER_POOL = 'calc:hasBonusUserPool_';
    const REDIS_KEY_PREFIX_HAS_FW_BONUS_USER_POOL = 'calc:hasFwBonusUserPool_';
    const REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER_POOL = 'calc:hasMonthBonusUserPool_';
    const REDIS_KEY_PREFIX_HAS_LS_PCS_USER = 'calc:hasLSPCSUser_';
    const REDIS_KEY_PREFIX_HAS_LS_PCS_USER_POOL = 'calc:hasLSPCSUserPool_';
    const REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER = 'calc:hasCFPercentPCSUser_';
    const REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER_POOL = 'calc:hasCFPercentPCSUserPool_';
    const REDIS_KEY_PREFIX_HAS_LX_PERCENT_USER = 'calc:hasLXPercentPCSUser_';
    const REDIS_KEY_PREFIX_HAS_LX_PERCENT_USER_POOL = 'calc:hasLXPercentPCSUserPool_';
    const REDIS_KEY_PREFIX_DEC_ROLE_CONFIG = 'calc:decRoleConfig_';
    const REDIS_KEY_PREFIX_USER_INFO_CHILD_ONE_DEEP = 'calc:userInfo:ChildOneDeep_';
    const REDIS_KEY_PREFIX_FW_BONUS_LIST_DATA = 'calc:fwBonusListData_';
    const REDIS_KEY_PREFIX_BONUS_CROWN_CROWN_LIST_DATA = 'calc:bonusStarCrownListData_';

    //@todo
    const REDIS_KEY_PREFIX_REPAIR_SURPLUS_PERF = 'calc:repairSurplusPerf_';
    const REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER = 'calc:hasRepairPerfUser_';
    const REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER_POOL = 'calc:hasRepairPerfPool_';

    const INCOME_QY_BONUS_BD = 'BONUS_QY_BD';
    const INCOME_BONUS_TRAVEL = 'BONUS_TRAVEL';
    const INCOME_BONUS_CAR = 'BONUS_CAR';
    const INCOME_BONUS_HOUSE = 'BONUS_HOUSE';
    const CAPPED_BONUS_QY = 'CAPPED_BONUS_QY'; // 团队奖封顶前的金额
    const INCOME_BONUS_LIST = [
        self::INCOME_QY_BONUS_BD,
    ];
    const NOT_SEND_BONUS_LIST = [
        self::INCOME_QY_BONUS_BD,
        self::INCOME_BONUS_TRAVEL,
        self::INCOME_BONUS_CAR,
        self::INCOME_BONUS_HOUSE,
        self::CAPPED_BONUS_QY,
    ];

    const FROM_MEANS_BD = 'BD';

    /**
     * 结算奖金时要清空的缓存
     * @param $periodNum
     */
    public static function clearCalcBonusCache($periodNum) {
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_BONUS . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_BONUS_USER . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_BONUS_USER_POOL . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_FW_BONUS . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER_POOL . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER_POOL . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_FW_BONUS_LIST_DATA . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_BONUS_CROWN_CROWN_LIST_DATA . $periodNum);
        DeclarationLevel::updateToCache();
        Config::updateToCache();
        DecRole::updateToCache();
        EmployLevel::updateToCache();
        StarCrownLevel::updateToCache();
    }

    /**
     * 清网络缓存
     */
    public static function clearNetCache(){
        \Yii::$app->redis->del(Cache::USER_NETWORK_PARENTS);
        \Yii::$app->redis->del(Cache::USER_RELATION_PARENTS);
    }

    /**
     * 清空所有临时计算用到的缓存
     * @param $periodNum
     */
    public static function clearAll($periodNum) {
        //Yii::$app->redis->del(Yii::$app->redis->keys('calc*'));
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_USER . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_USER_ACTIVE . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_USER_INFO . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_USER_BONUS . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_PERIOD_MONTH_CALC_BONUS . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_SURPLUS_PERF . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_USER_PERF . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_NOW_PERIOD_PERF . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_LAST_MONTH_PERF . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_NOW_MONTH_PERF . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_NOW_MONTH_LAST_PERIOD_RECONSUME_POINTS . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_EMP_NUM_PERF . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_BONUS . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_FW_BONUS . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_PERF_USER . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_PERF_USER_POOL . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER_POOL . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_BD_USER . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_BD_USER_POOL . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_INCOME_USER . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_INCOME_USER_POOL . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_BONUS_USER . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_BONUS_USER_POOL . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER_POOL . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER_POOL . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_DEC_ROLE_CONFIG . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_USER_INFO_CHILD_ONE_DEEP . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_FW_BONUS_LIST_DATA . $periodNum);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_BONUS_CROWN_CROWN_LIST_DATA . $periodNum);
        DeclarationLevel::updateToCache();
        Config::updateToCache();
        DecRole::updateToCache();
        EmployLevel::updateToCache();
        StarCrownLevel::updateToCache();
    }

    /**
     * 会员信息加入缓存
     * @param $periodNum
     * @param int $offset
     * @param int $limit
     * @return bool
     */
    public static function addUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
        $allData = UserInfo::findUseDbCalc()
            ->from(UserInfo::tableName(). 'AS UI')
            ->select('UI.USER_ID,U.STATUS')
            ->leftJoin(User::tableName() . 'AS U', 'U.ID=UI.USER_ID')
            ->where('1=1')
            ->orderBy('UI.ID DESC')
            ->offset($offset)
            ->limit($limit)
            ->asArray()
            ->all();
        if ($allData) {
            foreach ($allData as $data) {
                $cacheKey = self::REDIS_KEY_PREFIX_USER . $periodNum;
                $value = $data['USER_ID'];
                Yii::$app->redis->rpush($cacheKey, $value);
                if( $data['STATUS'] == 1 ) {
                    $activeCacheKey = self::REDIS_KEY_PREFIX_USER_ACTIVE . $periodNum;
                    Yii::$app->redis->rpush($activeCacheKey, $value);
                    unset($activeCacheKey);
                }
                unset($data, $cacheKey, $value);
            }
            unset($allData);
            return self::addUsers($periodNum, $offset + $limit, $limit);
        }
        unset($allData);
        return true;
    }

    /**
     * 获取会员从缓存中
     * @param $periodNum
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public static function getUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_USER . $periodNum, $offset, ($offset + $limit - 1));
    }

    /**
     * 获取激活会员从缓存中
     * @param $periodNum
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public static function getActiveUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_USER_ACTIVE . $periodNum, $offset, ($offset + $limit - 1));
    }

    /**
     * 加入有业绩的会员
     * @param $userId
     * @param $periodNum
     */
    public static function addHasPerfUsers($userId, $periodNum) {
        // 先从已存在的会员池里面获取
        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_PERF_USER_POOL . $periodNum, $userId);
        if (!$isset) {
            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_PERF_USER_POOL . $periodNum, $userId, 1);
            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_PERF_USER . $periodNum, $userId);
        }
        unset($userId, $periodNum, $isset);
    }

    /**
     * 获取有业绩的会员
     * @param $periodNum
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public static function getHasPerfUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_PERF_USER . $periodNum, $offset, ($offset + $limit - 1));
    }

    /**
     * 加入有月业绩的会员
     * @param $userId
     * @param $periodNum
     */
    public static function addHasMonthPerfUsers($userId, $periodNum) {
        // 先从已存在的会员池里面获取
        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER_POOL . $periodNum, $userId);
        if (!$isset) {
            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER_POOL . $periodNum, $userId, 1);
            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER . $periodNum, $userId);
        }
        unset($userId, $periodNum, $isset);
    }

    /**
     * 获取有业绩的会员
     * @param $periodNum
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public static function getHasMonthPerfUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_MONTH_PERF_USER . $periodNum, $offset, ($offset + $limit - 1));
    }

    /**
     * 加入被报单的会员
     * @param $userId
     * @param $periodNum
     * @param $saveData
     */
    public static function addHasBDUsers($userId, $periodNum, $saveData) {
        // 先从已存在的会员池里面获取
        $data = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_BD_USER_POOL . $periodNum, $userId);
        if (!$data) {
            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_BD_USER_POOL . $periodNum, $userId, Json::encode($saveData));
            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_BD_USER . $periodNum, $userId);
        }
        unset($userId, $periodNum, $saveData, $isset);
    }

    /**
     * 获取被报单的会员信息
     * @param $userId
     * @param $periodNum
     * @return array
     */
    public static function getBDUsersInfo($userId, $periodNum) {
        $data = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_BD_USER_POOL . $periodNum, $userId);
        if( !$data ) return [];

        return Json::decode($data, true);
    }

    /**
     * 获取被报单的会员
     * @param $periodNum
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public static function getHasBDUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_BD_USER . $periodNum, $offset, ($offset + $limit - 1));
    }

    /**
     * 加入有收入的会员
     * @param $userId
     * @param $periodNum
     */
    public static function addHasIncomeUsers($userId, $periodNum) {
        // 先从已存在的会员池里面获取
        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_INCOME_USER_POOL . $periodNum, $userId);
        if (!$isset) {
            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_INCOME_USER_POOL . $periodNum, $userId, 1);
            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_INCOME_USER . $periodNum, $userId);
        }

        unset($userId, $periodNum, $isset);
    }

    /**
     * 获取有收入的会员
     * @param $periodNum
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public static function getHasIncomeUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_INCOME_USER . $periodNum, $offset, ($offset + $limit - 1));
    }

    /**
     * 加入有奖金的会员
     * @param $userId
     * @param $periodNum
     */
    public static function addHasBonusUsers($userId, $periodNum) {
        // 先从已存在的会员池里面获取
        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_BONUS_USER_POOL . $periodNum, $userId);
        if (!$isset) {
            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_BONUS_USER_POOL . $periodNum, $userId, 1);
            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_BONUS_USER . $periodNum, $userId);
        }

        unset($userId, $periodNum, $isset);
    }

    /**
     * 获取有奖金的会员
     * @param $periodNum
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public static function getHasBonusUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_BONUS_USER . $periodNum, $offset, ($offset + $limit - 1));
    }

    /**
     * 获取有服务奖的会员
     * @param $periodNum
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public static function getHasFwBonusUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER . $periodNum, $offset, ($offset + $limit - 1));
    }

    /**
     * 加入服务奖的会员
     * @param $userId
     * @param $periodNum
     */
    public static function addHasFwBonusUsers($userId, $periodNum) {
        // 先从已存在的会员池里面获取
        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER_POOL . $periodNum, $userId);
        if (!$isset) {
            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER_POOL . $periodNum, $userId, 1);
            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_FW_BONUS_USER . $periodNum, $userId);
        }

        unset($userId, $periodNum, $isset);
    }

    /**
     * 获取有月奖的会员
     * @param $periodNum
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public static function getHasMonthBonusUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_MONTH_BONUS_USER . $periodNum, $offset, ($offset + $limit - 1));
    }

    /**
     * 保存服务奖奖金
     * @param $userId
     * @param $periodNum
     * @param $fwBonus
     * @param array $fromData
     */
    public static function saveFwBonusList($userId, $periodNum, $fwBonus, $fromData=[]) {
        $userFwBonusData = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_FW_BONUS_LIST_DATA . $periodNum, $userId);
        if( $userFwBonusData ) {
            $fwBonusData = Json::decode($userFwBonusData, true);
            $fwBonusData['fwBonus'] += $fwBonus;
        }else {
            $fwBonusData = [
                'fwBonus' => $fwBonus,
            ];
        }
        unset($userFwBonusData);

        Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_FW_BONUS_LIST_DATA . $periodNum, $userId, Json::encode($fwBonusData));
        unset($fwBonusData, $userId, $periodNum, $empBonus, $fromData);
    }

    /**
     * 返回服务奖信息
     * @param $userId
     * @param $periodNum
     * @return array
     */
    public static function getFwBonusList($userId, $periodNum) {
        $userYcBonusData = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_FW_BONUS_LIST_DATA . $periodNum, $userId);

        return $userYcBonusData ? Json::decode($userYcBonusData, true) : [];
    }

    /**
     * 会员星级加入缓存
     * @param $userId
     * @param $periodNum
     * @param $crownCrown
     */
    public static function addUserStarCrown($userId, $periodNum, $starCrown) {
        // 先从已存在的会员池里面获取
        $data = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_BONUS_CROWN_CROWN_LIST_DATA . $periodNum, $userId);
        if (!$data) {
            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_BONUS_CROWN_CROWN_LIST_DATA . $periodNum, $userId, $starCrown);
        }

        unset($userId, $periodNum, $saveData, $isset);
    }

    /**
     * 获取会员星级信息
     * @param $userId
     * @param $periodNum
     * @return array
     */
    public static function getUserStarCrown($userId, $periodNum) {
        return Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_BONUS_CROWN_CROWN_LIST_DATA . $periodNum, $userId);
    }

    /**
     * 有车房补贴比例的人
     * @param $userId
     * @param $periodNum
     */
    public static function addHasCFPercentUsers($userId, $periodNum) {
        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER_POOL . $periodNum, $userId);
        if (!$isset) {
            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER_POOL . $periodNum, $userId, 1);
            $key = self::REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER . $periodNum;
            $value = $userId;
            Yii::$app->redis->rpush($key, $value);
        }
    }

    /**
     * 获取有车房补贴的人
     * @param $periodNum
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public static function getHasCFPercentUsers($periodNum, $offset = 0, $limit = self::LIMIT) {
        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_CF_PERCENT_USER . $periodNum, $offset, ($offset + $limit - 1));
    }

    /**
     * 通过创建时间获取指定长度的用户列表
     * @param $userId
     * @param $limit
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getUserListByCreatedAtFromDb($userId, $limit)
    {
        //查找这个人的CREATED_AT
        $user = User::findUseDbCalc()->select('ID,CREATED_AT')->where('ID=:ID', ['ID'=>$userId])->asArray()->one();
        if( !$user ) return [];

        return User::findUseDbCalc()->select('ID,CREATED_AT')->where('ID<:ID AND CREATED_AT<=:CREATED_AT', [
            'ID'=>$userId,
            'CREATED_AT' => $user['CREATED_AT']
        ])->orderBy('CREATED_AT DESC,ID DESC')->limit($limit)->asArray()->all();
    }

    /**
     * 通过创建时间获取指定长度的用户列表
     * @param $userId
     * @param $limit
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getAfterUserListByCreatedAtFromDb($userId, $limit)
    {
        $cacheKey = Cache::USER_CREATED_AT_LIST . $limit;
        $value = Yii::$app->redis->hGet($cacheKey, $userId);
        if( $value ) {
            unset($cacheKey);
            return json_decode($value, true);
        }
        unset($value);

        $list = UserInfo::findUseDbCalc()->select('USER_ID')->where('USER_ID>:USER_ID', [
            'USER_ID'=>$userId,
        ])->orderBy('USER_ID ASC')->limit($limit)->asArray()->all();
        if ( $limit == count($list) ) {
            Yii::$app->redis->hSet($cacheKey, $userId, json_encode($list));
        }

        unset($cacheKey);
        return $list;
    }

    // 从缓存获取哪些奖金需要扣除管理费和复消积分
    public static function deductBonus($periodNum) {

    }

    /**
     * 获取会员信息从缓存
     * @param $userId
     * @param $periodNum
     * @return array
     * @throws \Exception
     */
    public static function getUserInfo($userId, $periodNum) {
        $key = self::REDIS_KEY_PREFIX_USER_INFO . $periodNum;
        $data = Yii::$app->redis->hget($key, $userId);
        if (empty($data)) {
            $userInfo = UserInfo::findUseDbCalc()
            ->select('USER_ID,USER_NAME,CON_UID,REC_UID')
            ->where('USER_ID=:USER_ID', [':USER_ID' => $userId])
            ->asArray()
            ->one();
            if( !$userInfo ) {
                throw new \Exception('用户信息表数据不存在,userId:'.$userId);
            }

            $userShopInfo = User::findUseDbCalc()
            ->select('LAST_DEC_LV,REAL_NAME,DEC_LV,EMP_LV,CROWN_LV,IS_DEC,STATUS,IS_STUDIO,DEC_ID,DEC_ROLE_ID,LAST_EMP_LV')
            ->where('ID=:ID', [':ID' => $userId])
            ->asArray()
            ->one();
            if ( !$userShopInfo ) {
                throw new \Exception('用户表数据不存在,userId:'.$userId);
            }

            // 用户的最新蓝星级别,需要修改调整因为计算服务这里并没有以前的级别数据表数据,所以无法查询出以前的最近月节点数据
            // 获取用户的最新级别数据,根据蓝星最近一期月结数据进行查询
            $userInfo['REAL_NAME'] = $userShopInfo['REAL_NAME'];
            $userInfo['DEC_LV'] = $userShopInfo['LAST_DEC_LV'];
            $userInfo['EMP_LV'] = $userShopInfo['EMP_LV'];
            $userInfo['LAST_EMP_LV'] = empty($userShopInfo['LAST_EMP_LV']) ? EmployLevel::NO_LEVEL_ID : $userShopInfo['LAST_EMP_LV'];// 最新的聘级
            $userInfo['CROWN_LV'] = $userShopInfo['CROWN_LV'];
            $userInfo['IS_DEC'] = $userShopInfo['IS_DEC'];
            $userInfo['STATUS'] = $userShopInfo['STATUS'];
            $userInfo['DEC_ID'] = $userShopInfo['DEC_ID'];
            $userInfo['DEC_ROLE_ID'] = $userShopInfo['DEC_ROLE_ID'];

            unset($userShopInfo);

            if (!$userInfo['DEC_LV']) {
                $userInfo['DEC_LV'] = DeclarationLevel::getDefaultLevelId();
            }
            if (!$userInfo['EMP_LV']) {
                $userInfo['EMP_LV'] = EmployLevel::getDefaultLevelId();
            }
            if (!$userInfo['CROWN_LV']) {
                $userInfo['CROWN_LV'] = StarCrownLevel::getDefaultLevelId();
            }

            $data = Json::encode($userInfo);
            Yii::$app->redis->hset($key, $userId, $data);

            unset($key, $userId, $periodNum);

            return $userInfo;
        } else {
            return Json::decode($data);
        }
    }

    public static function setUserInfo($userId, $periodNum, $userInfo) {
        $key = self::REDIS_KEY_PREFIX_USER_INFO . $periodNum;
        $data = Json::encode($userInfo);
        Yii::$app->redis->hset($key, $userId, $data);
        unset($userId, $key, $data, $userInfo, $periodNum);
        return true;
    }

    /**
     * 本月往期的复消积分的数据
     * @param $userId
     * @param $periodNum
     * @param $calcYearMonth
     * @return array|mixed|null|\yii\db\ActiveRecord
     * @throws \yii\db\Exception
     */
    public static function monthLastPeriodReconsumePoints($userId, $periodNum, $calcYearMonth) {
        $cacheKey = self::REDIS_KEY_PREFIX_NOW_MONTH_LAST_PERIOD_RECONSUME_POINTS . $periodNum;
        $cacheValue = \Yii::$app->redis->hget($cacheKey, $userId);
        if ($cacheValue) {
            $value = Json::decode($cacheValue, true);
        } else {
            $value = DeductReconsume::findUseDbCalc()
            ->select(["RECONSUME_POINTS_SUM"])
            ->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $userId, ':CALC_MONTH'=>$calcYearMonth])
            ->asArray()
            ->one();
            //$value = CalcBonus::findUseDbCalc()->select(["SUM(RECONSUME_POINTS) as RECONSUME_POINTS_SUM"])->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $userId, ':CALC_MONTH'=>$calcYearMonth])->asArray()->one();
            \Yii::$app->redis->hset($cacheKey, $userId, Json::encode($value));
        }
        return $value;
    }

    /**
     * 获取结算时这一期的报单中心级别的配置
     * @param $periodNum
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getDecRoleConfig($periodNum) {
        $key = self::REDIS_KEY_PREFIX_DEC_ROLE_CONFIG . $periodNum;
        Yii::$app->redis->del($key);
        $data = Yii::$app->redis->get($key);
        if (!$data) {
            $data = DecRole::find()->where('1=1')->indexBy('ID')->asArray()->all();
            $data = Json::encode($data);
            Yii::$app->redis->set($key, $data);
        }
        return $data ? Json::decode($data) : [];
    }

    /**
     * 上一期结余业绩
     * @param $userId
     * @param $periodNum
     * @return array|mixed|\yii\db\ActiveRecord|null
     * @throws \yii\db\Exception
     */
    public static function surplusPerf($userId, $periodNum) {
        $userPerf = self::userPerf($userId, $periodNum);
        return [
            'SURPLUS_1L' => $userPerf['SURPLUS_1L'],
            'SURPLUS_2L' => $userPerf['SURPLUS_2L'],
            'SURPLUS_3L' => $userPerf['SURPLUS_3L'],
            'SURPLUS_4L' => $userPerf['SURPLUS_4L'],
            'SURPLUS_5L' => $userPerf['SURPLUS_5L'],
            'SURPLUS_1L_ZC' => $userPerf['SURPLUS_1L_ZC'],
            'SURPLUS_2L_ZC' => $userPerf['SURPLUS_2L_ZC'],
            'SURPLUS_3L_ZC' => $userPerf['SURPLUS_3L_ZC'],
            'SURPLUS_4L_ZC' => $userPerf['SURPLUS_4L_ZC'],
            'SURPLUS_5L_ZC' => $userPerf['SURPLUS_5L_ZC'],
            'SURPLUS_1L_FX' => $userPerf['SURPLUS_1L_FX'],
            'SURPLUS_2L_FX' => $userPerf['SURPLUS_2L_FX'],
            'SURPLUS_3L_FX' => $userPerf['SURPLUS_3L_FX'],
            'SURPLUS_4L_FX' => $userPerf['SURPLUS_4L_FX'],
            'SURPLUS_5L_FX' => $userPerf['SURPLUS_5L_FX'],
        ];
    }

    /**
     * 获取repairSurplusPerf
     * @param $userId
     * @return int[]|mixed|null
     */
    public static function getRepairSurplusPerf($userId) {
        $cacheKey = self::REDIS_KEY_PREFIX_REPAIR_SURPLUS_PERF;
        $cacheValue = \Yii::$app->redis->hget($cacheKey, $userId);
        if ($cacheValue) {
            $value = Json::decode($cacheValue);
        }else {
            $value = [
                'SURPLUS_1L' => 0,
                'SURPLUS_2L' => 0,
                'SURPLUS_3L' => 0,
                'SURPLUS_4L' => 0,
                'SURPLUS_5L' => 0,
            ];
        }

        return $value;
    }

    /**
     * 累加repairSurplusPerf
     * @param $userId
     * @param $surplusPerf
     * @return int[]|mixed|null
     */
    public static function setRepairSurplusPerf($userId, $surplusPerf) {
        $surplusPerfList = self::getRepairSurplusPerf($userId);
        foreach ($surplusPerfList as $key => $perf) {
            $thisPerf = $surplusPerf[$key] ?? 0;
            $surplusPerfList[$key] = $perf + $thisPerf;

            unset($key, $perf, $thisPerf);
        }

        $cacheKey = self::REDIS_KEY_PREFIX_REPAIR_SURPLUS_PERF;
        \Yii::$app->redis->hset($cacheKey, $userId, Json::encode($surplusPerfList));
        self::addHasRepairPerfUsers($userId);

        unset($userId, $cacheKey, $surplusPerf);

        return $surplusPerfList;
    }

    /**
     * 加入有往期结余业绩的会员
     * @param $userId
     */
    public static function addHasRepairPerfUsers($userId) {
        // 先从已存在的会员池里面获取
        $isset = Yii::$app->redis->hget(self::REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER_POOL, $userId);
        if (!$isset) {
            Yii::$app->redis->hset(self::REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER_POOL, $userId, 1);
            Yii::$app->redis->rpush(self::REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER, $userId);
        }
        unset($userId, $isset);
    }

    /**
     * 获取有往期结余业绩的会员
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public static function getHasRepairPerfUsers($offset = 0, $limit = self::LIMIT) {
        return Yii::$app->redis->lrange(self::REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER, $offset, ($offset + $limit - 1));
    }

    /**
     * 修正业绩缓存清空
     */
    public static function clearRepairAllCache() {
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_REPAIR_SURPLUS_PERF);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER);
        Yii::$app->redis->del(self::REDIS_KEY_PREFIX_HAS_REPAIR_PERF_USER_POOL);
    }

    /**
     * 上一期结余业绩
     * @param $userId
     * @param $periodNum
     * @return array|mixed|\yii\db\ActiveRecord|null
     * @throws \yii\db\Exception
     */
    public static function userPerf($userId, $periodNum) {
        $value = UserPerf::getOneUserPerf($userId);
        return $value;
        $cacheKey = self::REDIS_KEY_PREFIX_USER_PERF . $periodNum;
        $field = $userId;
        $cacheValue = \Yii::$app->redis->hget($cacheKey, $field);
        if ($cacheValue) {
            $value = Json::decode($cacheValue);
        } else {
            $value = UserPerf::getOneUserPerf($userId);
            \Yii::$app->redis->hset($cacheKey, $field, Json::encode($value));
        }
        return $value;
    }

    /**
     * 当前期数的的业绩
     * @param $userId
     * @param $periodNum
     * @param null $perf
     * @return array|mixed
     */
    public static function nowPeriodPerf($userId, $periodNum, $perf = null) {
        $cacheKey = self::REDIS_KEY_PREFIX_NOW_PERIOD_PERF . $periodNum;
        $field = $userId;
        $cacheValue = \Yii::$app->redis->hget($cacheKey, $field);
        if ($cacheValue) {
            $value = Json::decode($cacheValue);
        } else {
            $value = [
                'FX_AMOUNT_CASH' => 0,
                'PV_PCS' => 0,
                'PV_PSS' => 0,//本期的团队业绩
                'PV_PCS_ZC' => 0,//注册
                'PV_PCS_FX' => 0,
                'PV_PCS_FX_CASH' => 0,//现金复消
                'PV_PCS_FX_POINT' => 0,//积分复消
                'PV_1L' => 0,
                'PV_1L_TOUCH' => 0,
                'PV_1L_ZC' => 0,
                'PV_1L_FX' => 0,
                'PV_2L' => 0,
                'PV_2L_TOUCH' => 0,
                'PV_2L_ZC' => 0,
                'PV_2L_FX' => 0,
                'PV_3L' => 0,
                'PV_3L_TOUCH' => 0,
                'PV_3L_ZC' => 0,
                'PV_3L_FX' => 0,
                'PV_4L' => 0,
                'PV_4L_TOUCH' => 0,
                'PV_4L_ZC' => 0,
                'PV_4L_FX' => 0,
                'PV_5L' => 0,
                'PV_5L_TOUCH' => 0,
                'PV_5L_ZC' => 0,
                'PV_5L_FX' => 0,
                'SURPLUS_1L' => 0,
                'SURPLUS_2L' => 0,
                'SURPLUS_3L' => 0,
                'SURPLUS_4L' => 0,
                'SURPLUS_5L' => 0,
                'SURPLUS_1L_ZC' => 0,
                'SURPLUS_2L_ZC' => 0,
                'SURPLUS_3L_ZC' => 0,
                'SURPLUS_4L_ZC' => 0,
                'SURPLUS_5L_ZC' => 0,
                'SURPLUS_1L_FX' => 0,
                'SURPLUS_2L_FX' => 0,
                'SURPLUS_3L_FX' => 0,
                'SURPLUS_4L_FX' => 0,
                'SURPLUS_5L_FX' => 0,
            ];
        }
        if ($perf !== null) {
            foreach ($perf as $key => $pv) {
                if (strpos($key, 'SURPLUS') !== false) {
                    $value[$key] = $pv;
                } else {
                    $value[$key] = $pv + $value[$key];
                }
            }
            Yii::$app->redis->hset($cacheKey, $field, Json::encode($value));
        }
        return $value;
    }

    /**
     * 上个月的业绩
     * @param $userId
     * @param $periodNum
     * @return array|mixed|null|\yii\db\ActiveRecord
     */
    public static function lastMonthPerf($userId, $periodNum) {
        $period = Period::instance();
        $last = $period->getLastMonth($periodNum);
        $lastYearMonth = $last['yearMonth'];
        $cacheKey = self::REDIS_KEY_PREFIX_LAST_MONTH_PERF . $periodNum;
        $field = $userId;
        $cacheValue = \Yii::$app->redis->hget($cacheKey, $field);
        if ($cacheValue) {
            $value = Json::decode($cacheValue);
        } else {
            $value = PerfMonth::getMonthPerf($lastYearMonth, $userId);
            \Yii::$app->redis->hset($cacheKey, $field, Json::encode($value));
        }
        return $value;
    }

    /**
     * 当前月的业绩
     * @param $userId
     * @param $periodNum
     * @param $perf
     * @return array|mixed
     */
    public static function nowMonthPerf($userId, $periodNum, $perf = null) {
        $cacheKey = self::REDIS_KEY_PREFIX_NOW_MONTH_PERF . $periodNum;
        $field = $userId;
        $cacheValue = \Yii::$app->redis->hget($cacheKey, $field);
        if ($cacheValue) {
            $value = Json::decode($cacheValue);
        } else {
            $baseInfo = self::getUserInfo($userId, $periodNum);
            $value = [
                'USER_ID' => $userId,
                'FX_AMOUNT_CASH' => 0,
                'PV_PCS' => 0,
                'PV_PCS_FX' => 0,
                'PV_PSS' => 0,
                'PV_1L' => 0,
                'PV_2L' => 0,
                'PV_3L' => 0,
                'PV_4L' => 0,
                'PV_5L' => 0,
                'VIP_PV_1L_ZC' => 0,
                'VIP_PV_2L_ZC' => 0,
                'VIP_PV_3L_ZC' => 0,
                'VIP_PV_4L_ZC' => 0,
                'VIP_PV_5L_ZC' => 0,
                'PV_1L_TOTAL' => 0,
                'PV_2L_TOTAL' => 0,
                'PV_3L_TOTAL' => 0,
                'PV_4L_TOTAL' => 0,
                'PV_5L_TOTAL' => 0,
                'PV_PSS_TOTAL' => 0,
                'DEC_LEVEL' => $baseInfo['DEC_LV'],
                'EMP_LEVEL' => EmployLevel::getDefaultLevelId(),
            ];
        }
        if ($perf !== null) {
            foreach ($perf as $key => $item) {
                $value[$key] = $item;
            }
        }
        Yii::$app->redis->hset($cacheKey, $field, Json::encode($value));
        return $value;
    }

    /**
     * 获取直推的所有子会员
     * @param $userId
     * @param $periodNum
     * @return array
     */
    public static function getChildrenOneDeepFromRedis($userId, $periodNum){
        $key = self::REDIS_KEY_PREFIX_USER_INFO_CHILD_ONE_DEEP . $periodNum;
        $data = Yii::$app->redis->hget($key, $userId);
        if(!$data){
            $list = UserInfo::findUseDbCalc()->select('USER_ID')->where('REC_UID=:REC_UID', [
                'REC_UID' => $userId
            ])->asArray()->all();
            $data = Json::encode($list);
            unset($list);
            Yii::$app->redis->hset($key, $userId, $data);
        }
        unset($key, $userId, $periodNum);
        return $data ? Json::decode($data, true) : [];
    }

    /**
     * 服务奖最大比例
     * @param $userId
     * @param $periodNum
     * @param int $percent
     * @return float|int
     */
    public static function fwMaxBonusPercent($userId, $periodNum, $percent=0) {
        $cacheKey = self::REDIS_KEY_PREFIX_FW_BONUS . $periodNum;
        $value = Yii::$app->redis->hget($cacheKey, $userId);
        $maxPercent = floatval($value)>0 ? floatval($value) : 0;
        if ( $percent > 0 && $percent > $maxPercent ) {
            $maxPercent = $percent;
            unset($periodNum, $percent);
            Yii::$app->redis->hset($cacheKey, $userId, $maxPercent);

            return $maxPercent;
        }

        unset($userId, $periodNum, $oriBonus, $cacheKey, $value);
        return $maxPercent;
    }

    /**
     * 奖金缓存
     * @param $userId
     * @param $periodNum
     * @param string $bonusType
     * @param float $oriBonus
     * @param array $deductData
     * @return array|mixed
     */
    public static function bonus($userId, $periodNum, $bonusType = null, $oriBonus = 0.00, $deductData=[], $fromMeans='') {
        $cacheKey = self::REDIS_KEY_PREFIX_BONUS . $periodNum;
        $value = [
            'BONUS_TG' => 0,
            'BONUS_QY' => 0,
            'BONUS_BS' => 0,
            'BONUS_QUARTER' => 0,
            'BONUS_BD' => 0,
            'ORI_BONUS_BS' => 0,
            'ORI_BONUS_BD' => 0,
            'ORI_BONUS_QUARTER' => 0,
            'ORI_BONUS_TG' => 0,
            'ORI_BONUS_QY' => 0,
            'INCOME_TOTAL' => 0,
            'BONUS_TOTAL' => 0,
            'RECONSUME_POINTS' => 0,
            'MANAGE_TAX' => 0,
            'ORI_CAPPED_BONUS_QY' => 0,// 团队奖,封顶前金额
        ];
        // 从 redis 中获取当前的结果
        $cacheValue = \Yii::$app->redis->hget($cacheKey, $userId);
        if ($cacheValue) {
            $cacheValue = Json::decode($cacheValue);
            $value = $cacheValue;
        }
        unset($cacheValue);
        if ($oriBonus > 0) {
            $oriBonusType = sprintf('ORI_%s', $bonusType);
            $value[$oriBonusType] += $oriBonus;
            if( $fromMeans !== '' ) {
                $oriBonusMeansType = sprintf('ORI_%s_%s', $bonusType, $fromMeans);
                $value[$oriBonusMeansType] += $oriBonus;
            }

            if( !in_array($bonusType, self::NOT_SEND_BONUS_LIST) ) {
                if( $deductData ) {
                    $value[$bonusType] += $deductData['surplus'];
                    $value['RECONSUME_POINTS'] += $deductData['reConsumePoints'];
                    $value['MANAGE_TAX'] += $deductData['manageTax'];
                }else {
                    $value[$bonusType] += $oriBonus;
                }
                $value['BONUS_TOTAL'] += $oriBonus;
            }

            if( in_array($bonusType, self::INCOME_BONUS_LIST) ) {
                self::addHasIncomeUsers($userId, $periodNum);
//                if( !in_array($bonusType, self::NOT_SEND_BONUS_LIST) ) {
//                    $value['INCOME_TOTAL'] += $oriBonus;
//                }
            }

            Yii::$app->redis->hset($cacheKey, $userId, Json::encode($value));
            unset($oriBonusType);
            self::addHasBonusUsers($userId, $periodNum);
        }
        unset($userId, $periodNum, $bonusType, $oriBonus, $deductData, $cacheKey);
        return $value;
    }

    public static function tourismBonus($userId, $periodNum, $bonus = 0.00) {
        $cacheKey = self::REDIS_KEY_PREFIX_TOURISM_BONUS . $periodNum;

        $value = 0.00;
        if( $bonus > 0 ) {
            Yii::$app->redis->hset($cacheKey, $userId, $bonus);
            $value = $bonus;
            //加入有奖金的会员中
            self::addHasBonusUsers($userId, $periodNum);
        }else {
            $cacheValue = \Yii::$app->redis->hget($cacheKey, $userId);
            if ($cacheValue) {
                $value = $cacheValue;
            }
            unset($cacheValue);
        }

        unset($cacheKey, $userId, $periodNum, $bonus);
        return $value;
    }

    public static function villaBonus($userId, $periodNum, $bonus = 0.00) {
        $cacheKey = self::REDIS_KEY_PREFIX_VILLA_BONUS . $periodNum;

        $value = 0.00;
        if( $bonus > 0 ) {
            Yii::$app->redis->hset($cacheKey, $userId, $bonus);
            $value = $bonus;
            //加入有奖金的会员中
            self::addHasBonusUsers($userId, $periodNum);
        }else {
            $cacheValue = \Yii::$app->redis->hget($cacheKey, $userId);
            if ($cacheValue) {
                $value = $cacheValue;
            }
            unset($cacheValue);
        }

        unset($cacheKey, $userId, $periodNum, $bonus);
        return $value;
    }

    public static function garageBonus($userId, $periodNum, $bonus = 0.00) {
        $cacheKey = self::REDIS_KEY_PREFIX_GARAGE_BONUS . $periodNum;

        $value = 0.00;
        if( $bonus > 0 ) {
            Yii::$app->redis->hset($cacheKey, $userId, $bonus);
            $value = $bonus;
            //加入有奖金的会员中
            self::addHasBonusUsers($userId, $periodNum);
        }else {
            $cacheValue = \Yii::$app->redis->hget($cacheKey, $userId);
            if ($cacheValue) {
                $value = $cacheValue;
            }
            unset($cacheValue);
        }

        unset($cacheKey, $userId, $periodNum, $bonus);
        return $value;
    }
}