import { ACTIVITY_TYPE, ITEM_CHANGE_REASON, REFRESH_TIME, STATUS } from '../../consts';
import { ActivityModel, ActivityModelType } from '../../db/Activity';
import { ActivitySelfServiceGoodsModel, ActivitySelfServiceGoodsModelType } from '../../db/ActivitySelfServiceGoods';
import { ActivitySelfServiceShopModel, ActivitySelfServiceShopModelType } from '../../db/ActivitySelfServiceShop';
import { ActivitySelfServiceModel } from '../../db/ActivitySelfService';
import { ServerlistModel } from '../../db/Serverlist';
import { RewardParam } from '../../domain/activityField/rewardField';
import { SelfServiceShopData, SelfServiceShopItem } from '../../domain/activityField/selfServiceShopField';
import { addReward, stringToRewardParam } from './giftPackageService';
import moment = require('moment');
import { RoleModel } from '../../db/Role';
import { getActivitiesByType, getActivityById } from './activityService';
import { getRoleCreateTime, getServerCreateTime } from '../redisService';

/**
   * 获取活动数据
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   *
   */
export async function getSelfServiceShopActivityData(serverId: number, roleId: string) {
    let activityArray = await getActivitiesByType(serverId, ACTIVITY_TYPE.SELF_SERVICE_SHOP);
    activityArray = activityArray.sort((a, b) => {
        return b.activityId - a.activityId
    });
    if (activityArray.length > 0) {
        let activityData = activityArray[0];
        let playerData = await getPlayerActivityData(activityData.activityId, serverId, roleId);
        return playerData;
    }
    return null;
}

/**
   * 玩家活动数据
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   *
   */
export async function getPlayerActivityData(activityId: number, serverId: number, roleId: string) {
    let activityData = await getActivityById(activityId);
    let createTime = await getRoleCreateTime(roleId);
    let serverTime = await getServerCreateTime(serverId);
    let playerData = new SelfServiceShopData(activityData, createTime, serverTime);

    let playerRecords: ActivitySelfServiceShopModelType[] = await ActivitySelfServiceShopModel.findDataByPriceType(serverId, activityId, roleId, playerData.roundIndex);

    playerData.setPlayerRecords(playerRecords);
    let playerSelfServerData = await ActivitySelfServiceModel.findData(serverId, activityId, roleId, playerData.roundIndex);
    let buyCount = (playerSelfServerData && playerSelfServerData.unitBuyCount) ? playerSelfServerData.unitBuyCount : 0;
    playerData.unitBuyCount = buyCount;
    let challengeBeginTime = null;
    let challengeEndTime = null;
    let curDate = moment(new Date());
    if (curDate.hour() < REFRESH_TIME) {
        challengeBeginTime = moment(new Date()).startOf('d').add(-1, 'd').add(REFRESH_TIME, 'h').toDate();
        challengeEndTime = moment(challengeBeginTime).add(1, 'd').toDate()
    } else {
        challengeBeginTime = moment(new Date()).startOf('d').add(REFRESH_TIME, 'h').toDate();
        challengeEndTime = moment(challengeBeginTime).add(1, 'd').toDate()
    }
    let records = (playerSelfServerData && playerSelfServerData.challengeRecords) ? playerSelfServerData.challengeRecords : [];
    for (let record of records) {
        // console.log(challengeBeginTime, challengeEndTime, record.time)
        if (record.time >= challengeBeginTime && record.time <= challengeEndTime) {
            playerData.challengeCount++;
        }
    }

    return playerData;
}

/**
   * 结算礼包
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   * @param {number} roundIndex 周期数
   * @param {number} index 货架
   * @param {number} price 价格
   * @param {number} priceType 价格类型
   *
   */

export async function addSelfServiceShopGiftReward(roleId: string, roleName: string, sid: string, serverId: number, activityId: number, roundIndex: number, index: number, item: SelfServiceShopItem) {
    let playerGoods: ActivitySelfServiceGoodsModelType[] = await ActivitySelfServiceGoodsModel.findDataByIndex(activityId, roleId, roundIndex, index);

    let rewardArray: Array<RewardParam> = [];
    for (let obj of playerGoods) {
        let selectedIndex = obj.rewardIndex;
        let cellIndex = obj.cellIndex;
        let giftData = item.findCellIndex(cellIndex);
        let rewards: Array<RewardParam> = stringToRewardParam(giftData.gift);
        rewardArray = rewardArray.concat(rewards[selectedIndex])
    }
    let goodsStr = '';
    for (let obj of rewardArray) {
        goodsStr += `${obj.type}&${obj.id}&${obj.count}|`;
    }
    let result = await addReward(roleId, roleName, sid, serverId, rewardArray, ITEM_CHANGE_REASON.SELF_SERVICE_SHOP_BUY_GIFT);
    //购买记录
    console.log('dddddddd', rewardArray.length, serverId, activityId, roleId, roundIndex, index, goodsStr, JSON.stringify(item))
    await ActivitySelfServiceShopModel.addBuyRecord(serverId, activityId, roleId, roundIndex, index, goodsStr);
    return result
}


/**
   * 购买自选礼包
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   * @param {string} productID 商品ID
   *
   */
export async function makeSelfServerShop(roleId: string, roleName: string, sid: string, serverId: number,
    activityId: number, productID: string) {

    let activityData: ActivityModelType = await getActivityById(activityId);
    if (!activityData) {
        return {
            code: STATUS.ACTIVITY_MISSING,
        }
    }
    let createTime = await getRoleCreateTime(roleId);
    let serverTime = await getServerCreateTime(serverId);
    let playerData = new SelfServiceShopData(activityData, createTime, serverTime);
    let item: SelfServiceShopItem = playerData.getItemByProductID(productID);
    if (!item) {
        return {
            code: STATUS.ACTIVITY_DATA_ERROR,
        }
    }
    if (item.countMax > 0) {//限制购买次数
        let playerRecords: ActivitySelfServiceShopModelType[] = await ActivitySelfServiceShopModel.findDataByIndex(serverId, activityId, roleId, playerData.roundIndex, item.index);
        if (playerRecords.length >= item.countMax) {
            return {
                code: STATUS.ACTIVITY_MAX_COUNT,
            }
        }
    }
    let result = await addSelfServiceShopGiftReward(roleId, roleName, sid, serverId, activityId, playerData.roundIndex, item.index, item);
    item.buyCount += 1;
    return {
        code: 0,
        data: Object.assign(result, { item })
    }
}
