import { Application, BackendSession, pinus, HandlerService, } from 'pinus';
import { UserGuildModel } from '../../../db/UserGuild';
import { resResult } from '../../../pubUtils/util';
import { STATUS, GUILD_OPERATE, TASK_TYPE, ITEM_CHANGE_REASON, ITID, CONSUME_TYPE } from '../../../consts';
import { GuildRefineModel } from '../../../db/GuildRefine';
import { gameData, getArmyDevelopConsumeById, getGoodById } from '../../../pubUtils/data';
import { nowSeconds } from '../../../pubUtils/timeUtil';
import { handleCost, addItems } from '../../../services/role/rewardService';
import { GuildModel } from '../../../db/Guild';
import { findIndex, findWhere } from 'underscore';
import { lockData } from '../../../services/redLockService';
import { ARMY } from '../../../pubUtils/dicParam';
import { CURRENCY_BY_TYPE, CURRENCY_TYPE } from '../../../consts/constModules/itemConst';
import { checkEquipProduceStructureLv, openGuildRefine, refreshRefinCnt } from '../../../services/guildRefineService';
import { DATA_NAME } from '../../../consts/dataName';
import { checkTask } from '../../../services/task/taskService';
import { guildInter } from '../../../pubUtils/interface';
import { DicArmyDevelopConsume } from '../../../pubUtils/dictionary/DicArmyDevelopConsume';

export default function (app: Application) {
    new HandlerService(app, {});
    return new GuildRefineHandler(app);
}

export class GuildRefineHandler {
    constructor(private app: Application) {

    }
    /**
     * 获得科技树信息
     * @param msg 
     * @param session 
     */
    async getRefine(msg: guildInter & {}, session: BackendSession) {
        const { myUserGuild: userGuild } = msg;
        const { guildCode: code } = userGuild;
        let guildRefine = await GuildRefineModel.getRefine(code);
        if (!guildRefine) {
            guildRefine = await openGuildRefine(code);
        }
        let { refineCnt } = refreshRefinCnt(userGuild);
        return resResult(STATUS.SUCCESS, { scienceTrees: guildRefine.scienceTrees, refineCnt });
    }
    /**
     * 炼器
     * @param msg 
     * @param session 
     */
    async refine(msg: guildInter & { id: number, count: number }, session: BackendSession) {
        let { id, count, myUserGuild: userGuild } = msg;
        const roleId: string = session.get('roleId');
        const sid: string = session.get('sid');
        const roleName: string = session.get('roleName');
        const serverId: number = session.get('serverId');
        
        let dicGoods = gameData.goods.get(id);
        if(!dicGoods) return resResult(STATUS.DIC_DATA_NOT_FOUND);
        let dicItid = ITID.get(dicGoods.itid);
        if(!dicItid || dicItid.type != CONSUME_TYPE.DRAWING) return resResult(STATUS.GUILD_CANNOT_REFINE_THIS);

        let { guildCode: code } = userGuild;

        let guildRefine = await GuildRefineModel.getRefine(code);
        if(!guildRefine) return resResult(STATUS.GUILD_PERSITION_TREE_NOT_LIGHT);

        let { scienceTrees } = guildRefine;
        let dicDevelopConsume: DicArmyDevelopConsume;
        for(let scienceTree of scienceTrees) {
            if(scienceTree.endTime && scienceTree.endTime >= nowSeconds()) continue; // 没有炼完
            let _dicDevelopConsume = getArmyDevelopConsumeById(scienceTree.id);
            if(_dicDevelopConsume.quality != dicGoods.quality) continue; // 品质错误
            if(!dicDevelopConsume || dicDevelopConsume.qualityLevel < _dicDevelopConsume.qualityLevel) { // 选择等级最高的
                dicDevelopConsume = _dicDevelopConsume;
            }
        }
        if(!dicDevelopConsume) return resResult(STATUS.GUILD_CANNOT_REFINE_THIS);

        let { refineCnt, refRefineTime } = refreshRefinCnt(userGuild);
        let curQualityCnt = refineCnt.find(cur => cur.quality == dicGoods.quality);
        let myCnt = curQualityCnt?.count||0;
        if(myCnt + count > dicDevelopConsume.max) return resResult(STATUS.GUILD_REFINE_CNT_MAX);
        if(!curQualityCnt) {
            refineCnt.push({ quality: dicGoods.quality, count });
        } else {
            curQualityCnt.count += count;
        }

        let result = await handleCost(roleId, sid, dicDevelopConsume.honourConsume.map(cur=> ({...cur, count: cur.count * count })), ITEM_CHANGE_REASON.REFINE_EQUIP);
        if (!result)
            return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);

        await UserGuildModel.updateInfo(roleId, { refineCnt, refRefineTime }, {});

        let goods = await addItems(roleId, roleName, sid, [{ id, count }], ITEM_CHANGE_REASON.REFINE_EQUIP);

        // 任务
        await checkTask(serverId, roleId, sid, TASK_TYPE.GUILD_REFINE, { quality: dicGoods.quality, count });
        return resResult(STATUS.SUCCESS, { goods, refineCnt });
    }
    /**
     * 点亮科技树
     * @param msg 
     * @param session 
     */
    async lightUpTree(msg: guildInter & guildInter & { id: number }, session: BackendSession) {
        let { id } = msg;
        const serverId: number = session.get('serverId');
        const { myUserGuild: userGuild } = msg

        const { guildCode: code } = userGuild;
        let { structure } = await GuildModel.findByCode(code, serverId);
        let dicDevelopConsume = getArmyDevelopConsumeById(id);
        if (!dicDevelopConsume) return resResult(STATUS.WRONG_PARMS);

        let res: any = await lockData(serverId, DATA_NAME.GUILD_REFINE, code);//加锁
        if (!!res.err) return resResult(STATUS.REDLOCK_ERR);

        if(!checkEquipProduceStructureLv(structure, id)) {
            res.releaseCallback();
            return resResult(STATUS.GUILD_EQUIP_PRODUCE_LV_NOT_ENOUGH);
        }

        let guildRefine = await GuildRefineModel.getRefine(code);
        let nowTime = nowSeconds();

        for (let scienceTree of guildRefine.scienceTrees) {
            if (scienceTree.id == id) {//检查是否点亮过
                res.releaseCallback();
                return resResult(STATUS.GUILD_LIGHT_UP_THE_SCIENCETREE);
            }

            if (scienceTree.endTime > nowTime) {
                res.releaseCallback();
                return resResult(STATUS.GUILD_SCIENCETREE_IS_RUNNING);//检查是否有在进行的科技研发，若在研发，不允许研发其他科技树
            }
        }

        for (let prePosition of dicDevelopConsume.prePositions) {
            let preScieceTree = guildRefine.scienceTrees.find(cur => cur.id == prePosition);
            if (!preScieceTree || preScieceTree.endTime > nowTime) {
                res.releaseCallback();
                return resResult(STATUS.GUILD_PERSITION_TREE_NOT_LIGHT);//前置科技树未点亮
            }
        }
        //点亮消耗
        const costResult = await GuildModel.costFund(code, dicDevelopConsume.fundConsume);
        if (!costResult) {
            res.releaseCallback();
            return resResult(STATUS.GUILD_FUND_NOT_ENOUGH);
        }
        let scienceTree = { id, endTime: nowTime + dicDevelopConsume.timeConsume, assistRoleIds: [] }
        let { scienceTrees } = await GuildRefineModel.pushRefine(code, scienceTree);
        res.releaseCallback();
        return resResult(STATUS.SUCCESS, { scienceTrees });
    }
    /**
     * 协助点亮科技树
     * @param msg 
     * @param session 
     */
    async assistRefine(msg: guildInter & { id: number }, session: BackendSession) {
        let { id, myUserGuild: userGuild } = msg;
        const roleId: string = session.get('roleId');
        const serverId: number = session.get('serverId');
        const sid: string = session.get('sid');
        
        const { guildCode: code } = userGuild;
        let res: any = await lockData(serverId, DATA_NAME.GUILD_ASSIST_REFINE, code);//加锁
        if (!!res.err)
            return resResult(STATUS.REDLOCK_ERR);
        let guildRefine = await GuildRefineModel.getRefine(code);

        let index = findIndex(guildRefine.scienceTrees, { id });
        if (index == -1) {
            res.releaseCallback();
            return resResult(STATUS.WRONG_PARMS);
        }
        let scienceTree = guildRefine.scienceTrees[index];
        if (scienceTree.assistRoleIds.indexOf(roleId) != -1) {
            res.releaseCallback();
            return resResult(STATUS.GUILD_IS_ASSISTED_SCIENCETREE); //玩家已经协助过
        }
        if (scienceTree.assistRoleIds.length >= ARMY.ARMY_DEVELOPMENT_SPEEDTMES) {
            res.releaseCallback();
            return resResult(STATUS.GUILD_REACH_MAX_ASSIST_COUNT); //协助的人数已经达到最大
        }
        let result = await handleCost(roleId, sid, [{ id: CURRENCY_BY_TYPE.get(CURRENCY_TYPE.GOLD), count: ARMY.ARMY_DEVELOPMENT_SPEEDCOST }], ITEM_CHANGE_REASON.ASSIST_REFINE);
        if (!result) {
            res.releaseCallback();
            return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);
        }
        scienceTree.assistRoleIds.push(roleId);
        scienceTree.endTime = scienceTree.endTime - ARMY.ARMY_DEVELOPMENT_SPEED * 60;
        let { scienceTrees } = await GuildRefineModel.updateRefine(code, { scienceTrees: guildRefine.scienceTrees })
        res.releaseCallback();

        // 任务
        await checkTask(serverId, roleId, sid, TASK_TYPE.GUILD_ASSIST_REFINE);

        return resResult(STATUS.SUCCESS, { scienceTrees });
    }
}