<?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 {

    /**
     * 逻辑分发
     * 所有的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();
            default:
                Err(ErrCode::cmd_err);
        }
    }

    /**
     *  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($codestring, ctx()->privateState->usedTokens), ErrCode::active_hasgetted); # 已经领取过该礼包了
            $packageID = $codestring;
            $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);                 # 防御
            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);            # 发放礼包
            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_toke_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_toke_gift)                                   # 表名
                ->data($actvieCode)
                ->exec();
        return $ret > 0;
    }

    /**
     * 7日签到 数据更新
     */
    public static function DailyResetDay7Task() {
        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;
    }

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

        my_Assert(in_array($day, $user->privateState->LoginDays), ErrCode::active_day7_expired);
        my_Assert(!in_array($day, $user->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);                       # 发放奖励
        $user->privateState->day7_drawed[] = $day;                              # 添加领取记录

        ctx($user);
        UserProc::updateUserInfo();                                             # 回存
        return Resp::ok(array(
                    'gold' => $user->baseInfo->gold,
                    'cash' => $user->baseInfo->cash,
                    'tili' => $user->baseInfo->tili,
                    'store' => $user->store,
        ));
    }

}
