// 每个农庄/每个田一条记录，这个田被其他人用了之后会覆盖

import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType, } from '@typegoose/typegoose';
import { getFutureTime, nowSeconds } from '../pubUtils/timeUtil';
import { GVG } from '../pubUtils/dicParam';
import { GVG_RESOURCE_TYPE } from '../consts';

class AddType {
    @prop({ required: true })
    addType: number;          // 加成类型
    @prop({ required: true })
    roleId: string;          // 加成玩家
}

@index({ leagueCode: 1, configId: 1 })
@index({ fieldId: 1 })
@index({ batchCode: 1 })
export default class GVGLeagueFarm extends BaseModel {

    @prop({ required: true })
    leagueCode: string;          // 联军唯一code

    @prop({ required: true })
    configId: number;

    @prop({ required: true })
    farmId: number;              // 农庄id

    @prop({ required: true })
    type: number;              // 农庄类型

    @prop({ required: true })
    fieldId: number;              // 农庄id

    @prop({ required: true })
    unlockTime: number;          // 解锁时间，农场：打开界面时预锁定一批填，种下去之后锁定时间延长到收获时间，林场&矿场：开始小游戏时锁定时间

    @prop({ required: true })
    lockRoleId: string;          // 锁定的人

    @prop({ required: true })
    lockRoleName: string;

    @prop({ required: true })
    harvestTime: number;         // 收获时间，农庄：种植下去后将时间更新，收获之后设为0，林场&矿场：小游戏结束时更新

    @prop({ required: true })
    seedType: number;            // 仅农庄使用，实际种的种子类型

    @prop({ required: true })
    addType: number;             // 仅农庄使用，当前种子加成

    @prop({ required: true, type: AddType, _id: false })
    addTypes: AddType[];             // 仅农庄使用，历史种子加成

    @prop({ required: true })
    batchCode: string;             // 批量号

    @prop({ required: true })
    itemId: number;            // 仅矿山使用，使用的铲子id

    @prop({ required: true })
    output: number;             // 产量，农庄：种下去时可以预估产量，林场&矿场：小游戏结束时根据结果更新

    @prop({ required: true })
    outputStr: string;             // 产量计算公式

    @prop({ required: true })
    index: number;             // 种植位置

    public static async findByType(configId: number, leagueCode: string, type: number) {
        const result: GVGLeagueFarmType[] = await GVGLeagueFarmModel.find({ configId, leagueCode, type }).select('-_id').lean();
        return result;
    }

    public static async findByFarmId(configId: number, leagueCode: string, farmId: number) {
        const result: GVGLeagueFarmType[] = await GVGLeagueFarmModel.find({ configId, leagueCode, farmId }).select('-_id').lean();
        return result;
    }

    public static async findLockedByFarmId(configId: number, leagueCode: string, farmId: number) {
        const result: GVGLeagueFarmType[] = await GVGLeagueFarmModel.find({ configId, leagueCode, farmId, unlockTime: { $gte: nowSeconds() }}).select('-_id').lean();
        return result;
    }

    public static async findPlantedByFarmId(configId: number, leagueCode: string, farmId: number) {
        const result: GVGLeagueFarmType[] = await GVGLeagueFarmModel.find({ configId, leagueCode, farmId, unlockTime: { $gte: nowSeconds() }}).select('-_id').lean();
        return result;
    }

    public static async findByFieldIds(configId: number, leagueCode: string, farmId: number, fieldIds: number[]) {
        const result: GVGLeagueFarmType[] = await GVGLeagueFarmModel.find({ configId, leagueCode, farmId, fieldId: { $in: fieldIds } }).select('-_id').lean();
        return result;
    }

    /**
     * 首次打开页面时锁定田
     * @param configId 
     * @param leagueCode 
     * @param lands [{fieldId: number, time: number, addType: number}]  fieldId:田地id， time: 锁定时间 addType: 种子加成
     * @returns 
     */
    public static async lockFields(configId: number, leagueCode: string, farmId: number, type: number, roleId: string, roleName: string, lands: { fieldId: number, addType: number }[]) {
        // 先创建
        await GVGLeagueFarmModel.bulkWrite(lands.map(({ fieldId }) => {
            return { updateOne: { filter: { configId, leagueCode, farmId, fieldId }, update: { $setOnInsert: { unlockTime: 0, harvestTime: 0, seedType: 0, addType: 0, addTypes: [], type, index: 0 } }, upsert: true} }
        }));
        const result = await GVGLeagueFarmModel.bulkWrite(lands.map(({ fieldId, addType }) => {
            if(addType > 0) {
                return { updateOne: { filter: { configId, leagueCode, farmId, fieldId, $or:[{ unlockTime: { $lt: nowSeconds() }}, {lockRoleId: roleId } ] }, update: { $set: { addType, unlockTime: nowSeconds()  + GVG.GVG_FARM_LOCK_TIME, lockRoleId: roleId, lockRoleName: roleName }, $push: { addTypes: { addType, roleId } } } } }
            } else {
                return { updateOne: { filter: { configId, leagueCode, farmId, fieldId, $or:[{ unlockTime: { $lt: nowSeconds() }}, {lockRoleId: roleId } ] }, update: { $set: { addType, unlockTime: nowSeconds()  + GVG.GVG_FARM_LOCK_TIME, lockRoleId: roleId, lockRoleName: roleName } } } }
            }
        }));
        return result;
    }

    public static async findByFarmIdAndRoleId(configId: number, leagueCode: string, farmId: number, roleId: string) {
        const result: GVGLeagueFarmType[] = await GVGLeagueFarmModel.find({ configId, leagueCode, farmId, lockRoleId: roleId, unlockTime: { $gte: nowSeconds() } }).sort({ index: -1, fieldId: 1 }).select('-_id -createdAt -updatedAt -__v -leagueCode -configId -roleId').lean();
        return result;
    }

    public static async plant(configId: number, leagueCode: string, farmId: number, fields: { fieldId: number, seedType: number, time: number, output: number, outputStr: string, index: number }[], roleId: string) {
        const fieldResult: GVGLeagueFarmType[] = [];
        for(let { fieldId, seedType, time, output, outputStr, index } of fields) {
            let obj: GVGLeagueFarmType = await GVGLeagueFarmModel.findOneAndUpdate({ configId, leagueCode, farmId, fieldId, lockRoleId: roleId }, {$set: { seedType, unlockTime: getFutureTime(), harvestTime: nowSeconds() + time, output, outputStr, index }}, { new: true }).lean();
            if(obj) fieldResult.push(obj);
        }
        return fieldResult;
    }

    public static async harvest(configId: number, leagueCode: string, farmId: number, fieldIds: number[], roleId: string) {
        const fieldResult: GVGLeagueFarmType[] = [], _ids: string[] = [];
        for(let fieldId of fieldIds) {
            let obj: GVGLeagueFarmType = await GVGLeagueFarmModel.findOneAndUpdate(
                { configId, leagueCode, farmId, fieldId, lockRoleId: roleId, harvestTime: { $lt: nowSeconds() } }, 
                { $set: { unlockTime: 0, harvestTime: 0, lockRoleId: '', lockRoleName: '', index: 0 } }, {new: true}).lean();
            if(obj) { fieldResult.push(obj); _ids.push(obj._id);}
        }
        await GVGLeagueFarmModel.updateMany({ _id: { $in: _ids } }, { $set: { seedType: 0 } });
        return fieldResult;
    }

    public static async helpHarvest(configId: number, leagueCode: string, farmId: number, roleId: string) {
        const fieldResult: GVGLeagueFarmType[] = await GVGLeagueFarmModel.find({ configId, leagueCode, farmId, lockRoleId: roleId, harvestTime: { $lt: nowSeconds() } }).lean();
        const _ids = fieldResult.map(cur => cur._id);
        const result = await GVGLeagueFarmModel.updateMany({ _id: { $in: _ids } },
            { $set: { unlockTime: 0, harvestTime: 0, lockRoleId: '', lockRoleName: '', seedType: 0, index: 0 }}, { new: true });
        if(result.modifiedCount == 0) return [];
        return fieldResult
    }

    public static async releaseLock(configId: number, leagueCode: string, farmId: number, roleId: string) {
        await GVGLeagueFarmModel.updateMany({ configId, leagueCode, farmId, lockRoleId: roleId, index: 0 }, { $set: { unlockTime: 0, lockRoleId: '', lockRoleName: '', addType: 0 }, $pull: { addTypes: { roleId } } });
    }

    public static async lockMineOrForestry(configId: number, leagueCode: string, farmId: number, type: number, roleId: string, fieldId: number, itemId: number) {
        // 先创建
        await GVGLeagueFarmModel.findOneAndUpdate({ configId, leagueCode, farmId, fieldId }, { $setOnInsert: { unlockTime: 0, itemId: 0, type } }, { upsert: true });
        let unlockTime = nowSeconds() + (type == GVG_RESOURCE_TYPE.MINERAL? GVG.GVG_MINE_LOCK_TIME: GVG.GVG_FORESTRY_LOCK_TIME);
        const result: GVGLeagueFarmType = await GVGLeagueFarmModel.findOneAndUpdate(
            { configId, leagueCode, farmId, fieldId, $or:[{ unlockTime: { $lt: nowSeconds() } }, {lockRoleId: roleId}] },
            { $set: { unlockTime, lockRoleId: roleId, itemId } },
            { new: true }).lean();
        return result;
    }

    public static async findByField(configId: number, leagueCode: string, farmId: number, fieldId: number) {
        const result: GVGLeagueFarmType = await GVGLeagueFarmModel.findOne({ configId, leagueCode, farmId, fieldId }).lean();
        return result;
    }

    public static async mineOrForestryEnd(configId: number, leagueCode: string, farmId: number, roleId: string, fieldId: number, output: number, outputStr: string) {
        const result: GVGLeagueFarmType = await GVGLeagueFarmModel.findOneAndUpdate(
            { configId, leagueCode, farmId, fieldId, lockRoleId: roleId,unlockTime: { $gte: nowSeconds() } },
            { $set: { output, outputStr, unlockTime: getFutureTime(), harvestTime: nowSeconds() } },
            { new: true }).lean();
        return result;
    }

    public static async setMyHarvestTime(configId: number, leagueCode: string, time: number) {
        console.log(configId, leagueCode, nowSeconds(), time)
        await GVGLeagueFarmModel.updateMany({ configId, leagueCode, harvestTime: { $gt: nowSeconds() } }, { $set: { harvestTime: nowSeconds() + time }});
    }
}

export const GVGLeagueFarmModel = getModelForClass(GVGLeagueFarm);

export interface GVGLeagueFarmType extends Pick<DocumentType<GVGLeagueFarm>, keyof GVGLeagueFarm> {
    id: number;
};
export type GVGLeagueFarmUpdate = Partial<GVGLeagueFarmType>; // 将所有字段变成可选项
