<?php

namespace loyalsoft;

/**
 * Description of StoreProc
 * 仓库/背包 处理流程
 * ===========================
 * 尚待处理的流程：道具售出时貌似存在多种格式....
 * @author
 */
class StoreProc {

    /**
     * 逻辑分发
     * 所有的Proc中必须有这样一个方法 
     */
    static function procMain() {
        switch (req()->cmd) {
            case CmdCode::cmd_store_put:                                        # 6401 放入仓库
                return StoreProc::AddItemInStore();
            case CmdCode::cmd_store_singleSell:                                 # 6402 出售单个道具
                return StoreProc::sellItem();
            case CmdCode::cmd_store_mutliSell:                                  # 6403 批量出售 卖掉
                return StoreProc::sellMultiItemFromStore();
            case CmdCode::cmd_store_use:                                        # 6404 使用道具
                return StoreProc::useItem();
            case CmdCode::cmd_store_refresh:                                    # 6405 获取最新的仓库数据
                return StoreProc::refreshStore();
            case CmdCode::cmd_store_delItem:                                    # 6406 从仓库删除道具
                return StoreProc::delItemFromStore();
            case CmdCode::cmd_store_Testcmd:                                    # 6407 测试方法
                return StoreProc::Test();
//            case CmdCode::cmd_store_ItemUpgrade:                                # 6408 装备升级
//                return StoreProc::ItemUpgrade($req);
//            case CmdCode::cmd_store_GemCompose:                                 # 6408 装备合成
//                return StoreProc::composeItem($req);
//
            case CmdCode::cmd_store_WearEquip:                                  # 6410 给英雄穿装备
                return StoreProc::WearEquipToHero();
            case CmdCode::cmd_store_UnWieldEquip:                               # 6411 将该装备从指定英雄上脱下
                return StoreProc::UnWieldEquip();

// 
            case CmdCode::cmd_store_AddMaxPacketNum:                            # 6412 扩展包裹格子数量
                return StoreProc::AddPacketNum();
//            case CmdCode::cmd_store_MeltEquip:                                  # 6413 装备融合
//                Err(ErrCode::err_method_obsoleted);
////                return StoreProc::MeltEquip($req);
//            case CmdCode::cmd_store_PiecesCompose:                              # 6415 碎片合成
//                return StoreProc::composePieces($req);
            case CmdCode::cmd_store_WearYanling:                                # 6416 装备言灵
                return StoreProc::WearYanlingToHero();
            case CmdCode::cmd_store_UnWieldYanling:                             # 6417 卸下言灵
                return StoreProc::UnWieldYanling();
            case CmdCode::cmd_store_mergeYanlingbook:                           # 6418 利用言灵召唤书碎片合成召唤书
                return self::MergeYanlingBook();
            case CmdCode::cmd_store_callyanling:                                # 6419 利用言灵召唤书召唤言灵
                return self::CallYanlingByBook();
            case CmdCode::cmd_store_yanling_upgrade:                            # 6420 言灵进阶
                return self::YanlingUpgrade();
            default:
                Err(ErrCode::cmd_err);
        }
    }

    /**
     * [6420] 言灵进阶 
     */
    static function YanlingUpgrade() {
        list($yanlingUid) = req()->paras;                                        # 参数 言灵uid(指定进阶的言灵实例id)
        $user = req()->userInfo->game;
        my_Assert(property_exists($user->store->yanling, $yanlingUid), "找不到这个言灵");
        $yanlingObj = $user->store->yanling->$yanlingUid;
        $yanlingMoId = $yanlingObj->typeId;
        $curGrade = property_exists($yanlingObj, "grade") ? $yanlingObj->grade : 1; # 当前等阶
        $toGrade = $curGrade + 1;                                               # 下一等阶
        my_Assert($toGrade <= 5, ErrCode::store_yanlingGrade_max);              # 已经进阶到最高
        $toGradeCfg = GameConfig::yanling_upgrade_getItem($yanlingMoId, $toGrade); # 下一阶配置
        my_Assert(null != $toGradeCfg, ErrCode::err_const_no);                  # 找不到言灵进阶常量 
        $costs = explode(';', $toGradeCfg->cost_materials);
        my_Assert(count($costs) > 0, ErrCode::store_yanlingGrade_cfg);          # 言灵进阶数据有误
        foreach ($costs as $c) {
            list($itemId, $num) = explode(',', $c);                             # 解析材料
            $err = self::removeItemFromStore($user->store, $itemId, $num);      # 扣除 材料
            my_Assert(ErrCode::ok == $err, $err);                               # 防御扣除材料失败
        }
        $yanlingObj->grade = $toGrade;                                          # 修改进阶
        $user->store->yanling->$yanlingUid = $yanlingObj;                       # 回写言灵数据 
        UserProc::updateUserInfo();                                             # 回写玩家数据 
        return Resp::ok(array(
                    "store" => $user->store, #                                  # 目前来看只涉及到items变化
        ));
    }

    /**
     * [6418] 利用言灵召唤书碎片合成召唤书 
     */
    static function MergeYanlingBook() {
        list($bookId) = req()->paras;                                            # 参数 言灵召唤书id
        $user = req()->userInfo->game;
        $bookIdCfg = GameConfig::item_yanlingbook_getItem($bookId);
        my_Assert(null != $bookIdCfg, ErrCode::err_const_no);                   # 找不到言灵书常量
        list($segId, $num) = explode(',', $bookIdCfg->seg_num);                 # 解析所需碎片信息
        $err = self::removeItemFromStore($user->store, $segId, $num);           # 扣除 碎片
        my_Assert(ErrCode::ok == $err, $err);                                   # 防御扣除碎片失败
        self::PutOverlyingItemInStore($bookId);                                 # 添加召唤书
        UserProc::updateUserInfo();                                             # 回写数据 
        return Resp::ok(array(
                    "store" => $user->store, #                                  # 目前来看只涉及到items变化
        ));
    }

    /**
     * [6419] 利用言灵召唤书召唤言灵 
     */
    static function CallYanlingByBook() {
        list($bookId) = req()->paras;                                            # 参数 利用的言灵召唤书id
        $user = req()->userInfo->game;
        $bookIdCfg = GameConfig::item_yanlingbook_getItem($bookId);
        my_Assert(null != $bookIdCfg, ErrCode::err_const_no);                   # 找不到言灵书常量
        $err = self::removeItemFromStore($user->store, $bookId);                # 扣除 召唤书
        my_Assert(ErrCode::ok == $err, $err);                                   # 防御扣除召唤书失败
        $costs = explode(';', $bookIdCfg->cost_materials);
        my_Assert(count($costs) > 0, ErrCode::store_book_info);                 # 召唤书数据有误
        foreach ($costs as $c) {
            list($itemId, $num) = explode(',', $c);                             # 解析材料
            $err = self::removeItemFromStore($user->store, $itemId, $num);      # 扣除 材料
            my_Assert(ErrCode::ok == $err, $err);                               # 防御扣除材料失败
        }
        self::PutYanLingInStore($bookIdCfg->yanling_id);                        # 添加言灵 
        UserProc::updateUserInfo();                                             # 回写数据 
        return Resp::ok(array(
                    "store" => $user->store, #                                  # 目前来看只涉及到items变化
        ));
    }

    /**
     * 测试方法 
     * @return type
     */
    static public function Test() {
        Err(ErrCode::msg_method_obsoleted, "代码需更新");
    }

    /**
     * [6404] 使用仓库道具 
     */
    static function useItem() {
        Err(ErrCode::msg_method_obsoleted, "代码需更新");
    }

    /**
     * [6405] 刷新仓库列表 
     */
    static function refreshStore() {
        StoreProc::CheckItemNum();
        return Resp::ok(array('store' => req()->userInfo->game->store));
    }

    /**
     * [6406] 从仓库删除道具 
     */
    static function delItemFromStore() {
        list($itemId, $num) = req()->paras;
        $err = self::removeItemFromStore(req()->userInfo->game->store, $itemId, $num);
        my_Assert(ErrCode::ok == $err, $err);
        UserProc::updateUserInfo();
        return Resp::ok(array('store' => req()->userInfo->game->store));
    }

    /**
     * [6409] 合成道具
     */
    static public function composeItem() {
        Err(ErrCode::err_method_notimplement);
    }

    /**
     * [6409] 合成碎片（几个碎片合成获得同品质或者更高品质的新碎片） 
     */
    static public function composePieces() {
        Err(ErrCode::err_method_notimplement);
    }

// </editor-fold>
//  ---------------  以下为辅助方法  ------------------
//
// <editor-fold defaultstate="collapsed" desc="   移除物品   ">

    /**
     * 从仓库中移除指定数量的物品
     * @param Info_Store $store
     * @param type $itemId
     * @param type $itemcount
     * @return type
     */
    static function removeItemFromStore($store, $itemId, $itemcount = 1) {
        my_Assert(CommUtil::isPropertyExists($store->items, $itemId), ErrCode::store_itemno_err); # 没有这个道具
        my_Assert($store->items->$itemId >= $itemcount, ErrCode::store_itemnotenough); # 数量不足
        $store->items->$itemId -= $itemcount;
        if ($store->items->$itemId == 0) {
            unset($store->items->$itemId);
        }
        NormalEventProc::OnBag_Remove_Item($itemId, $itemcount);                # 插入事件
        return ErrCode::ok;
    }

    /**
     * 从仓库移出装备
     * @param type $itemId  uid
     * @param Info_Store $store
     * @return boolean
     */
    static function removeEquipFromStore($uid, $typeId) {
        $ok = false;
        if (CommUtil::isPropertyExists(req()->userInfo->game->store->equipment, $uid)) {
            my_Assert($typeId == req()->userInfo->game->store->equipment->$uid->typeId, "typeid检验错误"); // typeid相同;
            unset(req()->userInfo->game->store->equipment->$uid);
            $ok = true;
        }
        return $ok;
    }

    /**
     * 从仓库移除碎片
     * @param Info_Store $store
     * @param int $segmentId
     * @param int $num
     * @return bool 成功/失败
     */
    static function removeSegmetFromStore($store, $segmentId, $num = 1) {
        if (CommUtil::isPropertyExists($store->segement, $segmentId)  #
                && $store->segement->$segmentId >= $num) {
            $store->segement->$segmentId -= $num;
            return TRUE;
        }
        return false;
    }

    /**
     * 向仓库添加碎片
     * @param Info_Store $store
     * @param int $segmentId
     * @param int $num
     */
    static function addSegmentIntoStore($store, $segmentId, $num = 1) {
        if (CommUtil::isPropertyExists($store->segement, $segmentId)) {
            $store->segement->$segmentId += $num;
        } else {
            $store->segement->$segmentId = $num;
        }
        $segMo = GameConfig::item_segment_getItem($segmentId);
        my_Assert($segMo != null, ErrCode::err_const_no);
        TaskProc::OnHeroSegmengNum($segMo->protoHeroID, $num);
    }

// </editor-fold>
//
// <editor-fold defaultstate="collapsed" desc="   放入物品   ">

    /**
     * 将其他物品放入仓库
     * @param type $itemId
     * @param Data_UserGame $game
     */
    static function PutItemInStore($itemId, &$game) {
        if (CommUtil::isPropertyExists($game->store->items, $itemId)) {         // 如果仓库中已经有这种元素，则其数目+1
            $game->store->items->$itemId += 1;
        } else {// 如果仓库中没有这种元素，则其数目置1
            $game->store->items->$itemId = 1;
        }
    }

    /**
     * 解包多种物品到玩家身上 【警告】此函数的异常处理功能残废，不安全
     * 检测如果当前物品格子大于物品总数,则可以获取战利品,否则不可以 
     * @param string $goodsStr itemid,num;itemid,num;...
     * @param int $src 1:战斗奖励, 2: 任务奖励, 3: 抽奖奖品, 4: 邮件领取, 5: 现金充值
     * @deprecated since version 0
     * @return type
     */
    public static function AddMultiItemInStore($goodsStr, $src = 1) {
        $user = req()->userInfo->game;
        $ary = explode(";", $goodsStr);
        foreach ($ary as $value) {
            $val = explode(",", $value);
            $cid = "";
            my_Assert(count($val) > 1, "解析奖励字符串出错");
            list( $itemId, $num) = $val;                                        # ID, 数量
            $smItem = GameConfig::item_base_getItem($itemId);                   # 道具mo
            switch ($smItem->subType) {                                         # 根据类型分别添加到容器中
                case META_EXP:                                                  # 指挥官经验
//                    Data_UserGame::Add_Exp($user->baseInfo, $num);
                    $user->base()->Add_Exp($num);                               # 加指挥官经验
                    break;
                case META_GOLD_ITEMID:                                          # 金币
//                    Data_UserGame::Add_Gold($user->baseInfo, $num);
                    $user->base()->Add_Gold($num);                              # 增加金币
                    break;
                case META_CASH_ITEMID:                                          # 钻石
//                    Data_UserGame::Add_Cash($user->baseInfo, $num);
                    $user->base()->Add_Cash($num);                              # 增加钻石
                    break;
                case META_tili_ITEMID:                                          # 体力       
//                    Data_UserGame::Add_tili($num);
                    $user->base()->Add_tili($num);                              # 增加体力
                    break;
                case META_FriendShipPoit_ItemId:                                # 友情值
//                    Data_UserGame::Add_FriendPoint($user->baseInfo, $num);
                    $user->base()->Add_FriendPoint($num);                       # 加友情点
                    break;
                case META_PVPCOIN_ITEMID:                                       # 竞技币
                    $user->pvp->pvpCoins += $num;
                    break;
                case META_ActivePoint_ITEMID:
//                    $user->task->dailyActivePoint += $num;                    # 每日任务活跃点
                    break;
                case META_RESPOINT_ITEMID:
                    $user->base()->Add_resPoint($num);                          # 增加资源点
//                    Data_UserGame::Add_resPoint($user->baseInfo, $num);         # 资源点添加
                    break;
                case 101:                                                       # 武器 
                    for ($n = 0; $n < $num; $n++) {
                        $cid = StoreProc::PutEquipInStore($itemId);
                    }
                    CornerSignEventProc::OnBag_new_Weapon();
                    break;
                case 401:                                                       # 言灵
                    for ($n = 0; $n < $num; $n++) {
                        $cid = StoreProc::PutYanLingInStore($itemId);
                    }
                    CornerSignEventProc::OnBag_new_Yanling();
                    break;
                case 501:                                                       # 限购礼包
                    var_dump("-== 礼包解包 nil ==-");
                    $itemMO = GameConfig::item_package_getItem($itemId);
                    my_Assert(null != $itemMO, ErrCode::err_const_no);
                    $err = StoreProc::AddMultiItemInStore($itemMO->contents);         # 发放奖励
                    my_Assert(ErrCode::ok == $err, $err);
                    break;
                case 601:                                                       # 任务卡
                    $cid = StoreProc::PutTaskCardInStore($itemId);
                    break;
                case 201:                                                       # 碎片
                    $segMo = GameConfig::item_segment_getItem($itemId);
                    my_Assert($segMo != null, ErrCode::err_const_no);
                    TaskProc::OnHeroSegmengNum($segMo->protoHeroID, $num);
                    CornerSignEventProc::OnBag_new_Fragment();
                case 202:                                                       # 召唤书碎片
                case 312:                                                       # 言灵召唤/进阶材料
                case 351:                                                       # 言灵召唤书
                    StoreProc::PutOverlyingItemInStore($itemId, $num);          # 直接进包裹items
                    $book = GameConfig::item_yanlingbook_getItem($itemId);
                    my_Assert(null != $book, ErrCode::err_const_no);
                    $ylCfg = GameConfig::item_yanling_getItem($book->yanling_id);
                    my_Assert(null != $ylCfg, ErrCode::err_const_no);
                    switch ($ylCfg->career) {                                   # 根据不同职业更新角标系统
                        case 1:
                            CornerSignEventProc::OnCall_Warrior_new();          # 战士
                            break;
                        case 2:
                            CornerSignEventProc::OnCall_Magician_new();         # 法师
                            break;
                        case 3:
                            CornerSignEventProc::OnCall_Archer_new();           # 射手
                            break;
                        default :
                            break;
                    }
                    break;
                case 321:                                                       # 进阶材料
                case 322:                                                       # 进阶材料
                case 323:                                                       # 锻造材料
                case 324:                                                       # 魂器
                case 332:
                case 333:
                    StoreProc::PutOverlyingItemInStore($itemId, $num);          # 直接进包裹items
                    CornerSignEventProc::OnBag_new_Material();
                    break;
                case 311:                                                       # 基因(经验丹)
                    StoreProc::PutOverlyingItemInStore($itemId, $num);          # 直接进包裹items
                    break;
                case 341:                                                       # 战场中掉落,不会进入包裹
                case 342:
                case 343:
                    Err(ErrCode::err_innerfault, "落入包裹时,出现了非法物品($itemId)");
                    break;
                default :
                    Err(ErrCode::err_innerfault, "落入包裹时,出现了非法物品($itemId)");
            }
            TaskProc::OnGainItem($itemId, $num);                                // 检查获得道具的任务进度
            NormalEventProc::OnBag_new_Item($itemId, $num, $cid);
        }
        return ErrCode::ok;                                                     // 返回
    }

    /**
     * [6401]向包裹中添加物品 
     */
    public static function AddItemInStore() {
        list($rwdStr) = req()->paras;
        $user = req()->userInfo->game;
        $err = self::AddMultiItemInStore($rwdStr);
        my_Assert(ErrCode::ok == $err, $err);
        UserProc::updateUserInfo();
        return Resp::ok(array(
                    'gold' => $user->baseInfo->gold,
                    'tili' => $user->baseInfo->tili,
                    'cash' => $user->baseInfo->cash,
                    'resPoint' => $user->baseInfo->resPoint,
                    'store' => $user->store));
    }

    /**
     * 将装备放入背包
     * @param type $itemId 
     */
    static function PutEquipInStore($itemId) {
        $privateState = req()->userInfo->game->privateState;
        if (!CommUtil::isPropertyExists($privateState, "currentId")) {          // 如果仓库中已经有这种元素，则其数目+1
            req()->userInfo->game->privateState->currentId = 1;
        }
        $cid = req()->userInfo->game->privateState->currentId++;
        $equip = ObjectInit();
        $equip->typeId = $itemId;
        req()->userInfo->game->store->equipment->$cid = $equip;
        return $cid;
//        SystemProc::GetEquip($req->zoneid, $req->userInfo->game, $itemId);      # 添加获得装备的消息
    }

    /**
     * 将言灵放入背包
     * @param type $itemId 
     */
    static function PutYanLingInStore($itemId) {
        my_Assert(count((array) req()->userInfo->game->store->yanling) < 100, ErrCode::store_yanling_bagfull);
        $privateState = req()->userInfo->game->privateState;
        if (!CommUtil::isPropertyExists($privateState, "currentId")) {          # 如果仓库中已经有这种元素，则其数目+1
            req()->userInfo->game->privateState->currentId = 1;
        }
        $cid = req()->userInfo->game->privateState->currentId++;
        //$equip = ObjectInit();
        $equip = new Ins_YanLin();
        $equip->typeId = $itemId;
        req()->userInfo->game->store->yanling->$cid = $equip;
        return $cid;
    }

    /**
     * 将任务卡放入背包
     * @param type $itemId 
     */
    static function PutTaskCardInStore($itemId) {
        $privateState = req()->userInfo->game->privateState;
        if (!CommUtil::isPropertyExists($privateState, "currentId")) {          # 如果仓库中已经有这种元素，则其数目+1
            req()->userInfo->game->privateState->currentId = 1;
        }
        $cid = req()->userInfo->game->privateState->currentId++;
        $mo = GameConfig::item_taskcard_getItem($itemId);                       # 任务卡常量
        my_Assert(null != $mo, ErrCode::err_const_no);
        $itembaseMo = GameConfig::item_base_getItem($itemId);
        my_Assert(null != $itembaseMo, ErrCode::err_const_no);
        if ($itembaseMo->pileNum > 0) {                                         # 可叠加
            Err(ErrCode::taskCard_no_pile);                                     # 不可堆叠!!! 我支持不了.gwang 2020年12月12日13:40:04
            // <editor-fold defaultstate="collapsed" desc=" 折叠 ">
//            $taskCard = null;
//            foreach ($req->userInfo->game->store->taskcards as $uuid => &$val) {
//                $val = new Ins_TaskCard($val);
//                if ($val->typeId == $itemId) {
//                    $taskCard = $val;
//                    break;
//                }
//            }
//            if (null == $taskCard) {                                            # 原来么有
//                $taskCard = new Ins_TaskCard($itemId);
//                $taskCard->uid = $cid;
//                $req->userInfo->game->store->taskcards->$cid = $taskCard;
//            }
//            $taskCard->count += 1;
            // </editor-fold>
        } else {
            $taskCard = new Ins_TaskCard($itemId);
            $taskCard->uid = $cid;
            req()->userInfo->game->store->taskcards->$cid = $taskCard;
        }
        NormalEventProc::OnTaskBag_new_Card($cid, 1);                           # 播放获得任务卡事件
        if (null != $taskCard) {
            req()->paras = array($cid);
            TaskProc::OnTaskCard_active();                                      # 自动激活任务卡
        }
        return $cid;
    }

    /**
     * 将可叠加物品放入背包
     * @param int $itemId
     * @param int $num
     */
    static function PutOverlyingItemInStore($itemId, $num = 1) {
        $items = req()->userInfo->game->store->items;                           # dic: itemid=>number
        if (CommUtil::isPropertyExists($items, $itemId)) {                      # 如果仓库中已经有这种元素，则其数目+=num
            $items->$itemId += $num;
        } else {                                                                # 如果仓库中没有这种元素，则其数目置为num
            $items->$itemId = $num;
        }
    }

    /**
     * 物品包裹打散成独立道具到仓库
     * @param GoodsItemModel $itemModel 
     * @deprecated since version now
     */
    static function addSeprateItem($itemModel) {
        Err(ErrCode::err_method_obsoleted, "未更新包裹操作");
    }

    /**
     * [6416] 给英雄装上言灵
     */
    static function WearYanlingToHero() {
        $user = req()->userInfo->game;                                           # user引用
        list($itemtype, $yanling_uid, $herouid) = req()->paras;                  # 提取参数: 装备类型, 装备的UID, 英雄的UID 
        my_Assert(CommUtil::isPropertyExists($user->store->yanling, $yanling_uid), ErrCode::store_itemno_err); # 检测是否存在该言灵
        $yanlingVo = new Ins_YanLin($user->store->yanling->$yanling_uid);       # 取言灵对象
        if (isset($yanlingVo->herouid) && $yanlingVo->herouid > 0               #
                && $yanlingVo->herouid != $herouid) {                           # 检测该言灵是否装备到其他英雄身上 
            Err(ErrCode::store_equipWeared_err);
        }
        $collectHeros = $user->heros->collectHeros;                             # 英雄集合
        my_Assert(null != $collectHeros, ErrCode::err_innerfault);              # 防御对象为空
        my_Assert(CommUtil::isPropertyExists($collectHeros, $herouid), ErrCode::hero_no); # 检查英雄是否存在
        $hero = new Ins_UserHero($collectHeros->$herouid);                      # 取hero
        my_Assert($hero->level >= $yanlingVo->mo()->require_herolvl, "请提升唤灵师等级"); # 可装备的言灵等级受唤灵师等级限制.
        $user->store->yanling->$yanling_uid->herouid = $herouid;                # 言灵上添加反向引用, 避免查询时的循环
        $oldYLid = $collectHeros->$herouid->yanling->$itemtype->itemuid;        # 旧言灵id
        if ($oldYLid > 0) {                                                     # 代表替换操作
            $user->store->yanling->$oldYLid->herouid = 0;                       # 清理旧言灵的
        }
        $hero->yanling->$itemtype->itemuid = $yanling_uid;                      # 英雄身上添加言灵记录
        $collectHeros->$herouid = $hero;
        TaskProc::OnHeroWearYanling($collectHeros->$herouid->typeId, $user->store->yanling->$yanling_uid->typeId);
        UserProc::updateUserInfo();                                             # 5.回写数据
        $ret = array('resp' => "succeed!",
            'store' => $user->store);
        $resp = Resp::ok($ret);                                                 // 返回 
        HeroProc::CalcUserFightPower(req()->zoneid, req()->uid, $user);           # 更新总战力榜
        return $resp;
    }

    /**
     * [6417] 给英雄卸下言灵 
     * @deprecated since version 无法卸下,只能更换
     */
    static function UnWieldYanling() {
        $user = req()->userInfo->game;                                           # user引用
        list($itemtype, $yanling_uid, $herouid) = req()->paras;                  # 提取参数: 装备类型, 装备的UID, 拥有该装备的英雄的UID 

        $collectHeros = $user->heros->collectHeros;
        my_Assert(null != $collectHeros, ErrCode::err_innerfault);              # 防御
        my_Assert(CommUtil::isPropertyExists($collectHeros, $herouid), ErrCode::hero_no); # 检测是否存在拥有该装备的英雄
        my_Assert(CommUtil::isPropertyExists($user->store->yanling, $yanling_uid), ErrCode::store_itemno_err); # 检测是否存在该装备
        if ($user->store->yanling->$yanling_uid->herouid == $herouid) {         # 取装备对象
            $user->store->yanling->$yanling_uid->herouid = 0;                   # 清理反向引用
        }
//        $arr = $collectHeros->$herouid->yanling;
//        my_Assert(in_array($yanling_uid, $arr), ErrCode::hero_yanling_notfound); # 未装备此言灵
//        StlUtil::arrayRemove($arr, $yanling_uid);
//        $collectHeros->$herouid->yanling = $arr;

        my_Assert($collectHeros->$herouid->yanling->$itemtype->itemuid == $yanling_uid, ErrCode::store_noequip_err); # 防御
        $collectHeros->$herouid->yanling->$itemtype->itemuid = 0;               # 卸下

        UserProc::updateUserInfo();                                             # 回写数据
        $resp = Resp::ok(array('resp' => "succeed!"));                          // 返回 
//        StoreProc::CheckItemNum($req);
        return $resp;
    }

    /**
     * [6410] 给英雄穿装备 
     */
    static function WearEquipToHero() {
        list($itemtype, $equipuid, $herouid) = req()->paras;                    # 提取参数: 装备类型, 装备的UID, 英雄的UID  
        $user = req()->userInfo->game;                                          # user引用
        my_Assert(CommUtil::isPropertyExists($user->store->equipment, $equipuid), ErrCode::store_itemno_err);  # 检测是否存在该装备
        $equipVo = new Ins_Weapon($user->store->equipment->$equipuid);          # 取装备对象
        if ($equipVo->herouid > 0) {                                            # 检测该装备是否装备到其他英雄身上 
            my_Assert($equipVo->herouid == $herouid, ErrCode::store_equipWeared_err);
            $user->store->equipment->$equipuid->herouid = 0;                    # 清理原来已经装备的言灵的反指向
        }
        $collectHeros = $user->heros->collectHeros;
        my_default_Obj($collectHeros);
        my_Assert(CommUtil::isPropertyExists($collectHeros, $herouid), ErrCode::hero_no); # 检查是否存在需要装备的英雄
        $hero = new Ins_UserHero($collectHeros->$herouid);                      # 取hero
        my_Assert($hero->level >= $equipVo->mo()->require_herolvl, "请升级唤灵师."); # 检查武器要求的唤灵师等级, -gwang 2021.4.20
        $user->store->equipment->$equipuid->herouid = $herouid;                 # 装备上添加反向引用, 避免查询时的循环
        $oldEquipId = 0;
        switch ($itemtype) {                                                    # 添加或替换英雄该部位的装备
            case 1:                                                             # 武器   
                $oldEquipId = $collectHeros->$herouid->equip->weapon->itemuid;
                $collectHeros->$herouid->equip->weapon->itemuid = $equipuid;
                break;
            case 2:                                                             # 防具 
                $oldEquipId = $collectHeros->$herouid->equip->armor->itemuid;
                $collectHeros->$herouid->equip->armor->itemuid = $equipuid;
                break;
            case 3:                                                             # 饰品   
                $oldEquipId = $collectHeros->$herouid->equip->ring->itemuid;
                $collectHeros->$herouid->equip->ring->itemuid = $equipuid;
                break;
            default :
                Err(ErrCode::store_equip_type);
                break;
        }
        if ($oldEquipId > 0 && $oldEquipId != $equipuid) {
            $user->store->equipment->$oldEquipId->herouid = 0;
        }
        UserProc::updateUserInfo();                                             // 5.回写数据
//        StoreProc::CheckItemNum($req);
        TaskProc::OnHeroWearWeapon($collectHeros->$herouid->typeId, $user->store->equipment->$equipuid->typeId);
        HeroProc::CalcUserFightPower(req()->zoneid, req()->uid, $user);           # 更新总战力榜
        return Resp::ok(array('resp' => "succeed!",
                    'store' => $user->store));                           // 返回 
    }

    /**
     * [6411] 给英雄脱装备
     * @deprecated since version 不能卸下装备, 只能更换.  
     */
    static function UnWieldEquip() {
        list($itemtype, $equipuid, $herouid) = req()->paras;                    # 提取参数: 装备类型, 装备的UID, 拥有该装备的英雄的UID 
        $user = req()->userInfo->game;                                          # user引用

        $collectHeros = $user->heros->collectHeros;
        my_default_Obj($collectHeros);
        my_Assert(CommUtil::isPropertyExists($collectHeros, $herouid), ErrCode::hero_no);             # 检测是否存在拥有该装备的英雄
        my_Assert(CommUtil::isPropertyExists($user->store->equipment, $equipuid), ErrCode::store_itemno_err);  # 检测是否存在该装备
        if ($user->store->equipment->$equipuid->herouid == $herouid) {          # 取装备对象
            $user->store->equipment->$equipuid->herouid = 0;
        }
        switch ($itemtype) {                                                    # 检测该装备是否装备在该英雄身上
            case 1:                                                             # 武器 
                if ($collectHeros->$herouid->equip->weapon->itemuid != $equipuid) {
                    Err(ErrCode::store_noequip_err);
                }
                $collectHeros->$herouid->equip->weapon->itemuid = 0;            # 卸下
                break;
            case 2:                                                             # 防具
                if ($collectHeros->$herouid->equip->armor->itemuid != $equipuid) {
                    Err(ErrCode::store_noequip_err);
                }
                $collectHeros->$herouid->equip->armor->itemuid = 0;
                break;
            case 3:                                                             # 饰品
                if ($collectHeros->$herouid->equip->ring->itemuid != $equipuid) {
                    Err(ErrCode::store_noequip_err);
                }
                $collectHeros->$herouid->equip->ring->itemuid = 0;
                break;
            default :
                Err(ErrCode::store_equip_type);
        }
        UserProc::updateUserInfo();                                             # 回写数据 
        return Resp::ok(array('resp' => "succeed!"));                           // 返回
    }

// </editor-fold>
//
// <editor-fold defaultstate="collapsed" desc="    辅助方法    ">
//    

    /**
     * 检查背包中物品的个数
     * @return int
     */
    public static function CheckItemNum() {
        $ItemObj = req()->userInfo->game->store->items;
        $EquipObj = req()->userInfo->game->store->equipment;
        $SegementObj = req()->userInfo->game->store->segement;
        $HeroObj = req()->userInfo->game->heros->collectHeros;
        $ItemNum = 0;
        if ($ItemObj) {
            foreach ($ItemObj as $value) {                                      ////检查宝石类可叠加物品的格子占用
                $ItemNum++;
            }
        }
        if ($SegementObj) {
            foreach ($SegementObj as $value) {                                  # 碎片
                $ItemNum++;
            }
        }
        if ($EquipObj) {
            foreach ($EquipObj as $value) {                                     // 检测装备类物品格子占用
                $ItemNum++;
            }
        }
        if ($HeroObj) {
            foreach ($HeroObj as $value) {                                      // 检测英雄装备到身上的情况,装备到英雄身上不占格子,要减去.
                $HeroEquipId = $value->equip->weapon->itemuid;
                if ($HeroEquipId > 0) {
                    $ItemNum--;
                }
                $HeroEquipId = $value->equip->armor->itemuid;
                if ($HeroEquipId > 0) {
                    $ItemNum--;
                }
                $HeroEquipId = $value->equip->ring->itemuid;
                if ($HeroEquipId > 0) {
                    $ItemNum--;
                }
            }
        }
        req()->userInfo->game->privateState->ItemNum = $ItemNum;
        return $ItemNum;
    }

    /**
     * 获取物品格子的上限值
     * @return int 上限数值
     */
    public static function GetItemMaxNum() {
        $user = req()->userInfo->game;
        if (!CommUtil::isPropertyExists($user->privateState, "maxItemNum")) {
            $user->privateState->maxItemNum = glc()->Item_Packet_MaxNum;
        }
        return $user->privateState->maxItemNum;
    }

    /**
     * 6412 背包扩容
     */
    public static function AddPacketNum() {
        $user = req()->userInfo->game;                                           # user引用
        if (!CommUtil::isPropertyExists($user->privateState, "maxItemNum")) {
            $user->privateState->maxItemNum = glc()->Item_Packet_MaxNum;
        }
        $costCash = glc()->Item_Packet_NumCostCash;                             # 钻石花费
        my_Assert($costCash > 0, ErrCode::paras_err);
        my_Assert($user->base()->Consume_Cash($costCash), ErrCode::notenough_cash_msg); # 6.进行消耗

        $user->privateState->maxItemNum += 10;                                  # 扩容
        UserProc::updateUserInfo();                                             # 保存玩家数据
        $resp = Resp::ok(array('maxItemNum' => $user->privateState->maxItemNum)); # 返回值
        StoreProc::CheckItemNum();
        return $resp;
    }

// </editor-fold>
//  
// <editor-fold defaultstate="collapsed" desc="   出售   ">
// 

    /**
     * 出售单一的物品
     */
    static function sellItem() {
        Err(ErrCode::err_method_obsoleted, "代码需要更新");
    }

    /**
     * 卖出一堆物品时候，检测每个单个物品是否符合卖的条件 
     */
    static function preSellSingleFromStore($type, $itemId, $count, $uid) {
        Err(ErrCode::err_method_obsoleted, "代码需要更新");
    }

    /**
     * 6403 从背包出售多个物品
     */
    static function sellMultiItemFromStore() {
        Err(ErrCode::err_method_obsoleted, "代码需要更新");
        $obj = req()->paras[0];                                                  // 获取物品的结构数组  
        foreach ($obj as $value) {
            $type = $value[0];
            $itemId = $value[1];

            if ($type > 3) {
                $count = intval($value[2]);  // 数量
                $uid = 0;
            } else {          ////先判断一下物品类型，如果是可叠加的，就按数量取值，如果是不可叠加的就按uid取值
                $count = 1;
                $uid = $value[2];
            }//物品的uid
            $resp = StoreProc:: preSellSingleFromStore($type, $itemId, $count, $uid);
        }

        if (0 == $resp->err) {
            UserProc::updateUserInfo();
        }

        StoreProc::CheckItemNum();
        return $resp;
    }

// </editor-fold>
//
}
