<?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 TaskProc
 *
 * @author c'y'zhao
 */
class TaskProc {

    /**
     * 逻辑分发
     * 所有的Proc中必须有这样一个方法
     * @param Req $req
     */
    public static function procMain($req) {
        switch ($req->cmd) {
            case CmdCode::cmd_task_getInfo:                                     # 6201
                return TaskProc::getTaskInfo();
            case CmdCode::cmd_task_getReward:                                   # 6202
                return TaskProc::getReward();
            case CmdCode::cmd_task_getAchieveReward:                            # 6203 领取成就奖励
                return TaskProc::getAchieveReward();
            case CmdCode::cmd_task_receiveActiveTaskReward:                     # 6204 领取活动任务奖励
                return TaskProc::receiveActiveTaskReward();
            case CmdCode::cmd_task_receiveActivePointBoxReward:                 # 6205 领取活跃点宝箱奖励
                return TaskProc::receiveActivePointBoxReward();
            default:
                Err(ErrCode::cmd_err);
        }
    }

    /**
     *  6205 领取活跃点宝箱奖励
     */
    public static function receiveActivePointBoxReward() {
        list($type, $typeId) = req()->paras;

        $point = 0;
        switch ($type) {
            case Enum_ActiveTaskType::Day7:
                $point = ctx()->task->day7Point;
                break;
            case Enum_ActiveTaskType::DailyTask:
                $point = ctx()->task->dailyTaskPoint;
                break;
            case Enum_ActiveTaskType::WeekTask:
                $point = ctx()->task->weekTaskPoint;
                break;
            default:
                break;
        }

        my_Assert($point >= $typeId, ErrCode::task_CanotPriceReviced);

        $mo = GameConfig::activepointreward_getItem($type, $typeId);
        my_Assert($mo != null, ErrCode::err_const_no);
                           
        StoreProc::AddMultiItemInStore($mo->reward);
        
        $strId = $type . "-" . $typeId;      
        my_Assert(!in_array($strId, ctx()->task->activePointReceived), ErrCode::task_CanotPriceReviced);
        ctx()->task->activePointReceived[] = $strId;

        UserProc::updateUserInfo();
        return Resp::ok(array("task" => ctx()->task,
                    "store" => ctx()->store,
                    "reward" => StoreProc::$reward,
        ));
    }

    /**
     * 6204 领取活动任务奖励
     * @return type
     */
    public static function receiveActiveTaskReward() {
        list($uid) = req()->paras;

        my_Assert(StlUtil::dictHasProperty(ctx()->task->activeTaskInfo, $uid), ErrCode::task_NoExist);

        $ins_activeTaskInfo = new Ins_TaskStep_Active(ctx()->task->activeTaskInfo->$uid);
        my_Assert($ins_activeTaskInfo->cur >= $ins_activeTaskInfo->max(), ErrCode::task_CanotPriceReviced);
        my_Assert($ins_activeTaskInfo->state == Enum_TaskCardStateType::finish, ErrCode::task_CanotPriceReviced);

        if($ins_activeTaskInfo->mo()->prizes != null){
            $reward = explode(',', $ins_activeTaskInfo->mo()->prizes);
            if(GameConfig::item_getItem($reward[0])->itemType == 201){
                SystemProc::GetGem_GreaterOrangeQual_Active(req()->zoneid, ctx()->baseInfo->name, $reward[0]);
            }
            
        }
        
        StoreProc::AddMultiItemInStore($ins_activeTaskInfo->mo()->prizes);
        ctx()->task->activeTaskInfo->$uid->state = Enum_TaskCardStateType::drawed;
        ctx()->task->activeTaskInfo->$uid->drawTs = now();

        $activePointArr = explode(',', $ins_activeTaskInfo->mo()->activePoint);
        switch ($ins_activeTaskInfo->mo()->type) {
            case Enum_ActiveTaskType::Day7:
                ctx()->task->day7Point += $activePointArr[1];
                break;
            case Enum_ActiveTaskType::DailyTask:
                ctx()->task->dailyTaskPoint += $activePointArr[1];
                break;
            case Enum_ActiveTaskType::WeekTask:
                ctx()->task->weekTaskPoint += $activePointArr[1];
                break;
            default:
                break;
        }

        StoreProc::$reward[] = $ins_activeTaskInfo->mo()->activePoint;
                
        UserProc::updateUserInfo();
        return Resp::ok(array("task" => ctx()->task,
                    "store" => ctx()->store,
                    'reward' => StoreProc::$reward,
                    'cash'=>ctx()->baseInfo->cash,
        ));
    }

    /**
     * 6203 领取成就奖励
     * @return type
     */
    public static function getAchieveReward() {
        list($typeId) = req()->paras;

        $mo = GameConfig::achieve_getItem($typeId);
        my_Assert($mo != null, ErrCode::err_const_no);

        my_Assert(StlUtil::dictHasProperty(ctx()->task->achieveDic, $typeId), ErrCode::err_const_no);
        $achieveDic = ctx()->task->achieveDic->$typeId;

        $list = explode(',', $mo->condition);
        $length = count($list);
        my_Assert($achieveDic->val >= $achieveDic->max, ErrCode::task_CanotPriceReviced);
        my_Assert($achieveDic->received < $achieveDic->max, ErrCode::task_PriceRepeatReviced);

        $index = 0;
        foreach ($list as $k => $num) {
            if ($num == $achieveDic->max) {
                $index = $k;
                break;
            }
        }
        //领取奖励
        $pList = explode(';', $mo->reward);
        StoreProc::AddMultiItemInStore($pList[$index]);

        //下一个max    
        if ($index + 1 < $length) {
            $achieveDic->max = $list[$index + 1];
        }
        ctx()->task->achieveDic->$typeId = $achieveDic;

        UserProc::updateUserInfo();
        return Resp::ok(array(
                    "achieve" => ctx()->task->achieveDic,
                    "cash" => ctx()->baseInfo->cash,
        ));
    }

    /**
     * 初始化成就信息
     */
    public static function initAchieveData() {
//        $dic = GameConfig::achieve_new();
//        if($dic == null){
//            return;
//        }
//        
//        $achieveDic = ctx()->task->achieveDic;
//        if(count((array)$achieveDic) > 0){
//            return;
//        }
//        
//        foreach ($dic as $key => $value) {
//            $item = new Ins_Achieve();
//            $typeId = $value->typeId;
//            $item->typeId = $typeId;
//            $item->cmd = $value->cmd;
//            //$item->max = explode(',', $value->condition)[0];
//            $item->max = $value->num;
//            $achieveDic->$typeId = $item;
//        }
//        ctx()->task->achieveDic = $achieveDic;
    }

    //检测成就条件
    public static function CheckAchieveConditions($arg) {
        $achieveDic = ctx()->task->achieveDic;
        foreach ($achieveDic as $key => $value) {
            $achieve = new Ins_Achieve($value);
            $tag = false;
            if ($achieve->cmd == $arg->taskType) {
                $mo = $achieve->getAchieveMo();
                if ($mo->paras == $arg->paras[0]) {//暂定，若有多个参数，在进行解析
                    $tag = true;
                }
            }

            if ($tag) {//找到正确数据
                switch ($arg->ope) {
                    case Enum_PropelType::set:
                        $achieve->val = $arg->val;
                        break;
                    case Enum_PropelType::add:
                        $achieve->val += $arg->val;
                        break;
                    default:
                        break;
                }
            }
        }

        ctx()->task->achieveDic = $achieveDic;
        UserProc::updateUserInfo();
    }

    //-------------------成就条件检测
    //单件装备等级达到X级
    static function accumulateEquiplevel_one($lv) {
        $taskEventArg = new Ins_TaskEventArgs(Enum_AchieveType::equiplevel_one, Enum_PropelType::set, $lv, array());
        //self::CheckAchieveConditions($taskEventArg);                
    }

    //累计消耗X钻石
    static function accumulateCostCash($num) {
        $taskEventArg = new Ins_TaskEventArgs(Enum_AchieveType::accumulateCostCash, Enum_PropelType::add, $num, array());
        //self::CheckAchieveConditions($taskEventArg);                           
    }

    //------------------------------------------------------

    public static function getTaskInfo() {
        list($type) = req()->paras; //武器uid

        return Resp::ok(array("task" => ctx()->task,
        ));
    }

    static function ResetTask() {
        //self::ResetTask_Daily();
        self::DailyTaskReset();
        self::ClearDay7Task();
        $week = date("w");
        if ($week == 1) {//每周一 第一次登录的时候刷新
            //self::ResetTask_Week();
            self::WeekTaskReset();
        }
    }

    static function ClearDay7Task() {
        if (ctx()->task->day7_startTs > 0) {
            $startDay = TimeUtil::totalDays(ctx()->task->day7_startTs);
            $endDay = $startDay + 6;
            if (TimeUtil::totalDays() > $endDay) {
                self::ClearActiveTask(Enum_ActiveTaskType::Day7);
            }
        }
    }

    /**
     * 7日狂欢数据重置
     */
    public static function Day7TaskReset($gateId) {
        if ($gateId != glc()->GateUnlock_7DayActive) {
            return;
        }

        if (ctx()->task->day7_startTs == 0) {
            $tag = true;
            foreach (ctx()->task->activeTaskInfo as $uid => $val) {
                $taskMo = GameConfig::activeTask_getItem($val->typeId);
                if ($taskMo->type == 1) {
                    $tag = false;
                    break;
                }
            }

            if ($tag) {//7日的数据初始化
                self::initActiveTask(Enum_ActiveTaskType::Day7);
                self::autoRecoverState_activeTask();
                ctx()->task->day7Point = 0;
                ctx()->task->day7_startTs = now();
            }
        }
    }

    static function ClearActiveTask($type) {
        $arr = array();
        foreach (ctx()->task->activeTaskInfo as $uid => $val) {
            $taskMo = GameConfig::activeTask_getItem($val->typeId);
            if ($taskMo->type == $type) {
                $arr[] = $uid;
            }
        }
        if (count($arr) > 0) {
            foreach ($arr as $uid) {
                StlUtil::dictRemove(ctx()->task->activeTaskInfo, $uid);
            }
        }
    }

    static function initActiveTask($type) {
        $day7List = GameConfig::activeTask_type_getItemArray($type);
        $length = ctx()->task->activeTaskLength;
        foreach ($day7List as $key => $task) {
            $length += 1;
            $ins_TaskStep_Active = new Ins_TaskStep_Active($task->id);
            $ins_TaskStep_Active->uid = $length;
            $ins_TaskStep_Active->state = Enum_TaskCardStateType::ing;
            ctx()->task->activeTaskInfo->$length = $ins_TaskStep_Active;
        }
        ctx()->task->activeTaskLength = $length;
    }
  
    /**
     * 日常
     */
    static function DailyTaskReset() {
        self::ClearActiveTask(Enum_ActiveTaskType::DailyTask);
        self::initActiveTask(Enum_ActiveTaskType::DailyTask);
        self::autoRecoverState_activeTask();
        ctx()->task->dailyTaskPoint = 0;
    }

    /**
     * 周常
     */
    static function WeekTaskReset() {
        self::ClearActiveTask(Enum_ActiveTaskType::WeekTask);
        self::initActiveTask(Enum_ActiveTaskType::WeekTask);

        self::autoRecoverState_activeTask();
        ctx()->task->weekTaskPoint = 0;
    }

// <editor-fold defaultstate="collapsed" desc="不同活动任务监测信息-">

    /**
     * 登录
     */
    static function OnLogin_Daily() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::DailyLogin, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 登录第X天
     */
    static function OnLogin_day7() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::OnLogin_X, Enum_PropelType::set, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 通关第X关
     */
    static function OnPassGate_X($gateId) {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::PassGate_X, Enum_PropelType::add, 1, array($gateId));
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 参与主线关卡1次
     */
    static function OnFightNumMainGate() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::FightNumMainGate, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 参与挑战副本1次
     */
    static function OnFightNumChallengeGate() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::FightNumChallengeGate, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 参与竞速副本1次
     */
    static function OnFightNumRaceGate() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::FightNumRaceGate, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 通关竞速副本5次
     */
    static function OnPassNumRaceGate() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::PassNumRaceGate, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 完成5次启灵	
     */
    static function OnCompleteNumQiLing() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::CompleteNumQiLing, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 完成1次关键启灵
     */
    static function OnCompleteNumSpecialQiLing() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::CompleteNumSpecialQiLing, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 镶嵌3个普通品质以上宝石 	
     */
    static function OnSetSpecialQualGem() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::SetSpecialQualGem, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 合成宝石2次
     */
    static function OnComposeNumGem() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::ComposeNumGem, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 任意1个法术等级达到2  
     */
    static function OnAnySkillUpLevel_X() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::AnySkillUpLevel_X, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 任意1件装备等级达到2     
     */
    static function OnAnyEquipUpLevel_X() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::AnyEquipUpLevel_X, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 全身装备等级达到3级以上  
     */
    static function OnAllEquipUpLevel_X() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::AllEquipUpLevel_X, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 任意装备等级升级1次    
     */
    static function OnEquipLevelUpNum() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::EquipLevelUpNum, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 击败怪物总数达到1000   
     */
    static function OnKillCommonNumMonster($num) {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::KillCommonNumMonster, Enum_PropelType::add, $num, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 击败领袖怪物总数达到1000   
     */
    static function OnKillleaderNumMonster($num) {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::KillleaderNumMonster, Enum_PropelType::add, $num, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 累计获取10000金币    
     */
    static function OnAccumulateGoldNum($num) {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::AccumulateGoldNum, Enum_PropelType::add, $num, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 累计获取10000体力    
     */
    static function OnAccumulateTiliNum($num) {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::AccumulateTiliNum, Enum_PropelType::add, $num, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 累计消耗10000钻石  
     */
    static function OnConsumeCashNum($num) {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::ConsumeCashNum, Enum_PropelType::add, $num, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 开启1次璀璨宝石箱
     */
    static function OnOpenNumBrightBox($boxId, $num) {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::OpenNumBrightBox, Enum_PropelType::add, $num, array($boxId));
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 每日商店购买物品1次    
     */
    static function OnBuyNumDailyShop() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::BuyNumDailyShop, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 开任意宝箱X次
     */
    static function OnOpenNumAnyBox($num) {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::OpenNumAnyBox, Enum_PropelType::add, $num, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 购买或观看广告获得体力X次
     */
    static function OnBuyTiliOrLookGuanggao() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::BuyTiliOrLookGuanggao, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

    /**
     * 任意充值X次
     */
    static function OnRecharge() {
        $taskEventArg = new Ins_TaskEventArgs(Enum_ActiveTaskCmdType::Recharge, Enum_PropelType::add, 1, array());
        self::CheckActiveTaskConditions($taskEventArg);
    }

// </editor-fold>
//
// <editor-fold defaultstate="collapsed" desc="活动任务是否完成的检测-">

    /**
     * 检测任务是否完成 
     * @param Ins_TaskEventArgs $taskParam
     */
    static function CheckActiveTaskConditions($taskParam) {
        $activeTaskDic = ctx()->task->activeTaskInfo;
        foreach ($activeTaskDic as $uid => &$task) {
            $ins_TaskStep_Active = new Ins_TaskStep_Active($task);
            if ($ins_TaskStep_Active->state > Enum_TaskCardStateType::ing) {
                continue;
            }

            if ($ins_TaskStep_Active->mo()->cmd == $taskParam->taskType) {
                if ($ins_TaskStep_Active->isStatusType()) {//校验状态类的
                    $cur = $ins_TaskStep_Active->calcStatusCur();
                    if ($cur != $ins_TaskStep_Active->cur) {
                        $ins_TaskStep_Active->cur = $cur;
                        if ($ins_TaskStep_Active->cur >= $ins_TaskStep_Active->max()) {
                            $ins_TaskStep_Active->cur = $ins_TaskStep_Active->max();
                        }
                    }
                } else {
                    $tag = true;
                    if ($ins_TaskStep_Active->mo()->cmd == Enum_ActiveTaskCmdType::AnySkillUpLevel_X && count($taskParam->paras) > 0 && $ins_TaskStep_Active->mo()->paras != null) {
                        $parasArr = $taskParam->paras;
                        $lvArr = explode(',', $ins_TaskStep_Active->mo()->paras);
                        $needLv = $lvArr[0];
                        $num = 0;
                        foreach ($parasArr as $lv) {
                            if ($lv > $needLv) {
                                $num += 1;
                            }
                        }
                        $ins_TaskStep_Active->cur = $num;
                        if ($ins_TaskStep_Active->cur >= $ins_TaskStep_Active->max()) {
                            $ins_TaskStep_Active->cur = $ins_TaskStep_Active->max();
                        }
                        $tag = false;
                    } else {
                        if ($ins_TaskStep_Active->mo()->paras != null) {
                            $parasArr = $taskParam->paras;
                            if (count($parasArr) > 0) {
                                $arr = explode(',', $ins_TaskStep_Active->mo()->paras);
                                $index = 0;
                                foreach ($arr as $s) {
                                    if ($s != $parasArr[$index]) {
                                        $tag = false;
                                        break;
                                    }
                                    $index += 1;
                                }
                            } else {
                                $tag = false;
                            }
                        }

                        if ($tag) {
                            $ins_TaskStep_Active->propel($taskParam);
                            if ($ins_TaskStep_Active->cur >= $ins_TaskStep_Active->max()) {
                                $ins_TaskStep_Active->cur = $ins_TaskStep_Active->max();
                            }
                        }
                    }
                }

                if ($ins_TaskStep_Active->isFinish()) {
                    $ins_TaskStep_Active->state = Enum_TaskCardStateType::finish;
                }

                ctx()->task->activeTaskInfo->$uid = $ins_TaskStep_Active;
            }
        }

        //ctx()->task->activeTaskInfo = $activeTaskDic;
        UserProc::updateUserInfo();                                             # 更新玩家数据
    }

    /**
     * 自动修复状态型任务
     */
    static function autoRecoverState_activeTask() {
        $activeTaskDic = ctx()->task->activeTaskInfo;
        foreach ($activeTaskDic as $uid => &$task) {
            $ins_TaskStep_Active = new Ins_TaskStep_Active($task);
            if ($ins_TaskStep_Active->state > Enum_TaskCardStateType::ing) {
                continue;
            }
            if ($ins_TaskStep_Active->isStatusType()) {
                $cur = $ins_TaskStep_Active->calcStatusCur();
                if ($cur != $ins_TaskStep_Active->cur) {
                    $ins_TaskStep_Active->cur = $cur;
                    if ($ins_TaskStep_Active->cur >= $ins_TaskStep_Active->max()) {
                        $ins_TaskStep_Active->cur = $ins_TaskStep_Active->max();
                    }
                }
            }

            if ($ins_TaskStep_Active->isFinish()) {
                $ins_TaskStep_Active->state = Enum_TaskCardStateType::finish;
            }

            ctx()->task->activeTaskInfo->$uid = $ins_TaskStep_Active;
        }

        UserProc::updateUserInfo();                                             # 更新玩家数据
    }

// </editor-fold>
//    
}
