import { ACTIVITY_TYPE, GROUP_SHOP_PRICE_STATUS, MAIL_TYPE, PUSH_ROUTE } from "../../consts";
import { ActivityModel, ActivityModelType } from "../../db/Activity";
import { ActivityGroupShopRecModel } from "../../db/ActivityGroupShopRec";
import { ActivityGroupShopRefundModel, RefundRec } from "../../db/ActivityGroupShopRefund";
import { ActivityGroupShopUserRecModel } from "../../db/ActivityGroupShopUserRec";
import { GroupShopData } from "../../domain/activityField/groupShopField";
import { gameData } from "../../pubUtils/data";
import { RewardInter } from "../../pubUtils/interface";
import { sendMailByContent } from "../mailService";
import { sendMessageToGroupShopWithSuc } from "../pushService";
import { getRoleCreateTime, getServerCreateTime } from "../redisService";
import { getGoldObject } from "../role/rewardService";
import { getActivityById } from "./activityService";

/**
   * 玩家活动数据
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   *
   */
 export async function getGroupShopData(activityId: number, roleId: string) {
    let activityData = await getActivityById(activityId);
    if(!activityData) return null
    let createTime = await getRoleCreateTime(roleId);

    let playerData = new GroupShopData(activityData, createTime, 0);
    let serverRecords = await ActivityGroupShopRecModel.findByActivity(activityId);
    playerData.setRecords(serverRecords);
    let playerRecords = await ActivityGroupShopUserRecModel.findByActivityAndRoleId(activityId, roleId);
    playerData.setPlayerRecord(playerRecords);

    return playerData;
}

export async function getGroupShopDataShow(activityId: number, roleId: string) {
    let playerData = await getGroupShopData(activityId, roleId);
    if(playerData && playerData.canShow && playerData.canShow()) {
        return playerData.getShowResult();
    }
    return null
}

export function getGroupShopPriceStatus(clientPrice: number, price: number) {
    if(clientPrice == price) return GROUP_SHOP_PRICE_STATUS.NORMAL;
    if(clientPrice < price) return GROUP_SHOP_PRICE_STATUS.NOT_ENOUGH;
    return GROUP_SHOP_PRICE_STATUS.OVER;
}

export async function getGroupShopServerData(activityData: ActivityModelType) {
    let playerData = new GroupShopData(activityData, 0, 0);
    let serverRecords = await ActivityGroupShopRecModel.findByActivity(activityData.activityId);
    playerData.setRecords(serverRecords);

    return playerData;
}

export async function getGroupShopTimers(activity: ActivityModelType) {
    if(!activity) return [];
    let playerData = await getGroupShopServerData(activity);
    return playerData?.timer||[];
}

export async function setGroupShopToSetSum(arr: { activityId: number, itemId: number, sum: number }[]) {
    console.log('###### setGroupShopToSetSum', JSON.stringify(arr));
    for(let { activityId, itemId, sum } of arr) {
        let serverRecord = await ActivityGroupShopRecModel.setSum(activityId, itemId, sum);
        if(serverRecord) {
            let activityData = await getActivityById(activityId);
            let playerData = new GroupShopData(activityData, 0, 0);
            playerData.setRecords([serverRecord]);
            
            let item = playerData.findItemById(itemId);
            let nextDiscount = item.getCurDiscount();
            // 推送频道
            await sendMessageToGroupShopWithSuc(PUSH_ROUTE.GROUP_SHOP_UPDATE, { activityId, sum, itemId, curDiscount: nextDiscount });
        }
    }
}

export async function refundGroupShop(isDebug = false) {
    console.log('###### refundGroupShop')
    let activities = await ActivityModel.findActivityByType(ACTIVITY_TYPE.GROUP_SHOP);

    for(let activityData of activities) {
        let hasRefund = await ActivityGroupShopRefundModel.check(activityData.activityId);
        if(!isDebug && hasRefund) continue;

        let playerData = await getGroupShopServerData(activityData);
        if(!isDebug && playerData.endTime >= Date.now()) continue;

        let items = playerData.items||[];
        let refundRecs: RefundRec[] = [];
        for(let item of items) {
            let curDiscount = item.getCurDiscount();
            let playerRecords = await ActivityGroupShopUserRecModel.findByPrice(activityData.activityId, item.itemId, item.getCurDiscount().price);
            for(let { roleId, records } of playerRecords) {
                let rewards: {id: number, count: number}[] = [], sumGold = 0;
                for(let { price, buyCnt } of records) {
                    if(price <= curDiscount.price) continue;
                    let diff = (price - curDiscount.price) * buyCnt;
                    rewards.push(getGoldObject(diff));
                    sumGold += diff;
                    refundRecs.push({ roleId, itemId: item.itemId, diff });
                }
                let itemName = gameData.goods.get(item.id)?.name?? `${item.id}`;
                let resultDiscount = curDiscount.discount;
                await sendMailByContent(MAIL_TYPE.GROUP_SHOP_REFUND, roleId, { goods: rewards, params: [itemName, `${resultDiscount}`, `${sumGold}`] });
            }
        }
        console.log('###### refundGroupShop refund complete', activityData.activityId)
        await ActivityGroupShopRefundModel.refund(activityData.activityId, refundRecs);
    }
}