<?php

namespace loyalsoft;

/**
 * 任务模块
 * @version
 *          1.0.0 Created at 2017-11-3. by --gwang
 * @author gwang (mail@wanggangzero.cn)
 * @copyright ? 2017-11-3, SJZ LoyalSoft Corporation & gwang. All rights reserved.
 */
class TaskProc {

    /**
     * 任务卡-同时激活数量上限
     */
    const TaskCard_ActiveMax = 9;

    /**
     * 任务卡商店-刷新数量
     */
    const TaskCardShop_Refresh_ItemNum = 5;

    static function procMain() {
        switch (req()->cmd) {
            case CmdCode::cmd_task_getInfo:                                     # 6201 刷新任务状态
                return TaskProc::GetTaskInfo();
            case CmdCode::cmd_task_getReward:                                   # 6202 领取任务奖励
                return TaskProc::GetTaskReward();
            case CmdCode::cmd_Task_setAttentionTask:                            # 6203 设置关注任务
                return TaskProc::setAttentionTask();
            case CmdCode::cmd_Task_getActiveReward:                             # 6204 领取日常任务活跃度阶段奖励
                return TaskProc::getActiveReward();
//---------------- 任务卡相关通讯 -----------------------------------------------
            case CmdCode::cmd_taskCard_PlotFinish:                              # 6210 任务卡剧情对话
                return self::PlotFinish();
//            case CmdCode::cmd_taskCard_PlotExchangeTaskCard:                    # 6211 任务卡兑换奖励
//                Err(ErrCode::err_method_obsoleted);
//                return self::PlotExchangeTaskCard($req);
//            case CmdCode::cmd_taskCard_PlotPresentTaskCard:                     # 6212 剧情赠送任务卡
//                Err(ErrCode::err_method_obsoleted);
//                return self::PlotPresetTaskCard($req);
//            case CmdCode::cmd_taskCard_FinishAndReward:                         # 6213 任务卡完成,并即时结算
//                Err(ErrCode::err_method_obsoleted);
//                return self::ImmetRewardTaskCard($req);

            case CmdCode::cmd_taskCard_onKillMonster:                           # 6214 杀死怪物事件
                return self::OnKillMonsterEvent();

            case CmdCode::cmd_taskCard_active:                                  # 6215 激活任务卡
                return self::OnTaskCard_active();
            case CmdCode::cmd_taskCard_reward:                                  # 6216 领取任务卡奖励
                return self::OnTaskCard_reward();
            case CmdCode::cmd_taskCard_info:                                    # 6217 任务卡 - 更新信息
                return self::OnTaskCard_GetInfo();
            case CmdCode::cmd_taskCard_StepActionDone:                          # 6218 任务步骤 - start/finish action done
                return self::OnTaskCard_StepActionDone();
// --------------   任务卡商城 -----------------------------                
            case CmdCode::cmd_taskcard_shop_open:                               # 6231 任务卡商店 - 开启
                return self::OnTaskCardShopOpen();
            case CmdCode::cmd_taskcard_shop_buy:                                # 6232 任务卡商店 - 购买
                return self::OnTaskCardShopBuy();
            case CmdCode::cmd_taskcard_shop_refresh:                            # 6233 任务卡商店 - 手动刷新
                return self::OnTaskCardShopRefresh();
            default:
                return Err(ErrCode::cmd_err);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="  任务卡商店">

    /**
     * [6231] 任务卡商店 - 开启
     */
    static function OnTaskCardShopOpen() {
        $userInfo = req()->userInfo->game;
        if (null == $userInfo->taskCardShop) {                                  # 防御
            $userInfo->taskCardShop = new Info_TaskCard_Shop();
        }
        if (null == $userInfo->taskCardShop->curCards || count($userInfo->taskCardShop->curCards) < 1) {
            $arr = (array) GameConfig::taskcard_shop();                         # 奖池配置
            $arr = self::FilterPrizepool($arr);                           # 利用玩家等级进行过滤
            $reward = ArrayInit();
            $err = self::Dice($arr, self::TaskCardShop_Refresh_ItemNum, $reward);  # 获得随机结果
            my_Assert(ErrCode::ok == $err, $err);
            $userInfo->taskCardShop->curCards = $reward;                        # 更新任务卡列表
            $userInfo->taskCardShop->selled = array();
            req()->userInfo->game = $userInfo;
            UserProc::updateUserInfo();                                         # 回写玩家数据 
        }
        return Resp::ok(array('taskCardShop' => $userInfo->taskCardShop));      # 返回最新任务卡列表
    }

    /**
     * [6232] 任务卡商店 - 购买
     */
    static function OnTaskCardShopBuy() {
        list($typeId, $num) = req()->paras;                                      # 提取参数: 任务卡类型ID,数量(暂时默认为1)
        $shopItemMo = GameConfig::taskcard_shop_getItem($typeId);
        my_Assert(null != $shopItemMo, ErrCode::err_const_no);                  # 常量异常
        my_Assert($num == 1, ErrCode::paras_err);                               # 数量异常
        $userInfo = req()->userInfo->game;
        $userInfo->taskCardShop = new Info_TaskCard_Shop($userInfo->taskCardShop);
        my_Assert(!in_array($typeId, $userInfo->taskCardShop->selled), ErrCode::taskCard_selled);
        switch ($shopItemMo->pricetype) {
            case 0:                                    # 人民币
                Err(ErrCode::err_method_notimplement);
//                my_Assert(Data_UserGame::Consume_Cash($userInfo->baseInfo, $shopItemMo->price), ErrCode::notenough_cash_msg); # 扣除费用
                break;
            case 1:                                    # 钻石
                my_Assert($userInfo->base()->Consume_Cash($shopItemMo->price), ErrCode::notenough_cash_msg); # 扣除费用
                break;
            case 2:                                    # 金币
                my_Assert($userInfo->base()->Consume_Gold($shopItemMo->price), ErrCode::notenough_gold_msg); # 扣除费用
                break;
            default:                                   # 其它
                Err(ErrCode::pay_m_type_err);                                   # 定价类型异常
                break;
        }

        $cid = StoreProc::PutTaskCardInStore($typeId);                          # 添加任务卡到背包
        $userInfo->taskCardShop->selled[] = $typeId;                            # 添加售罄记录
        UserProc::updateUserInfo();

        self::OnBuyTaskCard($num);                                              # 监控购买任务卡的任务卡[・_・?]
        return Resp::ok(array(
                    'gold' => req()->userInfo->game->baseInfo->gold,
                    'cash' => req()->userInfo->game->baseInfo->cash,
                    'store' => req()->userInfo->game->store));                   # 返回成功
    }

    /**
     * [6233] 任务卡商店 - 手动刷新
     */
    public static function OnTaskCardShopRefresh() {
        $cost = GameConfig::globalsettings()->TaskCardShop_Refresh_Cash;        # 消耗
        $userInfo = req()->userInfo->game;
//        var_dump(Data_UserGame::Consume_Cash($userInfo->baseInfo, $cost));
        my_Assert($userInfo->base()->Consume_Cash($cost), ErrCode::notenough_cash_msg); # 扣除费用
        // 刷新任务卡
        $arr = (array) GameConfig::taskcard_shop();                             # 奖池配置
        $arr = self::FilterPrizepool($arr);                               # 利用玩家等级进行过滤
        $reward = ArrayInit();
        $err = self::Dice($arr, self::TaskCardShop_Refresh_ItemNum, $reward);   # 获得随机结果
        my_Assert(ErrCode::ok == $err, $err);
//        if (null == $userInfo->taskCardShop) {                                  # 防御
        $userInfo->taskCardShop = new Info_TaskCard_Shop($userInfo->taskCardShop);
//        }
        $userInfo->taskCardShop->curCards = $reward;                            # 更新任务卡列表
        $userInfo->taskCardShop->selled = array();
        req()->userInfo->game = $userInfo;
        UserProc::updateUserInfo();                                             # 回写玩家数据 
        return Resp::ok(array(
                    'gold' => req()->userInfo->game->baseInfo->gold,
                    'cash' => req()->userInfo->game->baseInfo->cash,
                    'taskCardShop' => $userInfo->taskCardShop));                # 返回最新任务卡列表
    }

    /**
     * 过滤奖池 
     * @param array $arr 奖池
     */
    static function FilterPrizepool($arr) {
        $ret = array_filter($arr, function ($value) {
            return(req()->userInfo->game->baseInfo->level >= $value->unlock_level); # 等级限制
        });
        return $ret;
    }

    /**
     * 投骰子
     * @param assoc_array $arr 抽奖物品概率
     * @param int $number 连抽次数
     * @return array[] itemids
     */
    static function Dice($arr, $number, &$reward) {
        $max = 0;                                                               # 计算物品权重总和
        array_walk($arr, function ($value) use (&$max) {
            $max += $value->probability;
        });
        my_Assert($max > 0, ErrCode::err_const_no);                             # 配置数据有问题
        $reward = ArrayInit();
        for ($i = 0; $i < $number;) {
            $rnd = CommUtil::random(1, $max);                                   # 投骰子
            $start = 0;
            $rew = null;
            foreach ($arr as $item) {                                           # 循环判断落入那个物品上
                if ($start < $rnd && $rnd <= $start + $item->probability) {     # 落入区间
                    $rew = $item;                                               # 记录物品
                    break;
                }
                $start += $item->probability;                                   # 继续判断是否落入下一物品的区间
            } # foreach end
            if (!$rew) {
                return ErrCode::lottery_noselecteditem;
            }
            if (!in_array($rew->typeId, $reward)) {                             # 去除重复卡
                $reward[] = $rew->typeId;
                $i++;
            }
        } # for end 
        return ErrCode::ok;
    }

    // 
// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="  任务卡接口">
    // 

    /**
     * [6210]剧情对话-触发任务卡结束条件检测(中间某个step结束,进入下一个step)
     */
    static function PlotFinish() {
        list($gate_or_npc_id, $stage) = req()->paras;
        $bUpdate = self::OnPlotOver($gate_or_npc_id, $stage);                   # 触发一下任务检查,更新任务状态
        $arr = GameConfig::plot_getItem($gate_or_npc_id, $stage);               # 查找对应的剧情
        my_Assert(isset($arr), ErrCode::err_const_no);                          # 常量存在
        foreach ($arr as $plot) {
            isEditor() and $plot = new \sm_plot();
            if (!empty($plot->presentItem)) {
                if (strtolower($plot->presentItem) == strtolower("unlockBuild")) { # 特殊处理, 剧情中解锁建筑
                    req()->userInfo->game->privateState->unlockedBuild[] = $plot->presentEffect; # 添加解锁记录
                    NormalEventProc::OnUnlockBuild($plot->presentEffect);       # 插入解锁事件
                } else if (strtolower($plot->presentItem) == strtolower("rename")) {# 改名
                    // 跳过特殊字符串
                } else if (strtolower($plot->presentItem) == strtolower("zhaohuanyanling")) {
                    // 跳过特殊指令
                } else {                                                        # 普通奖励
                    StoreProc::AddMultiItemInStore($plot->presentItem);
                }
            }
            if (!empty($plot->recycleItem)) {
                $val = explode(",", $plot->recycleItem);
                my_Assert(count($val) > 1, "解析回收道具字符串出错");
                StoreProc::removeItemFromStore(req()->userInfo->game->store, $val[0], $val[1]);
            }
        }
        UserProc::updateUserInfo();
        return Resp::ok(array('store' => req()->userInfo->game->store,
                    'taskCardUpdate' => $bUpdate));
    }

// <editor-fold defaultstate="collapsed" desc="废弃">
//    /**
//     * [6211] 任务卡-剧情结束兑换奖励(销毁当前卡,换取新的任务卡)
//     * @deprecated since version 2020.12.12
//     * @param type $req
//     */
//    static function PlotExchangeTaskCard($req) {
//        Err(ErrCode::err_method_notimplement);
//    }
//
//
//    /**
//     * [6212] 任务卡- 剧情对话奖励任务卡
//     * @deprecated since version 2020.12.12
//     * @param req $req
//     */
//    static function PlotPresetTaskCard($req) {
//        // 发放任务卡
//        list($rwdStr) = $req->paras;
//        $err = StoreProc::AddMultiItemInStore($req, $rwdStr);
//        my_Assert(ErrCode::ok == $err, $err);
//        UserProc::updateUserInfo();
//        return Resp::ok(array('store' => $req->userInfo->game->store));
//    }
//
//    /**
//     * [6213]任务卡 - 即时奖励型任务卡
//     * @deprecated since version 2020.12.12
//     * @param req $req
//     */
//    static function ImmetRewardTaskCard($req) {
//        // 销毁任务卡, 发放奖励
//        list($taskCardUID) = $req->paras;
//        my_Assert(StlUtil::dictHasProperty($req->userInfo->game->store->taskcards, $taskCardUID), ErrCode::taskCard_no); # 防御
//        $taskCard = new Ins_TaskCard($req->userInfo->game->store->taskcards->$taskCardUID); # 任务卡对象
//        if (strlen($taskCard->mo()->reward) > 0) {                              # 防御奖励串为空
//            StoreProc::AddMultiItemInStore($req, $taskCard->mo()->reward);      # 发放奖励
//        }
//        if (strlen($taskCard->mo()->newTaskCard) > 0) {                         # 防御新卡串为空
//            StoreProc::AddMultiItemInStore($req, $taskCard->mo()->newTaskCard); # 发放新任务卡
//        }
//        StlUtil::dictRemove($req->userInfo->game->store->taskcards, $taskCardUID); # 移除任务卡
//        UserProc::updateUserInfo();                                             # 回存玩家数据
//        return Resp::ok(array('store' => $req->userInfo->game->store, 'taskCardUpdate' => true));         # 返回值更新背包
//    }
// </editor-fold>

    /**
     * [6214] 任务卡 - 杀死怪物事件
     */
    static function OnKillMonsterEvent() {
        // 触发一下任务检查
        list($monsterID, $num) = req()->paras;
        $bUpdate = self::OnKillMonster($monsterID, $num);
        return Resp::ok(array('store' => req()->userInfo->game->store,
                    'taskCardUpdate' => $bUpdate));
    }

    /**
     * [6215] 任务卡 - 激活任务卡
     */
    static function OnTaskCard_active() {
        list($taskCardUID) = req()->paras;                                       # 提取参数: 任务卡实例id
        $store = req()->userInfo->game->store;                                   # 快速访问store
        my_Assert(StlUtil::dictHasProperty($store->taskcards, $taskCardUID), ErrCode::taskCard_no); # 防御找不到实例
        $taskCard = new Ins_TaskCard($store->taskcards->$taskCardUID);          # 任务卡对象

        my_Assert($taskCard->state <= Enum_TaskCardStateType::notopen, ErrCode::taskCard_state); # 任务卡状态异常 
        my_Assert(true != self::FindSameIngCard($taskCard->typeId), ErrCode::taskCard_active_multi); # 不可激活多张任务卡
        my_Assert(self::FindIngCardCount() <= self::TaskCard_ActiveMax, ErrCode::taskCard_active_max); # 激活数量上限
        $taskCard->state = Enum_TaskCardStateType::ing;
        NormalEventProc::OnTaskCard_Actived($taskCardUID, null);                # 带入事件
        foreach ($taskCard->curSteps as &$tsp) {                                # 初期里面只有一个任务
            $tsp = new Ins_TaskStep($tsp);
            if ($tsp->isStatusType()) {                                         # 如果是道具收集类的, 扣除所收集道具
                $tsp->autoCalcStatusCur();
            }
//            $tsp->doStartAct();
        }
        if ($taskCard->IsFinish()) {                                            # 检查是否任务卡的所有步骤都已完成
            $taskCard->state = Enum_TaskCardStateType::finish;
            NormalEventProc::OnTaskCard_Finish($taskCard->uid, null);           # 广播卡完成事件
        }
        $store->taskcards->$taskCardUID = $taskCard;
        UserProc::updateUserInfo();                                             # 回存玩家数据
        return Resp::ok(array('store' => req()->userInfo->game->store));         # 返回值更新背包
    }

    static function FindSameIngCard($typeId) {
        $cardDic = req()->userInfo->game->store->taskcards;
        $find = false;
        array_walk($cardDic, function ($inst) use ($typeId, &$find) {
//             $inst = new Ins_TaskCard($inst); 
            if ($inst->state == Enum_TaskCardStateType::ing && $inst->typeId == $typeId) {
                $find = true;
            }
        });
        return $find;
    }

    static function FindIngCardCount() {
        $cardDic = req()->userInfo->game->store->taskcards;
        $num = 0;
        array_walk($cardDic, function ($inst) use (&$num) {
//             $inst = new Ins_TaskCard($inst); 
            if ($inst->state == Enum_TaskCardStateType::ing) {
                $num++;
            }
        });
        return $num;
    }

    /**
     * [6216] 任务卡 - 领取任务卡奖励 
     */
    static function OnTaskCard_reward() {
        // 销毁任务卡, 发放奖励
        list($taskCardUID) = req()->paras;
        $store = ctx()->store();                                   # 快速访问store
        my_Assert(StlUtil::dictHasProperty($store->taskcards, $taskCardUID), ErrCode::taskCard_no); # 防御找不到实例
        $taskCard = new Ins_TaskCard($store->taskcards->$taskCardUID);          # 任务卡对象
//  

        foreach ($taskCard->curSteps as &$tsp) {                                # 初期里面只有一个任务
            $tsp = new Ins_TaskStep($tsp);
            if ($tsp->mo()->cmd == Enum_TaskCmdType::GainItem) {                # 如果是道具收集类的, 扣除所收集道具
                $ok = StoreProc::removeItemFromStore($store, $tsp->mo()->paras, $tsp->mo()->num);
                my_Assert(ErrCode::ok == $ok, ErrCode::taskCard_gainItem_no);
            }
        }
        if (strlen($taskCard->mo()->reward) > 0) {                              # 防御奖励串为空
            StoreProc::AddMultiItemInStore($taskCard->mo()->reward);            # 发放奖励
        }
        if ($taskCard->mo()->exp > 0) {                                         # 任务卡增加了指挥官经验
            req()->userInfo->game->base()->Add_Exp($taskCard->mo()->exp);       # 加指挥官经验
        }
        $taskCard->state = Enum_TaskCardStateType::drawed;
        //2021-3-4
        $college = ctx()->college();
        $college->modifyTaskCardState($taskCard->typeId, Enum_TaskCardStateType::drawed);

        $store->taskcards->$taskCardUID = $taskCard;                            # 回写任务数据
        NormalEventProc::OnTaskCard_Reward($taskCard->mo()->reward, null);      # 带入事件
        self::OnFinishTaskCard();                                               # 触发检查任务卡的任务卡[・_・?]
        if (!empty($taskCard->mo()->newTaskCard)) {                             # 下一个任务卡存在  
            StoreProc::PutTaskCardInStore($taskCard->mo()->newTaskCard);        # 放卡入背包
        }
        StlUtil::dictRemove($store->taskcards, $taskCardUID);                   # 移除任务卡   
        self::autoRecoverStateMissions();                                       # 重新更新其它状态类的任务卡
        UserProc::updateUserInfo();                                             # 回存玩家数据
        return Resp::ok(array(
                    'gold' => req()->userInfo->game->baseInfo->gold,
                    'cash' => req()->userInfo->game->baseInfo->cash,
                    'store' => req()->userInfo->game->store,
                    'college' => req()->userInfo->game->college,));                   # 返回值更新背包
    }

    /**
     * [6217] 任务卡 - 更新信息
     */
    static function OnTaskCard_GetInfo() {
        return Resp::ok(array('store' => req()->userInfo->game->store));         # 返回值更新背包
    }

    /**
     * [6218] 任务步骤 - start/finish Action done
     */
    static function OnTaskCard_StepActionDone() {
        list($taskCardUID, $stepTypeId, $actType) = req()->paras;                # 参数提取,卡uid,步骤类型id,actType: 1:start,2:finish.
        $store = req()->userInfo->game->store;                                   # 快速访问store
        my_Assert(StlUtil::dictHasProperty($store->taskcards, $taskCardUID), ErrCode::taskCard_no); # 防御找不到实例
        $taskCard = new Ins_TaskCard($store->taskcards->$taskCardUID);          # 任务卡对象

        foreach ($taskCard->curSteps as &$tsp) {                                # 初期里面只有一个任务
            $tsp = new Ins_TaskStep($tsp);
            if ($tsp->typeId == $stepTypeId) {                                  # 找到指定步骤
                if ($actType == 1) {
                    $tsp->doStartAct();
                } else if ($actType == 2) {
                    $tsp->doFinishAct();
                }
            }
        }
        UserProc::updateUserInfo();
        return Resp::ok(array('store' => req()->userInfo->game->store));         # 返回值更新背包
    }

    // 
// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="  任务接口 ">

    /**
     * [6204] 领取日常任务活跃度阶段奖励
     */
    static function getActiveReward() {
        list($num) = req()->paras;                                               # 提取参数: 领奖的阶段
        $userTask = req()->userInfo->game->task;
        $rewardCfg = GameConfig::task_active_reward_getItem($num);              # 查找奖励配置
        my_Assert(null != $rewardCfg, ErrCode::err_const_no);                   # 防御: 常量丢失
        my_Assert(!in_array($num, $userTask->dailyActiveGetedRewardArr), ErrCode::task_reward_geted); # 判断尚未领取
        my_Assert($userTask->dailyActivePoint >= $num, ErrCode::task_activePoint_notenough);          # 判断活跃点数足够
        $ok = StoreProc::AddMultiItemInStore($rewardCfg->reward);         # 按照配置发放奖励
        my_Assert($ok == ErrCode::ok, $ok);                                     # 发放成功
        $userTask->dailyActiveGetedRewardArr[] = $num;                          # 添加领取记录
        UserProc::updateUserInfo();                                             # 回存数据
        return Resp::ok(array(//                                                # 返回
                    "gold" => req()->userInfo->game->baseInfo->gold,
                    "cash" => req()->userInfo->game->baseInfo->cash,
                    "tili" => req()->userInfo->game->baseInfo->tili,
                    "store" => req()->userInfo->game->store,
                    "task" => req()->userInfo->game->task
        ));
    }

    /**
     * [6203] 设置关注任务
     */
    static function setAttentionTask() {
        list($taskId) = req()->paras;
        $userTask = req()->userInfo->game->task;

        my_Assert(StlUtil::dictHasProperty($userTask->taskListPlot, $taskId), ErrCode::task_no); # 任务存在
        $taskItem = new Ins_TaskInfo($userTask->taskListPlot->$taskId);
        my_Assert($taskItem->rewardGeted < 1, ErrCode::task_reward_geted);      # 任务奖励尚未领取
        $userTask->curTaskId = $taskId;
//        var_dump($userTask);
        UserProc::updateUserInfo();
        return Resp::ok(array("task" => req()->userInfo->game->task));
    }

    /**
     * [6202]领取任务奖励 问:每日任务奖励和剧情任务奖励领取接口是否为一个? 
     */
    static function GetTaskReward() {
        list($taskId) = req()->paras;                                            # 提取参数: 任务id
        $userTask = new Info_UserTask(req()->userInfo->game->task);
        $mask = 100000;                                                         # 根据id段来区分任务和每日任务.
        $type = intval($taskId / $mask);                                        # 取出taskId第一位判断任务类型
        switch ($type) {                                                        # 
            case 4:                                                             # 剧情任务
                my_Assert(StlUtil::dictHasProperty($userTask->taskListPlot, $taskId), ErrCode::task_no); #判断是否存在指定任务
                $task = new Ins_TaskInfo($userTask->taskListPlot->$taskId);
                my_Assert($task->progress >= 1, ErrCode::task_progress_not_complete);   # 判断任务进度是否已完成>=1f
                my_Assert($task->rewardGeted < 1, ErrCode::task_reward_geted);          # 奖励不可重复领取
                $taskCfg = GameConfig::task_getItem($taskId);                           # 任务配置数据
                my_Assert($taskCfg != null, ErrCode::err_const_no);
                $ok = StoreProc::AddMultiItemInStore($taskCfg->reward);           # 发放任务奖励
                my_Assert($ok == ErrCode::ok, $ok);
                $task->rewardGeted = 1;
                $userTask->taskListPlot->$taskId = $task;
                if ($userTask->IsAllPlotTaskOver()) {                           # 检查当前节点任务是否已经全部清空
                    $userTask->curTaskNode += 1;
                    $userTask->taskListPlot = ObjectInit();
                    $userTask->initialize();
                }
                break;
            case 5:                                                             # 每日任务
                my_Assert(StlUtil::dictHasProperty($userTask->taskListDaily, $taskId), ErrCode::task_no);
                $task = new Ins_TaskInfo($userTask->taskListDaily->$taskId);
                my_Assert($task->progress >= 1, ErrCode::task_progress_not_complete);   # 判断任务进度是否已完成>=1f
                my_Assert($task->rewardGeted < 1, ErrCode::task_reward_geted);          # 奖励不可重复领取
                $taskCfg = GameConfig::task_daily_getItem($taskId);                     # 任务配置数据
                my_Assert($taskCfg != null, ErrCode::err_const_no);
//                Data_UserGame::Add_Exp(req()->userInfo->game->baseInfo, $taskCfg->exp);  # 发放任务奖励 
                req()->userInfo->game->base()->Add_Exp($taskCfg->exp);          # 发放指挥官经验
                $userTask->dailyActivePoint += $taskCfg->activePoint;
                $task->rewardGeted = 1;
                $userTask->taskListDaily->$taskId = $task;                      # 回存下
                break;
            default:
                break;
        }

        req()->userInfo->game->task = $userTask;                                 # 回存 
        UserProc::updateUserInfo();
        return Resp::ok(array(//                                                # 返回
                    "gold" => req()->userInfo->game->baseInfo->gold,
                    "cash" => req()->userInfo->game->baseInfo->cash,
                    "tili" => req()->userInfo->game->baseInfo->tili,
                    "store" => req()->userInfo->game->store,
                    "task" => req()->userInfo->game->task
        ));
    }

    /**
     * [6201]更新任务状态 
     */
    static function GetTaskInfo() {
        return Resp::ok(array("task" => req()->userInfo->game->task));
    }

// </editor-fold>

    /**
     * 重置每日任务 
     */
    static function ResetDailyTask() {
        return;
        $userTask = new Info_UserTask(req()->userInfo->game->task);
        $userTask->resetDailyTask();
        req()->userInfo->game->task = $userTask;
    }

// 
    // <editor-fold defaultstate="collapsed" desc="辅助方法-比对判断">

    /**
     * 检查任务条件是否达成
     * @param Ins_TaskParams $taskParam Description
     */
    static function CheckTaskConditions($taskParam) {
        return;
//        var_dump($taskParam);
        $bUpdate = false;
        foreach (req()->userInfo->game->task->taskListPlot as $tid => $task) {
            $taskCfg = GameConfig::task_getItem($tid);
            my_Assert($taskCfg != null, ErrCode::err_const_no);                 # 获取任务配置数据   
            if ($taskCfg->tasktype != $taskParam->taskType) {                   # 任务类型必须匹配
                continue;
            }
            isEditor() and $task = new Ins_TaskInfo(-1);
            if ($task->progress == 1) {                                         # 已完成的不再更新处理
                continue;
            }
            if (is_null($taskCfg->canshu1)) {
                $task->progress = 1;
                $bUpdate = true;
                continue;
            }

            if ($taskCfg->canshu1 == $taskParam->canshu1) {
                $task->tag1 = $taskParam->canshu1;
                if (null == $taskCfg->canshu2 || 0 == $taskCfg->canshu2) {
                    $task->progress = 1;
                    $task->tag2 = $taskParam->canshu2;
                    $bUpdate = true;
                } else {
                    if (is_numeric($taskCfg->canshu2)) {
                        $task->tag2 = max($task->tag2, $taskParam->canshu2);
                        if ($taskCfg->canshu2 <= $taskParam->canshu2) {
                            $bUpdate = true;
                            $task->progress = 1;
                        }
                    } else {
                        $task->tag2 = $taskParam->canshu2;
                        if ($taskCfg->canshu2 == $taskParam->canshu2) {
                            $bUpdate = true;
                            $task->progress = 1;
                        }
                    }
                }
            }
        }
        if ($bUpdate) {
            CornerSignEventProc::OnTask_Plot_new();
        }
    }

    /**
     * 检查任务条件是否达成
     * @param Ins_TaskParams $taskParam Description
     */
    static function CheckDailyTaskConditions($taskParam) {
        return;
        $bUpdate = false;
        $daily = req()->userInfo->game->task->taskListDaily;
        foreach ($daily as $tid => &$task) {
            $taskCfg = GameConfig::task_daily_getItem($tid);
            my_Assert($taskCfg != null, ErrCode::err_const_no);                 # 获取任务配置数据    
            if ($taskCfg->tasktype != $taskParam->taskType) {                   # 任务类型必须匹配
                continue;
            }
            $task = new Ins_TaskInfo($task);
            if ($task->progress >= 1) {                                         # 已完成的不再更新处理
                continue;
            }
            $task->counter++;                                                   # 计数器
            if (is_null($taskCfg->canshu1) || $taskCfg->canshu1 == 0) {
                $task->progress = 1;
                $bUpdate = true;
                continue;
            }
            if ($taskCfg->canshu1 == $task->counter) {
                $task->progress = 1;
                $bUpdate = true;
                continue;
            }
        }

        if ($bUpdate) {
            CornerSignEventProc::OnTask_Daily_new();
        }
    }

// </editor-fold>
// 
    // <editor-fold defaultstate="collapsed" desc="处理各种任务检测事务">
    // 

    /**
     * 例如当指挥官等级提升的时候需要检查是否有任务达成
     */
    static function OnUserLevelUp($newLvl) {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::CommanderLevelUpTo, $newLvl);
        self::CheckTaskConditions($taskParam);

        $taskEventArg = new Ins_TaskEventArgs(Enum_TaskCmdType::CommanderLevelUpTo, Enum_PropelType::set, $newLvl, array($newLvl));
        self::CheckTaskCardConditions($taskEventArg);
    }

    /**
     * 英雄升级
     * @param type $heroMoId
     * @param type $newLvl
     */
    static function OnHeroLevelUp($heroMoId, $newLvl) {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::HeroLevelUpTo, $heroMoId, $newLvl);
        self::CheckTaskConditions($taskParam);
        $taskEventArg = new Ins_TaskEventArgs(Enum_TaskCmdType::HeroLevelUpTo, Enum_PropelType::set, $newLvl, array($heroMoId));
        self::CheckTaskCardConditions($taskEventArg);
    }

    /**
     * 英雄升阶
     * @param type $heroMoId
     * @param type $newGrade
     */
    static function OnHeroGradeUp($heroMoId, $newGrade) {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::HeroGradeUpTo, $heroMoId, $newGrade);
        self::CheckTaskConditions($taskParam);
        self::OnHeroImprove();
    }

    /**
     * 英雄碎片数量达到指定值
     * @param type $heroMoId
     * @param type $num
     */
    static function OnHeroSegmengNum($heroMoId, $num) {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::HeroSegmentNumberTo, $heroMoId, $num);
        self::CheckTaskConditions($taskParam);
    }

    /**
     * 英雄解锁技能
     * @param type $heroMoId
     * @param type $skillId
     */
    static function OnHeroUnlocSkill($heroMoId, $skillId) {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::HeroSkillUnlock, $heroMoId, $skillId);
        self::CheckTaskConditions($taskParam);
    }

    /**
     * 英雄穿上武器
     * @param type $heroMoid
     * @param type $weaponMoId
     */
    static function OnHeroWearWeapon($heroMoid, $weaponMoId) {
        $weapMO = GameConfig::item_base_getItem($weaponMoId);
        my_Assert($weapMO, ErrCode::err_const_no);
        $taskEventArg = new Ins_TaskEventArgs(Enum_TaskCmdType::HeroWearupWeapon_quality, Enum_PropelType::set, 1, array($heroMoid, $weapMO->quality));
        self::CheckTaskCardConditions($taskEventArg);
    }

    /**
     * 英雄装备言灵
     * @param type $heroMoid
     * @param type $weaponMoId
     */
    static function OnHeroWearYanling($heroMoid, $yanlingMoId) {
        $taskEventArg = new Ins_TaskEventArgs(Enum_TaskCmdType::HeroWearupYanling, Enum_PropelType::set, 1, array($heroMoid, $yanlingMoId));
        self::CheckTaskCardConditions($taskEventArg);
    }

    /**
     * 通关剧情关卡
     * @param type $gateId
     * @param type $difficulty
     */
    static function OnPassGateN($gateId, $difficulty) {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::PassGateN, $gateId, $difficulty);
        self::CheckTaskConditions($taskParam);
        self::OnPassGate();
//        var_dump("通关剧情检测 $gateId $difficulty");
        $taskEventArg = new Ins_TaskEventArgs(Enum_TaskCmdType::PassGateN, Enum_PropelType::set, 1, array($gateId, $difficulty));
        self::CheckTaskCardConditions($taskEventArg);
    }

    /**
     * 通关副本关卡
     * @param type $gateId
     * @param type $difficulty
     */
    static function OnPassCarboN($gateId, $difficulty) {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::passCarbonN, $gateId, $difficulty);
        self::CheckTaskConditions($taskParam);
    }

    /**
     * 竞技场胜利场次
     * @param type $num
     */
    static function OnPvPWinN($num) {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::PvPWinNumberTo, $num);
        self::CheckTaskConditions($taskParam);
    }

    /**
     * 竞技场积分
     * @param type $score
     */
    static function OnPvPScoreN($score) {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::PvPScoreTo, $score);
        self::CheckTaskConditions($taskParam);
    }

    /**
     * 玩家总战力值
     * @param type $num
     */
    static function OnUserFightPowerN($num) {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::UserPowerTo, $num);
        self::CheckTaskConditions($taskParam);
    }

    /**
     * 玩家收集积分
     * @param type $num
     */
    static function OnUserCollectScoreN($num) {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::UserCollectScoreTo, $num);
        self::CheckTaskConditions($taskParam);
    }

    // 
// </editor-fold>
    //
    // <editor-fold defaultstate="collapsed" desc="每日任务条件检查">
    // 

    /**
     * 每日登陆
     */
    static function OnUserLogin() {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::DailyLogin);
        self::CheckDailyTaskConditions($taskParam);
    }

    /**
     * 每日:英雄强化(升级或升阶)n次
     */
    static function OnHeroImprove() {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::DailyHeroImprove);
        self::CheckDailyTaskConditions($taskParam);
    }

    /**
     * 每日:剧情关卡,胜利n次
     */
    static function OnPassGate() {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::DailyGatesWin);
        self::CheckDailyTaskConditions($taskParam);
    }

    /**
     * 竞技场每日挑战,胜负均可
     */
    static function OnPvp() {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::DailyPVP);
        self::CheckDailyTaskConditions($taskParam);
    }

    /**
     * 每日挑战,胜负均可
     */
    static function OnRankChalenge() {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::DailyRankChalenge);
        self::CheckDailyTaskConditions($taskParam);
    }

    /**
     * 每日购买商品
     */
    static function OnShopping() {
        $taskParam = new Ins_TaskParams(Enum_TaskCmdType::DailyShopping);
        self::CheckDailyTaskConditions($taskParam);
    }

    // 
// </editor-fold>
    // 
    // <editor-fold defaultstate="collapsed" desc="处理任务卡条件检查">
    // 

    /**
     * 自动修复状态型任务 
     */
    static function autoRecoverStateMissions() {
        $tasks = req()->userInfo->game->store->taskcards;
        foreach ($tasks as $tid => &$task) {
            $task = new Ins_TaskCard($task);

            if ($task->state == Enum_TaskCardStateType::ing //                   # 进行中的或者已完成的
                    || $task->state == Enum_TaskCardStateType::finish) {
                foreach ($task->curSteps as &$tsp) {                                # 初期里面只有一个任务
                    $tsp = new Ins_TaskStep($tsp);
                    $tsp->autoCalcStatusCur();
                }
                if ($task->state == Enum_TaskCardStateType::finish) {               # 检查是否任务卡的所有步骤都已完成
                    if (!$task->IsFinish()) {
                        $task->state = Enum_TaskCardStateType::ing;                 # 状态回退
                    }
                }
            }
        }
        req()->userInfo->game->store->taskcards = $tasks;
    }

    /**
     * 检查任务卡条件是否达成
     * @param Ins_TaskEventArgs $taskParam Description
     */
    static function CheckTaskCardConditions($taskParam) {
        $bUpdate = false;
        $tasks = req()->userInfo->game->store->taskcards;
        foreach ($tasks as $tid => &$task) {
            $task = new Ins_TaskCard($task);
            if ($task->state != Enum_TaskCardStateType::ing) {
                continue;
            }
            foreach ($task->curSteps as &$tsp) {                                # 初期里面只有一个任务
                $tsp = new Ins_TaskStep($tsp);
                if ($tsp->check_new($taskParam)) {
                    $bUpdate = true;
                    $tsp->propel($taskParam);
                    NormalEventProc::OnTaskCardStep_Process($task->uid, $tsp->typeId); # 任务进度更新
                    if ($tsp->isFinish()) {
                        NormalEventProc::OnTaskCardStep_Complete($task->uid, $tsp->typeId); # 广播任务步骤完成事件
//                        $tsp->doFinishAct();
                    }
                }
            }
            if ($task->IsFinish()) {                                            # 检查后添加后续任务
                $arr = array();
                foreach ($task->curSteps as &$tsp) {                            # 初期里面只有一个任务
                    $tsp = new Ins_TaskStep($tsp);
                    if (strlen($tsp->mo()->next) > 0) {                         # 有后续任务
                        $arr = array_merge($arr, explode(',', $tsp->mo()->next)); # 累加下一个任务步骤
                    }
                }
                foreach ($arr as $stpid) {                                      # 轮询添加后续任务
                    if ($stpid > 0) {
                        $task->AddStep($stpid);                                 # 将后续任务追加到任务列表中
                    }
                }
            }
            if ($task->IsFinish()) {                                            # 检查是否任务卡的所有步骤都已完成
                $task->state = Enum_TaskCardStateType::finish;
                NormalEventProc::OnTaskCard_Finish($task->uid, null);           # 广播卡完成事件
            }
        }
        if ($bUpdate) {                                                         # 带回数据到客户端
            req()->userInfo->game->store->taskcards = $tasks;
            UserProc::updateUserInfo();                                         # 更新玩家数据
        }

        return $bUpdate;
    }

    static function OnKillMonster($monsterID, $num) {
        $taskParam = new Ins_TaskEventArgs(Enum_TaskCmdType::KillMonster, Enum_PropelType::add, $num, array($monsterID));
        return self::CheckTaskCardConditions($taskParam);
    }

    /**
     * 获得道具
     */
    static function OnGainItem($itemId, $num) {
        $taskParam = new Ins_TaskEventArgs(Enum_TaskCmdType::GainItem, Enum_PropelType::stat, $num, array($itemId));

        self::CheckTaskCardConditions($taskParam);
    }

    /**
     * 对话完成
     * @param type $gate_or_npc_id
     * @param type $stage
     * @return type
     */
    static function OnPlotOver($gate_or_npc_id, $stage) {
        $taskParam = new Ins_TaskEventArgs(Enum_TaskCmdType::PlotOver, Enum_PropelType::set, 1, array($gate_or_npc_id, "$stage"));
        return self::CheckTaskCardConditions($taskParam);
    }

    /**
     * 购买n张任务卡(非特定) 
     * @param type $_num
     * @return type
     */
    static function OnBuyTaskCard($_num = 1) {
        $taskParam = new Ins_TaskEventArgs(Enum_TaskCmdType::BuyTaskCard_Num, Enum_PropelType::add, $_num, array());
        return self::CheckTaskCardConditions($taskParam);
    }

    /**
     * 完成任务卡(不指定) 这是要造检查任务卡的任务卡[・_・?]
     * @return type
     */
    static function OnFinishTaskCard() {
        $taskParam = new Ins_TaskEventArgs(Enum_TaskCmdType::FinishTaskCard_noID, Enum_PropelType::set, 1, array());
        return self::CheckTaskCardConditions($taskParam);
    }

    /**
     * 领取系统邮件奖励
     * @param type $mailId 指定邮件id
     * @return type
     */
    static function OnDrawSysMail($mailId) {
        $taskParam = new Ins_TaskEventArgs(Enum_TaskCmdType::DrawSysMail_ID, Enum_PropelType::set, 1, array($mailId));
        return self::CheckTaskCardConditions($taskParam);
    }

    /**
     * 言灵升级
     * @param type $yanlingType
     * @param type $level
     * @return type
     */
    static function OnYanlingLevelUp($yanlingType, $level) {
        $taskParam = new Ins_TaskEventArgs(Enum_TaskCmdType::AnyYanlingLevelUp, Enum_PropelType::set, 1, array($yanlingType, $level));
        return self::CheckTaskCardConditions($taskParam);
    }

    /**
     *  领取任意一个学院课程下的任意一个任务(num:1,paras[])(学院界面)
     */
    static function OnGetSchoolTask() {
        $taskParam = new Ins_TaskEventArgs(Enum_TaskCmdType::GetSchoolTask, Enum_PropelType::set, 1, array());
        return self::CheckTaskCardConditions($taskParam);
    }

    /**
     * 完成任意一个学院课程下的任意一张任务卡(num:1,paras:[])(学院界面)
     */
    static function OnFinishSchoolTask() {
        $taskParam = new Ins_TaskEventArgs(Enum_TaskCmdType::FinishSchoolTask, Enum_PropelType::set, 1, array());
        return self::CheckTaskCardConditions($taskParam);
    }

    /**
     * 完成指课程的全部任务(num:1,paras:[courseId])(学院界面)
     * @param int $courseId 课程id
     */
    static function OnFinishAllSchoolTaskOfGrade($courseId) {
        $taskParam = new Ins_TaskEventArgs(Enum_TaskCmdType::FinishAllSchoolTaskOfGrade, Enum_PropelType::set, 1, array($courseId));
        return self::CheckTaskCardConditions($taskParam);
    }

    // 
    // </editor-fold>
//
}
