<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace loyalsoft;

/**
 * Description of ActiveProc
 *
 * @author c'y'zhao
 */
class ActiveProc {

    const tab_token_gift = "tab_token_gift";

    /**
     * 逻辑分发
     * 所有的Proc中必须有这样一个方法
     * @param Req $req
     */
    public static function procMain($req) {
        switch ($req->cmd) {
            case CmdCode::cmd_active_day7_drawreward:                           # 6101 签到
                return ActiveProc::Day7_DrawReward();
            case CmdCode::cmd_active_drawPackageByCode:                         # 6102 兑换码礼包
                return ActiveProc::drawPackageByCode();
            case CmdCode::cmd_active_lottery_Tree:                              # 6103 转盘抽奖
                return ActiveProc::lottery_Tree();
            case CmdCode::cmd_active_lottery_Tree_cashExchange:                 # 6104 元宝兑换抽奖券
                return ActiveProc::lottery_Tree_cashExchange();
            case CmdCode::cmd_active_lotteryNumBox_RewardReceived:              # 6105 抽奖宝箱奖励领取
                return ActiveProc::lotteryNumBox_RewardReceived();
            case CmdCode::cmd_active_LotteryExchangeItem:                       # 6106 兑换
                return ActiveProc::LotteryExchangeItem();
            case CmdCode::cmd_active_day7_accumulateDrawreward:                 # 6107 7日签到 累计天数宝箱奖励领取
                return ActiveProc::Day7_AccumulateDrawreward();
            case CmdCode::cmd_active_limitTsBuy:                                # 6108 限时贩售
                return ActiveProc::LimitTsBuy_Drawreward();
            case CmdCode::cmd_active_battlePassDrawReward:                      # 6109 战令奖励领取
                return ActiveProc::BattlePassDrawReward();
            case CmdCode::cmd_active_day7_drawreward_newPlayer:                 # 6110 新手7日签到领取奖励
                return ActiveProc::Day7_Drawreward_NewPlayer();
            case CmdCode::cmd_active_getTodayOnlineInfos:                       # 6111 查询当天在线时长信息
                return self::GetTodayOnlineInfos();
            case CmdCode::cmd_active_draw_onlinegift:                           # 6112 领取在线(时长)礼包
                return self::DrawOnlineGift();    
            case CmdCode::cmd_active_YanBaoBuyItemActive_drawReward:
                return self::YanBaoBuyItemActive_drawReward();
            default:
                Err(ErrCode::cmd_err);
        }
    }
    
    /**
     * [6112] 领取连续在线礼包
     */
    static function YanBaoBuyItemActive_drawReward() {
        list($typeId) = req()->paras;                                           # 提取参数: 礼包的编号
                                                  
        $Mo = GameConfig::activity_cashmall_getItem($typeId);                   # 常量数据
        my_Assert(null != $Mo, ErrCode::err_const_no);                          # 防御找不到配置数据
        
        my_Assert(ctx()->baseInfo->cash >= explode(',', $Mo->cost)[1], ErrCode::notenough_cash_msg);
        ctx()->baseInfo->Consume_Cash(explode(',', $Mo->cost)[1]);
        
        $rewardArr = ctx()->privateState->YuanbaoBuy_RewardRecord;
        $count = array_count_values($rewardArr)[$typeId];
        my_Assert($count < $Mo->limitNum, ErrCode::user_shop_LimitNum);
        
//        my_Assert(!in_array($typeId, ctx()->privateData()->YuanbaoBuy_RewardRecord), #           # 判断礼包ID是否已经领取
//                ErrCode::active_hasgetted);
        $err = StoreProc::AddMultiItemInStore($Mo->reward);                     # 发放奖励
        my_Assert(ErrCode::ok == $err, $err);                                   # 发放奖励失败
        ctx()->privateData(true)->YuanbaoBuy_RewardRecord[] = $typeId;          # 记录已领礼包ID
                   
        UserProc::updateUserInfo();                                             # 回写用户数据
        return Resp::ok(array(                   
                    "reward" => StoreProc::$reward,
                    "reward_Gem" => StoreProc::$reward_Gem,
                    "reward_equip" => StoreProc::$reward_equip,
                    'gold' => ctx()->base()->gold,
                    'cash' => ctx()->base()->cash,                  
                    'store' => ctx()->store(),
                    'heros' => ctx()->heros()
        ));                                                                     # 设置返回值
    }  
    
    public static function GetTodayOnlineInfos() {
        return Resp::ok(array(
                    'onlineGiftts' => ctx()->privateState->onlineGiftts,
                    'onlineGiftIDs' => ctx()->privateState->onlineGiftIDs,                 
        )); 
    }
     
    /**
     * 清理/重置 在线礼包时间戳
     */
    public static function ClearOnlineGiftTs() {
        ctx()->privateState->onlineGiftts = 1;
        ctx()->privateState->onlineGiftIDs = array();       
    }
    
    /**
     * 清理/重置 元宝商城购买记录
     */
    public static function ClearYanBaoBuyItemActive_drawReward() {
        ctx()->privateState->YuanbaoBuy_RewardRecord = array();         
    }

    /**
     * [6112] 领取连续在线礼包
     */
    static function DrawOnlineGift() {
        list($giftid) = req()->paras;                                                  # 提取参数: 礼包的编号
                                                  
        $giftData = GameConfig::activity_onlinegift_getItem($giftid);           # 在线礼包常量数据
        my_Assert(null != $giftData, ErrCode::onlinegift_constno_err);          # 防御找不到配置数据
//        my_Assert($privateState->onlineGiftts + 30 >= $giftData->onlineSec, #        # 时间未到，不可以领取
//                ErrCode::onlinegift_timenotenough);
        my_Assert(ctx()->privateState->onlineGiftts >= $giftData->onlineSec ,   #
                ErrCode::active_day7_expired);
        my_default_Arr(ctx()->privateData()->onlineGiftIDs);                    # 防御未初始化领取记录
        my_Assert(!in_array($giftid, ctx()->privateData()->onlineGiftIDs), #           # 判断礼包ID是否已经领取
                ErrCode::active_hasgetted);
        $err = StoreProc::AddMultiItemInStore($giftData->rewardstr);            # 发放奖励
        my_Assert(ErrCode::ok == $err, $err);                                   # 发放奖励失败
        ctx()->privateData(true)->onlineGiftIDs[] = $giftid;                               # 记录已领礼包ID
        //$privateState->onlineGiftts = 0;                                        #每次领取奖励则时间重新计算

        
        UserProc::updateUserInfo();                                             # 回写用户数据
        return Resp::ok(array(
                    'onlineGiftts' => ctx()->privateState->onlineGiftts,
                    'onlineGiftIDs' => ctx()->privateState->onlineGiftIDs,
                    "reward" => StoreProc::$reward,
                    "reward_Gem" => StoreProc::$reward_Gem,
                    "reward_equip" => StoreProc::$reward_equip,
                    'gold' => ctx()->base()->gold,
                    'cash' => ctx()->base()->cash,
                    'tili' => ctx()->base()->tili,
                    'tili_ts' => ctx()->base()->tili_ts,
                    'store' => ctx()->store(),
                    'heros' => ctx()->heros()
        ));                                                                     # 设置返回值
    }

    /**
     * 6106 抽奖里面的兑换
     * @return type
     */
    public static function LotteryExchangeItem() {
        list($id) = req()->paras;

        $arr = array_count_values(ctx()->privateState->lotteryExchange);
        $num = $arr[$id];

        $mo = GameConfig::activity_lotteryitem_exchange_getItem($id);
        my_Assert($mo != null, ErrCode::err_const_no);
        my_Assert($num < $mo->exchangeNum, ErrCode::active_lotteryExchangeNumLimit);

        $itemNum = 0;
        $cost = explode(',', $mo->cost);
        $costId = $cost[0];
        if (StlUtil::dictHasProperty(ctx()->store->items, $costId)) {
            $itemNum = ctx()->store->items->$costId;
        }

        my_Assert($itemNum >= $cost[1], ErrCode::notenough_item);
        ctx()->store->removeItem($costId, $cost[1]);

        StoreProc::AddMultiItemInStore($mo->reward);
        ctx()->privateState->lotteryExchange[] = $id;

        UserProc::updateUserInfo();
        return Resp::ok(array(
                    "store" => ctx()->store,
                    'cash' => ctx()->baseInfo->cash,
                    'gold' => ctx()->baseInfo->gold,
                    'reward' => StoreProc::$reward,
                    'reward_Gem' => StoreProc::$reward_Gem,
                    'reward_equip' => StoreProc::$reward_equip,
        ));
    }

    /**
     * 6105 抽奖宝箱奖励领取
     * @return type
     */
    public static function lotteryNumBox_RewardReceived() {
        list($id) = req()->paras;

        $mo = GameConfig::activity_lotterynum_accumulate_getItem($id);
        my_Assert($mo != null, ErrCode::err_const_no);
        my_Assert(ctx()->privateState->lotteryNum >= $id, ErrCode::active_lotteryNumNotEnough);
        my_Assert(!in_array($id, ctx()->privateState->lotteryNumRewardReceived), ErrCode::active_hasgetted);

        StoreProc::AddMultiItemInStore($mo->reward);
        ctx()->privateState->lotteryNumRewardReceived[] = $id;

        UserProc::updateUserInfo();
        return Resp::ok(array(
                    "store" => ctx()->store,
                    'cash' => ctx()->baseInfo->cash,
                    'reward' => StoreProc::$reward,
                    'reward_Gem' => StoreProc::$reward_Gem,
                    'reward_equip' => StoreProc::$reward_equip,
        ));
    }

    /**
     *  6103 转盘抽奖
     */
    public static function lottery_Tree() {
        list($num) = req()->paras; //抽奖次数 1  10

        $arr = array(1, 10);
        my_Assert(in_array($num, $arr), ErrCode::active_lotteryNumErr);
        my_Assert(ctx()->privateState->lotteryNum + $num <= glc()->activity_lottery_allNum, ErrCode::active_lotteryNumLimit);

        $costTag = true;
        if ($num == 1 && ctx()->privateState->lotteryNum_free < GameConfig::glc2()->activity_lottery_FreeNum + GameConfig::glc2()->activity_lottery_GuanggaoNum) {
            $costTag = false;
        }

        if ($num == 1) {
            ctx()->privateState->lotteryNum_free += 1;
        }

        if ($costTag) {
            $cost = "";
            if ($num == 1) {
                $cost = glc()->activity_lottery_tree_one_cost;
            } else {
                $cost = glc()->activity_lottery_tree_ten_cost;
            }
            my_Assert($cost != "", ErrCode::active_lotteryCostErr);
            $costArr = explode(',', $cost);
            $item = ctx()->store->items;
            $costId = $costArr[0];
            $costNum = $costArr[1];
            my_Assert(StlUtil::dictHasProperty($item, $costId) && $item->$costId >= $costNum, ErrCode::notenough_item);
            ctx()->store->removeItem($costId, $costNum);
        }

        if (ctx()->privateState->lotteryNum_free > GameConfig::glc2()->activity_lottery_FreeNum && ctx()->privateState->lotteryNum_free <= GameConfig::glc2()->activity_lottery_FreeNum + GameConfig::glc2()->activity_lottery_GuanggaoNum) {
            my_Assert(now() - ctx()->privateData(true)->activity_lottery_guanggaoTs >= GameConfig::glc2()->activity_lottery_GuanggaoDownTs, ErrCode::user_shop_DownTsLimit);
            ctx()->privateData(true)->activity_lottery_guanggaoTs = now();

            TaskProc::OnLookGuanggao();
        }

        if (ctx()->privateState->lotteryNum < glc()->activity_lottery_allNum) {
            ctx()->privateState->lotteryNum += $num;
        }

        $rewardList = array();
        $dic = GameConfig::activity_lottery_tree();
        for ($i = 0; $i < $num; $i++) {
            $randNum = random_int(1, 10000);
            $start = 0;
            $end = 0;
            foreach ($dic as $id => $mo) {
                $end += $mo->per * 10000;
                if ($randNum > $start && $randNum <= $end) {
                    $rewardList[] = $id;
                    StoreProc::AddMultiItemInStore($mo->reward);
                    $prize = explode(',', $mo->reward);
                    if (GameConfig::item_getItem($prize[0])->itemType == 201 && GameConfig::item_getItem($prize[0])->quality >= 4 && ctx()->privateState->lottery_qualGem_4 == 0) {
                        ctx()->privateState->lottery_qualGem_4 = 1;
                    }

                    break;
                }
                $start = $end;
            }
        }

        UserProc::updateUserInfo();
        return Resp::ok(array(
                    "store" => ctx()->store,
                    'reward' => StoreProc::$reward,
                    'reward_Gem' => StoreProc::$reward_Gem,
                    'reward_equip' => StoreProc::$reward_equip,
                    'gold' => ctx()->baseInfo->gold,
                    'cash' => ctx()->baseInfo->cash,
                    'privateState' => ctx()->privateState,
                    'indexReward' => $rewardList,
                    'heros' => ctx()->heros,
        ));
    }

    /**
     * 元宝兑换寻宝券
     * @return type
     */
    public static function lottery_Tree_cashExchange() {
        list($num) = req()->paras; //抽奖次数 1  10

        $cost = "";
        if ($num == 1) {
            $cost = glc()->activity_lottery_tree_one_cost;
        } else {
            $cost = glc()->activity_lottery_tree_ten_cost;
        }
        my_Assert($cost != "", ErrCode::active_lotteryCostErr);
        $costArr = explode(',', $cost);
        $item = ctx()->store->items;
        $costId = $costArr[0];
        $costNum = $costArr[1];

        $selfNum = 0;
        if (StlUtil::dictHasProperty($item, $costId)) {
            $selfNum = $item->$costId;
        }
        my_Assert($selfNum < $costNum, ErrCode::active_lottery_unwantedExchange);

        $costNum -= $selfNum;
        $cash = glc()->activity_lottery_oneCost_cash * $costNum;
        my_Assert(ctx()->baseInfo->cash >= $cash, ErrCode::notenough_cash_msg);
        ctx()->baseInfo->Consume_Cash($cash);
        StoreProc::AddMultiItemInStore($costId . ',' . $costNum);

        UserProc::updateUserInfo();
        return Resp::ok(array(
                    "store" => ctx()->store,
                    'cash' => ctx()->baseInfo->cash,
        ));
    }

    /**
     *  6102 兑换码礼包
     */
    static function drawPackageByCode() {
        list($activeId, $codestring) = req()->paras;                            # 取参数 活动id, 兑换码

        $codePlatStr = "";
        $packageID = 0;

        if (self::PublicTokenCodeCheck($codestring)) {
            $packageInfo = GameConfig::token_PublicGift_getItem($codestring);
            my_Assert($packageInfo->expirets >= now() && $packageInfo->startTs <= now(),
                    ErrCode::active_activecode_outtime);
            my_Assert(!in_array($packageInfo->id, ctx()->privateState->usedTokens), ErrCode::active_hasgetted); # 已经领取过该礼包了
            $packageID = $packageInfo->id;
            //$err = StoreProc::AddMultiItemInStore($packageInfo->reward);            # 发放礼包
            EmailProc::SendPackageByCodeMail(req()->zoneid, req()->uid, $packageInfo->reward);
            my_Assert(ErrCode::ok == $err, $err);
        } else {
            $active = GameConfig::activity_getItem($activeId);                      # 活动数据
            my_Assert(null != $active, ErrCode::active_const_no_err);
            my_Assert($active->startts <= now() && $active->endts >= now(), ErrCode::active_time); # 校验开放时间
            my_Assert(preg_match("/^[a-kmnp-z2-9]{10}$/", $codestring), ErrCode::active_activecode_format); # 基础格式校验(10个特定字符)
            $activeCode = CipheredBase32::Decode($codestring);                      # 解码
            $codePlatStr = GameConstants::GetPlatStringByActivteCode($activeCode);  # platstr
            my_Assert(GameConstants::AllPlatStr == $codePlatStr #                   # 忽略全平台礼包
                    || req()->getPlatStr() == $codePlatStr, #                       # 平台字符串必须相符
                    ErrCode::active_activecode_plat); #                             # 平台错误

            my_Assert(is_int($activeCode->number) #                                 # 编号为int值
                    && $activeCode->number >= 1 && $activeCode->number <= 50000, #  # 检查 兑换码的编号范围0~50000
                    ErrCode::active_activecode_format);

            $packageID = $activeCode->package;                                      # 礼包id
            $packageInfo = GameConfig::token_gift_getItem($packageID);               # 礼包常量数据
            my_Assert(null != $packageInfo, ErrCode::err_const_no);                 # 防御
            CLog::err(json_encode($packageInfo));
            my_Assert($packageInfo->expirets >= now() && $packageInfo->startTs <= now(),
                    ErrCode::active_activecode_outtime);                            # 激活码已经失效,或者礼包尚未开启

            $privateState = new Info_PrivateState(ctx()->privateState);             # 快速访问
            my_Assert(!in_array($packageID, $privateState->usedTokens), ErrCode::active_hasgetted); # 已经领取过该礼包了
            my_Assert(!self::checkActiveCodeIsUsed($activeCode), ErrCode::active_activecode_used);  # 检查 该激活码是否别人已经使用过了
            $err = StoreProc::AddMultiItemInStore($packageInfo->reward);            # 发放礼包
            EmailProc::SendPackageByCodeMail(req()->zoneid, req()->uid, $packageInfo->reward);
//            my_Assert(ErrCode::ok == $err, $err);                                   # 防御发放礼包过程出错
            $ok = self::setActiveCodeUserRecord($activeCode, req()->uid);           # 插入数据库
            my_Assert($ok, ErrCode::err_db);                                        # 数据库操作失败- 重试
        }

        ctx()->privateState->usedTokens[] = $packageID;

        UserProc::updateUserInfo();                                             # 回存玩家数据
        $ret = array(#                                                          # 返回值
            "plat" => $codePlatStr,
            "packageId" => $packageID,
            "reward" => $packageInfo->reward,
            'gold' => ctx()->base()->gold,
            'cash' => ctx()->base()->cash,
            //'tili' => ctx()->base()->tili,
            'store' => ctx()->store,
                //'hero' => ctx()->heros,
        );
        return Resp::ok($ret);                                                  # 返回成功信息
    }

    public static function PublicTokenCodeCheck($codestring) {
        $dic = GameConfig::token_PublicGift();
        if (StlUtil::dictHasProperty($dic, $codestring)) {
            return true;
        }
        return false;
    }

    /**
     * 检查兑换码是否已经使用过了
     * @param ActiveCode $activeCode
     * @return boolean true : 已经用过了, false : 激活码尚未使用过.
     */
    static function checkActiveCodeIsUsed($activeCode) {
        $sql = sprintf("`plat`='%d' and `package`='%d' and `number`='%d'", #       # where 子句
                $activeCode->plat, $activeCode->package, $activeCode->number);
        $rows = daoInst()
                ->select()
                ->from(self::tab_token_gift)                                     # 表名
                ->where($sql)
                ->count();
        return $rows > 0;
    }

    /**
     * 将兑换码添加到使用记录中
     * @param ActiveCode $actvieCode
     * @param string $uid
     * @return boolean true: 操作成功, false: 操作失败
     */
    static function setActiveCodeUserRecord($actvieCode, $uid) {
        $actvieCode->uid = $uid;                                                # 添加uid
        $ret = daoInst()
                ->insert(self::tab_token_gift)                                   # 表名
                ->data($actvieCode)
                ->exec();
        return $ret > 0;
    }

    /**
     * 7日签到 数据更新
     */
    public static function DailyResetDay7Task($unlock = false) {
        if (!$unlock && !FightProc::isFunUnlock(5)) {//之所以这有两个判断是因为这个 活动解锁的代码监测位置问题，fightProc 里解锁监测代码在 $gateInfo->tz_state = $index;之前了 这个位置没有办法解锁
            return;
        }

        if (count(ctx()->privateState->LoginDays) >= 7) {
            ctx()->privateState->LoginDays = array();
            ctx()->privateState->day7_drawed = array();
        }
        $index = count(ctx()->privateState->LoginDays) + 1;
        ctx()->privateState->LoginDays[] = $index;
        ctx()->privateState->day7_accumulate += 1;
    }

    /**
     * 6101 签到
     * @return type
     */
    public static function Day7_DrawReward() {
        list($day) = req()->paras;                                              # 参数: 领取第x天的奖励

        my_Assert(in_array($day, ctx()->privateState->LoginDays), ErrCode::active_day7_expired);
        my_Assert(!in_array($day, ctx()->privateState->day7_drawed), ErrCode::active_hasgetted);
        $day_rwd = GameConfig::activity_day7_getItem($day);                     # 查询奖励数据
        my_Assert(null != $day_rwd, ErrCode::err_const_no);                     # 防御找不到配置
        StoreProc::AddMultiItemInStore($day_rwd->reward);                       # 发放奖励
        ctx()->privateState->day7_drawed[] = $day;                              # 添加领取记录

        UserProc::updateUserInfo();                                             # 回存
        return Resp::ok(array('gold' => ctx()->baseInfo->gold,
                    'cash' => ctx()->baseInfo->cash,
                    'store' => ctx()->store,
                    'heros' => ctx()->heros,
                    'reward' => StoreProc::$reward,
                    'reward_Gem' => StoreProc::$reward_Gem,
                    'reward_equip' => StoreProc::$reward_equip,
        ));
    }

    /**
     * 6107 7日签到 累计天数宝箱奖励领取
     * @return type
     */
    public static function Day7_AccumulateDrawreward() {
        list($day) = req()->paras;                                              # 参数: 领取第x天的奖励

        $yushu = $day % 10;
        if ($yushu == 0) {
            $num = $day / 10;
            if ($num > 6) {
                $n = $num % 6;
                $typeId = $n * 10;
            } else {
                $typeId = $day;
            }
        } else {
            $typeId = $yushu;
        }

        my_Assert(ctx()->privateState->day7_accumulate >= $day, ErrCode::active_day7_expired);
        my_Assert(!in_array($day, ctx()->privateState->day7_accumulateDrawed), ErrCode::active_hasgetted);
        $day_rwd = GameConfig::active_day7_accumulate_getItem($typeId);                     # 查询奖励数据
        my_Assert(null != $day_rwd, ErrCode::err_const_no);                     # 防御找不到配置
        StoreProc::AddMultiItemInStore($day_rwd->reward);                       # 发放奖励
        ctx()->privateState->day7_accumulateDrawed[] = $day;
        $baseArr = array(2, 4, 6, 8, 10);
        $tag = true;
        $loopNum = ctx()->privateState->day7_accumulate_loopNum;
        foreach ($baseArr as $id) {//查看当前这组天奖励是否全部被领取
            $id += ($loopNum - 1) * 10;
//            if(ctx()->privateState->day7_accumulate < $id){
//                $tag = false;
//                break;
//            }

            if (!in_array($id, ctx()->privateState->day7_accumulateDrawed)) {
                $tag = false;
            }
        }

        if ($tag) {//$typeId % 10 == 0
            ctx()->privateState->day7_accumulate_loopNum += 1;
        }


        UserProc::updateUserInfo();                                             # 回存
        return Resp::ok(array('gold' => ctx()->baseInfo->gold,
                    'cash' => ctx()->baseInfo->cash,
                    'store' => ctx()->store,
                    'privateState' => ctx()->privateState,
                    'reward' => StoreProc::$reward,
                    'reward_Gem' => StoreProc::$reward_Gem,
                    'reward_equip' => StoreProc::$reward_equip,
        ));
    }

    /**
     * 限时贩卖 2天一刷
     */
    public static function ResetLimitTsBuy() {
        ctx()->privateState->limitTsBuy_RewardRecord = array();

        $mo = GameConfig::subfun_unlock_getItem(Enum_SubFunType::LimitTsSale);
        $day = $mo->ts;
        $startDay = TimeUtil::totalDays($mo->startTs);
        $nextDay = TimeUtil::totalDays();

        $num = $nextDay - $startDay;
        $refershType = $num % $day; //day 2天一刷新 余数只会是0 或 1; 0:两天后在刷新，1就是已经过了一天了，在过一天就刷新，当前时间减一天
        ctx()->privateState->nextDayLogin = now() - 86400 * $refershType;
//        if ($refershType == 1) {
//            ctx()->privateState->nextDayLogin = now() - 86400;
//        }

        $val = intval($num / $day);
        $yushu = $val % glc()->activity_limitTsBuy_giftTypeNum;
        $type = $yushu + 1;

        $arr = GameConfig::activity_promopackinfo_type_getItemArray($type);
        $count = count($arr);

        $ret = array();
        if ($count == 6) {
            $ret = $arr;
        } else {
            for ($i = 0; $i < 6; $i++) {
                $count = count($arr);
                $rand = rand(0, $count - 1);
                $ret[] = $arr[$rand];
                StlUtil::arrayRemoveAt($arr, $rand);
                if (count($arr) == 0) {
                    break;
                }
            }
        }
        ctx()->privateState->limitTsBuy_RandIds = array();
        foreach ($ret as $mo) {
            ctx()->privateState->limitTsBuy_RandIds[] = $mo->typeId;
        }
    }

    /**
     * 6108 限时贩售
     */
    public static function LimitTsBuy_Drawreward() {
        list($typeId) = req()->paras;                                           # 参数: 领取第x天的奖励

        my_Assert(in_array($typeId, ctx()->privateState->limitTsBuy_RandIds), ErrCode::active_const_no_err);
        $mo = GameConfig::activity_promopackinfo_getItem($typeId);              # 查询奖励数据
        my_Assert(null != $mo, ErrCode::err_const_no);                          # 防御找不到配置

        my_Assert(ctx()->baseInfo->cash >= explode(',', $mo->cost)[1], ErrCode::notenough_cash_msg);
        ctx()->baseInfo->Consume_Cash(explode(',', $mo->cost)[1]);

        $rewardArr = ctx()->privateState->limitTsBuy_RewardRecord;
        $count = array_count_values($rewardArr)[$typeId];
        my_Assert($count < $mo->limitNum, ErrCode::user_shop_LimitNum);

        StoreProc::AddMultiItemInStore($mo->reward);                            # 发放奖励
        ctx()->privateState->limitTsBuy_RewardRecord[] = $typeId;

        UserProc::updateUserInfo();                                             # 回存
        return Resp::ok(array('gold' => ctx()->baseInfo->gold,
                    'cash' => ctx()->baseInfo->cash,
                    'store' => ctx()->store,
                    'heros' => ctx()->heros,
                    'privateState' => ctx()->privateState,
                    'reward' => StoreProc::$reward,
                    'reward_Gem' => StoreProc::$reward_Gem,
                    'reward_equip' => StoreProc::$reward_equip,
        ));
    }

    /**
     * 6109 战令奖励领取
     */
    public static function BattlePassDrawReward() {
        list($id) = req()->paras;

        $mo = GameConfig::activity_battlepass_getItem($id);                     # 查询奖励数据
        my_Assert(null != $mo, ErrCode::err_const_no);                          # 防御找不到配置
        $subFunType = $mo->type;
        $typeId = $mo->typeId;

        $str_1 = $subFunType . '-1-' . $typeId;
        $str_2 = $subFunType . '-2-' . $typeId;
        $isHasBuy_high = false;
        switch ($subFunType) {
            case Enum_SubFunType::ActivePoint_BattlePass:
                $point = ctx()->privateState->battlePass_taskPoint;
                my_Assert($point >= $typeId, ErrCode::active_pointNotEnough);

                if (ctx()->privateState->battlePass_activePoint_cost_ts > 0 && now() < ctx()->privateState->battlePass_activePoint_cost_ts + 30 * 24 * 60 * 60) {
                    $isHasBuy_high = true;
                }

                break;
            case Enum_SubFunType::Tili_BattleBass:
                my_Assert(ctx()->privateData()->battlePass_tili >= $typeId, ErrCode::active_costTiliNotEnough);
                if (ctx()->privateState->battlePass_tili_cost_ts > 0 && now() < ctx()->privateState->battlePass_tili_cost_ts + 30 * 24 * 60 * 60) {
                    $isHasBuy_high = true;
                }
                break;
            case Enum_SubFunType::Gate_BattleBass:
                my_Assert(StlUtil::dictHasProperty(ctx()->gates->GateList, $typeId), ErrCode::gate_GateNoUnlock);
                my_Assert(ctx()->gates->GateList->$typeId->pass > 0, ErrCode::evolve_GateNoPass);

                if (ctx()->privateState->battlePass_gate_cost_ts > 0 && now() < ctx()->privateState->battlePass_gate_cost_ts + 30 * 24 * 60 * 60) {
                    $isHasBuy_high = true;
                }
                break;

            default:
                break;
        }

        if (!in_array($str_1, ctx()->privateState->battlePassRewardReceived)) {
            StoreProc::AddMultiItemInStore($mo->rewards_1);                     # 发放奖励
            ctx()->privateData(true)->battlePassRewardReceived[] = $str_1;
        }

        //my_Assert(!in_array($str_1, ctx()->privateState->battlePassRewardReceived), ErrCode::active_hasgetted);
        if ($isHasBuy_high && !in_array($str_2, ctx()->privateState->battlePassRewardReceived)) {
            StoreProc::AddMultiItemInStore($mo->rewards_2);                     # 发放奖励
            ctx()->privateData(true)->battlePassRewardReceived[] = $str_2;
        }

        UserProc::updateUserInfo();                                             # 回存
        return Resp::ok(array('gold' => ctx()->baseInfo->gold,
                    'cash' => ctx()->baseInfo->cash,
                    'store' => ctx()->store,
                    'heros' => ctx()->heros,
                    'privateState' => ctx()->privateState,
                    'reward' => StoreProc::$reward,
                    'reward_Gem' => StoreProc::$reward_Gem,
                    'reward_equip' => StoreProc::$reward_equip,
                    "tili" => ctx()->baseInfo->tili,
                    "tili_ts" => ctx()->baseInfo->tili_ts,
        ));
    }

    /**
     * 重置战令奖励信息 一个月一清理但是不同战令 开始时间不同所以 清理时间也不同
     * @param type $type
     */
    public static function ResetBattlePassReward($type) {
        $list = ctx()->privateState->battlePassRewardReceived;
        $rmArr = array();
        foreach ($list as $str) {
            $arr = explode('-', $str);
            if ($arr[0] == $type) {
                $rmArr[] = $str;
            }
        }

        foreach ($rmArr as $k) {
            StlUtil::arrayRemove(ctx()->privateData(true)->battlePassRewardReceived, $k);
        }
    }

    /**
     * 7日签到 数据更新
     */
    public static function InitDay7_Sign_NewPlayer($unlock = false) {
        if (!$unlock && !FightProc::isFunUnlock(21)) {//之所以这有两个判断是因为这个 活动解锁的代码监测位置问题，fightProc 里解锁监测代码在 $gateInfo->tz_state = $index;之前了 这个位置没有办法解锁
            return;
        }
        $index = count(ctx()->privateState->day7_drawed_newPlayer_LoginDays) + 1;
        if (count(ctx()->privateState->day7_drawed_newPlayer_LoginDays) < 7) {
            ctx()->privateState->day7_drawed_newPlayer_LoginDays[] = $index;
        }
    }

    /**
     * 6110 新手7日签到
     * @return type
     */
    public static function Day7_Drawreward_NewPlayer() {
        list($day) = req()->paras;                                              # 参数: 领取第x天的奖励

        my_Assert(in_array($day, ctx()->privateState->day7_drawed_newPlayer_LoginDays), ErrCode::active_day7_expired);
        my_Assert(!in_array($day, ctx()->privateState->day7_drawed_newPlayer), ErrCode::active_hasgetted);
        $day_rwd = GameConfig::activity_day7sign_newplayer_getItem($day);                     # 查询奖励数据
        my_Assert(null != $day_rwd, ErrCode::err_const_no);                     # 防御找不到配置
        StoreProc::AddMultiItemInStore($day_rwd->reward);                       # 发放奖励
        ctx()->privateState->day7_drawed_newPlayer[] = $day;                    # 添加领取记录

        UserProc::updateUserInfo();                                             # 回存
        return Resp::ok(array('gold' => ctx()->baseInfo->gold,
                    'cash' => ctx()->baseInfo->cash,
                    'store' => ctx()->store,
                    'heros' => ctx()->heros,
                    'reward' => StoreProc::$reward,
                    'reward_Gem' => StoreProc::$reward_Gem,
                    'reward_equip' => StoreProc::$reward_equip,
        ));
    }
}
