import { ACTIVITY_TYPE, HANG_UP_CONSTS, ITEM_CHANGE_REASON, MAIL_TYPE, REFRESH_TIME, STATUS } from '../../consts';
import { ActivityModel, ActivityModelType } from '../../db/Activity';
import { ActivityMonthlyTicketModel, ActivityMonthlyTicketModelType } from '../../db/ActivityMonthlyTicket';
import { RewardParam } from '../../domain/activityField/rewardField';
import { MonthlyTicketData } from '../../domain/activityField/monthlyTicketField';
import { addReward, stringToRewardParam } from './giftPackageService';
import moment = require('moment');
import { ServerlistModel } from '../../db/Serverlist';
import { sendMailByContent } from './../mailService';
import { RoleModel, RoleType } from '../../db/Role';
import { getActivitiesByType, getActivityById } from './activityService';
import { RewardInter } from '../../pubUtils/interface';
import { DUNGEON_CONST, PVP, VIP } from '../../pubUtils/dicParam';
import { cal,  } from '../../pubUtils/util';
import { stringWithTypeToRewardInter } from '../../pubUtils/roleUtil';
import { pinus } from 'pinus';
import { getGoldId } from '../role/rewardService';
import { getRoleCreateTime, getServerCreateTime } from '../redisService';

/**
   * 获取活动数据
   *
   * @param {number} serverId 区Id
   * @param {number} type 活动类型 ACTIVITY_TYPE
   * @param {string} roleId 角色Id
   *
   */

export async function monthlyTicketActivity(serverId: number, roleId: string, type: number) {
    let activityArray = await getActivitiesByType(serverId, type);
    activityArray = activityArray.sort((a, b) => {
        return b.activityId - a.activityId
    });
    if (activityArray.length == 0) {
        return null;
    }
    let activityData = activityArray[0];
    let playerRecord: ActivityMonthlyTicketModelType = await ActivityMonthlyTicketModel.findMonthlyTicket(serverId, roleId, activityData.activityId);
    let createTime = await getRoleCreateTime(roleId);
    let serverTime = await getServerCreateTime(serverId);
    let playerData = new MonthlyTicketData(activityData, createTime, serverTime);
    playerData.setPlayerRecords(playerRecord);

    if ((playerData.price > 0 && playerData.isOpen) || playerData.price === 0) {
        if (playerData.todayIndex - 1 > playerData.dayIndex) {//过期还没领取
            //下发邮件奖励
            for (let i = playerData.dayIndex + 1; i < playerData.todayIndex; i++) {
                let goods = stringWithTypeToRewardInter(playerData.baseReward)
                await sendMailByContent(MAIL_TYPE.MONTHLY_REWARD, roleId, { params: [], goods });
            }
            await ActivityMonthlyTicketModel.setDayIndex(serverId, roleId, playerData.activityId, playerData.todayIndex - 1);
            playerData.dayIndex = playerData.todayIndex - 1;
        }
    }
    return playerData;
}

/**
   * 玩家活动数据
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   *
   */
export async function getPlayerMonthlyTicketData(activityId: number, serverId: number, roleId: string) {
    let activityData = await getActivityById(activityId);
    let playerRecord: ActivityMonthlyTicketModelType = await ActivityMonthlyTicketModel.findMonthlyTicket(serverId, roleId, activityId);
    let createTime = await getRoleCreateTime(roleId);
    let serverTime = await getServerCreateTime(serverId);
    let playerData = new MonthlyTicketData(activityData, createTime, serverTime);
    playerData.setPlayerRecords(playerRecord);
    return playerData;
}

/**
   * 玩家月卡当天的奖励
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   *
   */
export async function getPlayerMonthlyTicketDayReward(roleId: string, roleName: string, sid: string, serverId: number, 
    activityId: number,) {
    let activityData: ActivityModelType = await getActivityById(activityId);
    let createTime = await getRoleCreateTime(roleId);
    let serverTime = await getServerCreateTime(serverId);
    let playerData = new MonthlyTicketData(activityData, createTime, serverTime);

    let playerRecord: ActivityMonthlyTicketModelType = await ActivityMonthlyTicketModel.findMonthlyTicket(serverId, roleId, activityId);
    if (playerData.price > 0 && !playerRecord) {//没有购买过
        return null;
    }

    playerData.setPlayerRecords(playerRecord);
    if ((playerData.price > 0 && playerData.isOpen) || playerData.price == 0) {
        if (playerData.todayIndex > playerData.dayIndex) {//今天还没领取
            await ActivityMonthlyTicketModel.setDayIndex(serverId, roleId, activityId, playerData.todayIndex);
            let rewardParamArr: Array<RewardParam> = stringToRewardParam(playerData.baseReward);
            let result = await addReward(roleId, roleName, sid, serverId, rewardParamArr, ITEM_CHANGE_REASON.MONTHLY_TICKET_DAILY)
            return result
        }
    }
    return null
}

/**
   * 结算首次购买月卡的奖励
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   * @param {string} productID 商品ID
   *
   */
export async function makeMonthlyTicketReward(roleId: string, roleName: string, sid: string, serverId: number,
    activityId: number, productID: string) {
    let activityData: ActivityModelType = await getActivityById(activityId);
    if (activityData.type !== ACTIVITY_TYPE.MONTHLY_TICKET_1 && activityData.type !== ACTIVITY_TYPE.MONTHLY_TICKET_2) {
        return STATUS.ACTIVITY_TYPE_ERROR;
    }

    let createTime = await getRoleCreateTime(roleId);
    let serverTime = await getServerCreateTime(serverId);
    let playerData = new MonthlyTicketData(activityData, createTime, serverTime);

    let endTime = playerData.isForever? moment(playerData.endTime).toDate(): moment(new Date()).startOf('d').add(playerData.days, 'day').add(REFRESH_TIME, 'h').toDate();
    console.log('endTime', playerData.isForever, moment(new Date()).startOf('d'), endTime, playerData.days)
    await ActivityMonthlyTicketModel.buyMonthlyTicket(serverId, roleId, activityId, activityData.type, endTime, playerData.isForever)
    if(activityData.type == ACTIVITY_TYPE.MONTHLY_TICKET_2) {
        let role = await RoleModel.buyForeverTicket(roleId);
        if(sid) await pinus.app.rpc.connector.connectorRemote.setOtherUserSession.toServer(sid,[{ roleId, vipStartTime: role.vipStartTime }]);
    }
    let firstReward = playerData.firstReward;
    let rewardParamArr: Array<RewardParam> = stringToRewardParam(firstReward);
    let result = await addReward(roleId, roleName, sid, serverId, rewardParamArr, ITEM_CHANGE_REASON.MONTHLY_TICKET_FIRST)
    return {
        code: 0,
        data: Object.assign(result, { item: { isOpen: true, todayIndex: 1 }, activityId: activityData.activityId })
    }
}

// 月卡权限

// 军团捐献消耗
export function getVipDonateConsume(originConsume: RewardInter, vipStartTime: number) {
    if(vipStartTime > 0) {
        if(originConsume.id == getGoldId()) {
            return [{ id: originConsume.id, count: Math.floor(originConsume.count * VIP.VIP_GUILD_DONATE_COST_GOLD_RATIO) }];
        } else {
            return [originConsume];
        }
    } else {
        return [originConsume];
    }
}

export function getVipHungupReward(startTime: number, endTime: number, baseReward: RewardInter[], notReceivedGoods: {gid: number, count: number}[], vipStartTime: number) {
    let multi = Math.floor((endTime - startTime) / HANG_UP_CONSTS.UNIT_TIME);
    if(vipStartTime > 0) {
        if(vipStartTime > startTime) { // 开始挂机之后买的月卡
            let isNotVipNum = Math.floor((vipStartTime - startTime) / HANG_UP_CONSTS.UNIT_TIME); // 不是vip的时间段数
            let isVipNum = multi - isNotVipNum; // 是vip的时间段数
            multi = cal.add(isNotVipNum, cal.mul(isVipNum, VIP.VIP_TOWER_HUNG_UP_RATIO));
        } else {
            multi = cal.mul(multi, VIP.VIP_TOWER_HUNG_UP_RATIO);
        }
    }

    let needReceiveGoods: {gid: number, count: number}[] = [];// 由于小数，未能领取的奖励
    let timeReward: {id: number, count: number}[] = [];  // 本次奖励
    for (let { id, count } of baseReward) { 
        let newCount = cal.mul(count, multi);
        let oldGoods = notReceivedGoods.find(cur => cur.gid == id);
        if (oldGoods) newCount = cal.add(newCount, oldGoods.count);
        let roundCount = Math.floor(newCount);
        if (newCount > roundCount) {
            needReceiveGoods.push({ gid: id, count: cal.sub(newCount, roundCount) });
        }
        if (roundCount > 0) {
            timeReward.push({ id, count: roundCount })
        }
    }
    return { needReceiveGoods, timeReward }
}

export async function getVipPvpChallengeMaxCnt(roleId: string, vipStartTime?: number) {
    if(vipStartTime == undefined) {
        let role = await RoleModel.findByRoleId(roleId, 'vipStartTime');
        vipStartTime = role.vipStartTime;
    }
    let count = PVP.PVP_CHALLENGE_COUNTS;
    if(vipStartTime > 0) {
        count += VIP.VIP_PVP_CHALLENGE_COUNTS_ADD;
    }
    return count;
}

export function getVipDailyCnt(timesPerDay: number, role: RoleType) {
    let vipStartTime = role.vipStartTime;
    if(vipStartTime > 0) {
        timesPerDay += VIP.VIP_DAILY_TIMERS_PER_DAY_ADD;
    }
    return timesPerDay
}

export function getVipDungeonCnt(vipStartTime: number) {
    let count = DUNGEON_CONST.DUNGEON_CONST_FREE;
    if(vipStartTime > 0) {
        count += VIP.VIP_DUNGEON_CONST_FREE_ADD;
    }
    return count
}

export function getVipRegretCnt(vipStartTime: number) {
    let count = VIP.VIP_REGRET_CNT_WITHOUT_VIP;
    if(vipStartTime > 0) {
        count = VIP.VIP_REGRET_CNT_WITH_VIP;
    }
    return count;
}

export function vipCanSkipTower(recommendCeSum: number, heroesCeSum: number, vipStartTime: number) {
    let ratio = vipStartTime > 0? VIP.VIP_TOWER_SKIP_CE_RATIO_WITH_VIP: VIP.VIP_TOWER_SKIP_CE_RATIO_WITHOUT_VIP;
    return heroesCeSum > recommendCeSum * ratio;
}

export function vipCanSkipExpedition(recommendCe: number, topLineupCe: number, vipStartTime: number) {
    return vipStartTime > 0 && topLineupCe > recommendCe * VIP.EXPENDITION_SKIP_CE_RATIO_WITH_VIP; 
}