import { ACTIVITY_TYPE, ITEM_CHANGE_REASON, MAIL_TYPE, 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, stringToRewardInter, stringToRewardParam } from './giftPackageService';
import moment = require('moment');
import { ServerlistModel } from '../../db/Serverlist';
import { sendMailByContent } from './../mailService';
import { RoleModel } from '../../db/Role';
import { getActivityById } from './activityService';

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

export async function monthlyTicketActivity(serverId: number, roleId: string, type: number) {
    let { activityGroupId } = await ServerlistModel.findByServerId(serverId);
    let activityArray: ActivityModelType[] = await ActivityModel.findOpenActivityByType(activityGroupId, type, new Date())
    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 RoleModel.findByRoleId(roleId);
    let playerData = new MonthlyTicketData(activityData, createTime);
    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 = stringToRewardInter(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 RoleModel.findByRoleId(roleId);
    let playerData = new MonthlyTicketData(activityData, createTime);
    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 RoleModel.findByRoleId(roleId);
    let playerData = new MonthlyTicketData(activityData, createTime);

    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 RoleModel.findByRoleId(roleId);
    let playerData = new MonthlyTicketData(activityData, createTime);

    let endTime = moment(new Date()).startOf('d').add(playerData.days, 'day').toDate();
    console.log('endTime', moment(new Date()).startOf('d'), endTime, playerData.days)
    await ActivityMonthlyTicketModel.buyMonthlyTicket(serverId, roleId, activityId, activityData.type, endTime)

    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 })
    }
}
