import { SkinModel } from "../db/Skin";
import { HeroModel } from "../db/Hero";
import { RoleModel } from "../db/Role";
import { GuildModel } from "../db/Guild";
import { PvpDefenseModel } from "../db/PvpDefense";
import { ActionPointModel } from '../db/ActionPoint';
import { BattleDropModel } from '../db/BattleDrop';
import { BattleRecordModel } from '../db/BattleRecord';
import { BattleSweepRecordModel } from '../db/BattleSweepRecord';
import { DailyRecordModel } from '../db/DailyRecord';
import { EventRecordModel } from '../db/EventRecord';
import { ExpeditionPointModel } from '../db/ExpeditionPoint';
import { ExpeditionRecordModel } from '../db/ExpeditionRecord';
import { ExpeditionWarRecordModel } from '../db/ExpeditionWarRecord';
import { HangUpRecordModel } from '../db/HangUpRecord';
import { HangUpSpdUpRecModel } from '../db/HangUpSpdUpRec';
import { SearchRecordModel } from '../db/SearchRecord';
import { TowerRecordModel } from '../db/TowerRecord';
import { TowerTaskRecModel } from '../db/TowerTaskRec';
import { ItemModel } from '../db/Item';
import { SchoolModel } from '../db/School';
import { FriendShipModel } from '../db/FriendShip';
import { FriendApplyModel } from '../db/FriendApply';
import { FriendRelationModel } from '../db/FriendRelation';
import { ActivityBuyRecordsModel } from '../db/ActivityBuyRecords';
import { ActivityDailyChallengesModel } from '../db/ActivityDailyChallenges';
import { ActivityDailyCoinModel } from '../db/ActivityDailyCoin';
import { ActivityDailyGiftsModel } from '../db/ActivityDailyGifts';
import { ActivityDailyGKModel } from '../db/ActivityDailyGK';
import { ActivityDailyMealModel } from '../db/ActivityDailyMeal';
import { ActivityDailyRMBGiftsModel } from '../db/ActivityDailyRMBGifts';
import { ActivityFirstGiftModel } from '../db/ActivityFirstGift';
import { ActivityGrowthFundModel } from '../db/ActivityGrowthFund';
import { ActivityGrowthModel } from '../db/ActivityGrowth';
import { ActivityGrowthPointModel } from '../db/ActivityGrowthPoint';
import { ActivityMonopolyModel } from '../db/ActivityMonopoly';
import { ActivityMonopolyLandModel } from '../db/ActivityMonopolyLand';
import { ActivityMonthlyTicketModel } from '../db/ActivityMonthlyTicket';
import { ActivityNewHeroGiftModel } from '../db/ActivityNewHeroGift';
import { ActivityNewHeroGKModel } from '../db/ActivityNewHeroGK';
import { ActivityPopUpShopModel } from '../db/ActivityPopUpShop';
import { ActivityRechargeMoneyModel } from '../db/ActivityRechargeMoney';
import { ActivityRefreshShopModel } from '../db/ActivityRefreshShop';
import { ActivityRefreshTaskModel } from '../db/ActivityRefreshTask';
import { ActivityRefreshTaskPointModel } from '../db/ActivityRefreshTaskPoint';
import { ActivitySelfServiceGoodsModel } from '../db/ActivitySelfServiceGoods';
import { ActivitySelfServiceModel } from '../db/ActivitySelfService';
import { ActivitySelfServiceShopModel } from '../db/ActivitySelfServiceShop';
import { ActivityShopModel } from '../db/ActivityShop';
import { ActivitySignInModel } from '../db/ActivitySignIn';
import { ActivityTaskPointModel } from '../db/ActivityTaskPoint';
import { ActivityThirtyDaysModel } from '../db/ActivityThirtyDays';
import { ActivityThirtyDaysPointRewardModel } from '../db/ActivityThirtyDaysPointReward';
import { ActivityTreasureHuntFirstPageModel } from '../db/ActivityTreasureHuntFirstPage';
import { ActivityTreasureHuntShopModel } from '../db/ActivityTreasureHuntShop';
import { ActivityTreasureHuntTaskModel } from '../db/ActivityTreasureHuntTask';
import { ActivityTreasureHuntTreasureShopModel } from '../db/ActivityTreasureHuntTreasureShop';
import { ActivityVipRechargeMoneyModel } from '../db/ActivityVipRechargeMoney';
import { ChatInfoModel } from '../db/ChatInfo';
import { DungeonFirstModel } from '../db/DungeonFirst';
import { EquipPrintDropModel } from '../db/EquipPrintDrop';
import { FriendPointModel } from '../db/FriendPoint';
import { FriendPresentLogModel } from '../db/FriendPresentLog';
import { GroupMailModel } from '../db/GroupMail';
import { UserGuildModel } from '../db/UserGuild';
import { UserGuildApplyModel } from '../db/UserGuildApply';
import { GuildRecModel } from '../db/GuildRec';
import { MailModel } from '../db/Mail';
import { MessageModel } from '../db/Message';
import { PrivateMessageModel } from '../db/PrivateMessage';
import { RScriptRecordModel } from '../db/RScriptRecord';
import { ScriptBarrageModel } from '../db/ScriptBarrage';
import { ServerMailModel } from '../db/ServerMail';
import { UserGachaModel } from '../db/UserGacha';
import { UserGachaRecModel } from '../db/UserGachaRec';
import { UserGuildActivityRecModel } from '../db/UserGuildActivityRec';
import { UserOrderModel } from '../db/UserOrder';
import { UserShopModel } from '../db/UserShop';
import { UserTaskModel } from '../db/UserTask';
import { UserTaskHistoryModel } from '../db/UserTaskHistory';
import { UserTaskRecModel } from '../db/UserTaskRec';
import { WishPoolReportModel } from '../db/WishPoolReport';
import { pick } from "underscore";
import { JewelModel } from "../db/Jewel";
import { RoleCeModel } from "../db/RoleCe";
import { RewardParam } from "../domain/activityField/rewardField";
import { decodeArrayListStr } from "./util";
import { RewardInter } from "./interface";
import { CreateHeroParam } from "../domain/roleField/hero";
import { ACTIVITY_RESOURCES_TYPE } from "../consts";
import { gameData } from "./data";
import { ActivityTaskPassModel } from "../db/ActivityTaskPass";
import { LadderMatchModel } from "../db/LadderMatch";

export async function deletRole(roleId: string) {
    let role = await RoleModel.findByRoleId(roleId, null, true, true);
    if(!role ) return false;
    if(role.hasInit) {

    
    await ActionPointModel.deleteMany({roleId});
    await ActivityBuyRecordsModel.deleteMany({ roleId });
    await ActivityDailyChallengesModel.deleteMany({ roleId });
    await ActivityDailyCoinModel.deleteMany({ roleId });
    await ActivityDailyGiftsModel.deleteMany({ roleId });
    await ActivityDailyGKModel.deleteMany({ roleId });
    await ActivityDailyMealModel.deleteMany({ roleId });
    await ActivityDailyRMBGiftsModel.deleteMany({ roleId });
    await ActivityFirstGiftModel.deleteMany({ roleId });
    await ActivityGrowthModel.deleteMany({ roleId });
    await ActivityGrowthPointModel.deleteMany({ roleId });
    await ActivityGrowthFundModel.deleteMany({ roleId });
    await ActivityMonopolyModel.deleteMany({ roleId });
    await ActivityMonopolyLandModel.deleteMany({ roleId });
    await ActivityMonthlyTicketModel.deleteMany({ roleId });
    await ActivityNewHeroGiftModel.deleteMany({ roleId });
    await ActivityNewHeroGKModel.deleteMany({ roleId });
    await ActivityPopUpShopModel.deleteMany({ roleId });
    await ActivityRechargeMoneyModel.deleteMany({ roleId });
    await ActivityRefreshShopModel.deleteMany({ roleId });
    await ActivityRefreshTaskModel.deleteMany({ roleId });
    await ActivityRefreshTaskPointModel.deleteMany({ roleId });
    await ActivitySelfServiceModel.deleteMany({ roleId });
    await ActivitySelfServiceGoodsModel.deleteMany({ roleId });
    await ActivitySelfServiceShopModel.deleteMany({ roleId });
    await ActivityShopModel.deleteMany({ roleId });
    await ActivitySignInModel.deleteMany({ roleId });
    await ActivityTaskPointModel.deleteMany({ roleId });
    await ActivityThirtyDaysModel.deleteMany({ roleId });
    await ActivityThirtyDaysPointRewardModel.deleteMany({ roleId });
    await ActivityTreasureHuntFirstPageModel.deleteMany({ roleId });
    await ActivityTreasureHuntShopModel.deleteMany({ roleId });
    await ActivityTreasureHuntTaskModel.deleteMany({ roleId });
    await ActivityTreasureHuntTreasureShopModel.deleteMany({ roleId });
    await ActivityVipRechargeMoneyModel.deleteMany({ roleId });
    await BattleDropModel.deleteMany({ roleId });
    await BattleRecordModel.deleteMany({ roleId });
    await BattleSweepRecordModel.deleteMany({ roleId });
    await ChatInfoModel.deleteMany({ roleId });
    await ChatInfoModel.updateMany({ 'recentPrivateChats.targetRoleId': roleId }, { $pull: { recentPrivateChats: { targetRoleId: roleId } } });
    await DailyRecordModel.deleteMany({ roleId });
    await DungeonFirstModel.deleteMany({ roleId });
    await JewelModel.deleteMany({ roleId });
    await EquipPrintDropModel.deleteMany({ roleId });
    await EventRecordModel.deleteMany({ roleId });
    await ExpeditionPointModel.deleteMany({ roleId });
    await ExpeditionRecordModel.deleteMany({ roleId });
    await ExpeditionWarRecordModel.deleteMany({ roleId });
    await FriendApplyModel.deleteMany({ roleId });
    await FriendApplyModel.deleteMany({ frdRoleId: roleId });
    await FriendPointModel.deleteMany({ roleId });
    await FriendPresentLogModel.deleteMany({ roleId });
    await FriendPresentLogModel.deleteMany({ hisRoleId: roleId });
    await FriendRelationModel.deleteMany({ roleId });
    await FriendRelationModel.updateMany({ 'friends.roleId': roleId }, { $pull: { friends: { roleId }} });
    await FriendRelationModel.updateMany({ 'blacklist.roleId': roleId }, { $pull: { blacklist: { roleId }} });
    await FriendShipModel.deleteMany({ roleIdA: roleId });
    await FriendShipModel.deleteMany({ roleIdB: roleId });
    await GroupMailModel.updateMany({ 'roleStatus.roleId': roleId }, { $pull: { roleStatus: { roleId } } });
    await GroupMailModel.deleteMany({ roleId });
    await GroupMailModel.deleteMany({ targetRoleId: roleId });
    await ActivityTaskPassModel.deleteMany({ roleId });
    let userGuild = await UserGuildModel.getMyGuild(roleId);
    if(userGuild) {
        if(userGuild.auth == 1) {
            const guild = await GuildModel.dismiss(userGuild.guildCode, role.serverId);
            await UserGuildModel.dismiss(userGuild.guildCode);
            const { members } = guild;
            await RoleModel.dissmissGuild(members);
            await UserGuildApplyModel.deleteApplyByGuild(userGuild.guildCode);

        } else {
            await GuildModel.update({ members: { $in: [roleId] } }, { $pull: { members: roleId }, $inc: { memberCnt: -1, managerCnt: userGuild.auth == 2? -1: 0, guildCe: -role.ce }, $set: { isMemberMax: false } })
        }
    }
    await GuildModel.updateMany({ invitedMembers: { $in: [roleId] } }, { $pull: { invitedMembers: roleId } });
    await GuildRecModel.deleteMany({ roleId });
    await HangUpSpdUpRecModel.deleteMany({ roleId });
    await HangUpRecordModel.deleteMany({ roleId });
    await HeroModel.deleteMany({ roleId });
    await ItemModel.deleteMany({ roleId });
    await MailModel.deleteMany({ roleId });
    await MessageModel.deleteMany({ roleId });
    await MessageModel.deleteMany({ targetRoleId: roleId });
    await PrivateMessageModel.deleteMany({ roleId });
    await PrivateMessageModel.deleteMany({ targetRoleId: roleId });
    await PvpDefenseModel.deleteMany({ roleId });
    await RScriptRecordModel.deleteMany({ roleId });
    await SchoolModel.deleteMany({ roleId });
    await ScriptBarrageModel.deleteMany({ roleId });
    await SearchRecordModel.deleteMany({ roleId });
    await ServerMailModel.updateMany({ 'roleStatus.roleId': roleId }, { $pull: { roleStatus: { roleId } } });
    await SkinModel.deleteMany({ roleId });
    await TowerRecordModel.deleteMany({ roleId });
    await TowerTaskRecModel.deleteMany({ roleId });
    await UserGachaModel.deleteMany({ roleId });
    await UserGachaRecModel.deleteMany({ roleId });
    await UserGuildModel.deleteMany({ roleId });
    await UserGuildActivityRecModel.deleteMany({ roleId });
    await UserGuildApplyModel.deleteMany({ roleId });
    await UserOrderModel.deleteMany({ roleId });
    await UserShopModel.deleteMany({ roleId });
    await UserTaskModel.deleteMany({ roleId });
    await UserTaskHistoryModel.deleteMany({ roleId });
    await UserTaskRecModel.deleteMany({ roleId });
    await WishPoolReportModel.deleteMany({ wishRoleId: roleId});
    await WishPoolReportModel.deleteMany({ dntRoleId: roleId});
    await RoleCeModel.deleteMany({ roleId });
    await LadderMatchModel.deleteMany({ roleId });
    }

    let doc = new RoleModel();
    const update = Object.assign(doc.toJSON(), pick(role, ['serverType', 'userInfo', 'seqId', 'serverId']), { roleName: role.roleId });
    delete update._id;

    await RoleModel.updateMany({ roleId }, { $set: update });
    return true;
}


//数据格式转换'类型&id&数量|类型&id&数量|' ->> Array<RewardParam> 活动奖励
export function stringToRewardParam(rewardStr: string): Array<RewardParam> {
    let result = new Array<{ type: number, id: number, count: number }>();
    if (!rewardStr) return result;
    let decodeArr = decodeArrayListStr(rewardStr);
    for (let [type, id, count] of decodeArr) {
        if (isNaN(parseInt(type)) || isNaN(parseInt(id)) || isNaN(parseInt(count))) {
            throw new Error('data table format wrong');
        }
        result.push({ type: parseInt(type), id: parseInt(id), count: parseInt(count) });
    }
    return result
}

//表中的奖励数据(包括礼包)转换成具体对应奖励物品的实例
export function rewardItemData(reward: Array<RewardParam>) {
    let goods: Array<RewardInter> = [];
    let heroes: Array<CreateHeroParam> = [];
    for (let obj of reward) {
        switch (obj.type) {
            case ACTIVITY_RESOURCES_TYPE.HERO:
                heroes.push({ hid: obj.id, count: obj.count })
                break;
            case ACTIVITY_RESOURCES_TYPE.GOODS:
                goods.push({ id: obj.id, count: obj.count })
                break;
            case ACTIVITY_RESOURCES_TYPE.GIFTPACKAGE://配置成礼包会立刻兑换，配置成物品会把礼包放入背包中
                let giftPackageData = gameData.giftPackage.get(1)//gameData.giftPackage.get(goodData.gift);//礼包数据
                let giftReward = rewardItemData(giftPackageData.reward)
                goods = goods.concat(giftReward.goods)
                heroes = heroes.concat(giftReward.heroes)
                break;
            default:
                break;
        }
    }
    return { goods, heroes }
}

export function stringWithTypeToRewardInter(str: string): Array<RewardInter> {
    let reward = stringToRewardParam(str);
    let item = rewardItemData(reward);
    return item.goods||[];
}
