import { Application, BackendSession, pinus } from 'pinus';
import { UserGuildModel } from '../../../db/UserGuild';
import { resResult } from '../../../pubUtils/util';
import { STATUS, GUILD_OPERATE, TASK_TYPE } from '../../../consts';
import { GuildRefineModel } from '../../../db/GuildRefine';
import { getArmyDevelopConsumeById, getGoodById } from '../../../pubUtils/data';
import { nowSeconds } from '../../../pubUtils/timeUtil';
import { handleCost, addItems, checkGoods } from '../../../services/rewardService';
import { GuildModel } from '../../../db/Guild';
import { findIndex, findWhere } from 'underscore';
import { lockData } from '../../../services/redLockService';
import { checkAuth } from '../../../services/guildService';
import { ARMY } from '../../../pubUtils/dicParam';
import { CURRENCY_BY_TYPE, CURRENCY_TYPE } from '../../../consts/constModules/itemConst';
import { openGuildRefine } from '../../../services/guildRefineService';
import { DATA_NAME } from '../../../consts/dataName';
import { checkTask } from '../../../services/taskService';

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

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

    }
    /**
     * 获得科技树信息
     * @param msg 
     * @param session 
     */
    async getRefine(msg: {}, session: BackendSession) {
        const roleId = session.get('roleId');
        let userGuild = await UserGuildModel.getMyGuild(roleId, 'guildCode');
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS); 
        const { guildCode: code } = userGuild;
        let guildRefine = await GuildRefineModel.getRefine(code);
        if (!guildRefine) {
            guildRefine = await openGuildRefine(code);
        }
        return resResult(STATUS.SUCCESS, { scienceTrees: guildRefine.scienceTrees }); 
    }   
    /**
     * 炼器
     * @param msg 
     * @param session 
     */
    async refineEquip(msg: {pid: number}, session: BackendSession) {
        let { pid } = msg;
        const roleId: string = session.get('roleId');
        const sid: string = session.get('sid');
        const roleName: string = session.get('roleName');
        const funcs: number[] = session.get('funcs');
        let pieceInfo = getGoodById(pid);
        let userGuild = await UserGuildModel.getMyGuild(roleId, 'guildCode');
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS); 
        let { guildCode: code } = userGuild;
      
        let { scienceTrees } = await GuildRefineModel.getRefine(code);
        let findDevelopConsume;
        //判断是否可以炼该兵器
        for (let scienceTree of scienceTrees) {
            if (scienceTree.endTime < nowSeconds()) {
                let developConsume = getArmyDevelopConsumeById(scienceTree.id);
                if (developConsume.quality && developConsume.levelMax >= pieceInfo.lvLimited && pieceInfo.lvLimited <= developConsume.levelMin) {
                    findDevelopConsume = developConsume;
                    break;
                }
            }
        }
        if (!findDevelopConsume) 
            return resResult(STATUS.GUILD_NOT_REFINE_THE_EQUIP);
        let result = await handleCost(roleId, sid, findDevelopConsume.honourConsume);
        if(!result) 
            return resResult(STATUS.ROLE_MATERIAL_NOT_ENOUGH);
        let goods = await addItems(roleId, roleName, sid, [{id: pid, count: 1}]);

        // 任务
        await checkTask(roleId, sid, funcs, TASK_TYPE.GUILD_REFINE, 1, true, { quality: pieceInfo.lvLimited });
        return resResult(STATUS.SUCCESS, { goods }); 
    }   
    /**
     * 点亮科技树
     * @param msg 
     * @param session 
     */
    async lightUpTree(msg: {id: number}, session: BackendSession) {
        let { id } = msg;
        const roleId: string = session.get('roleId');
        const serverId: number = session.get('serverId');
        let userGuild = await UserGuildModel.getMyGuild(roleId, 'auth guildCode');
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS); 
        const checkMyResult = await checkAuth(GUILD_OPERATE.EQUIP_PRODUCE, roleId, null, userGuild);
        if(!checkMyResult) return resResult(STATUS.GUILD_AUTH_NOT_ENOUGH);
        const { guildCode: code } = userGuild;
        let developConsume = getArmyDevelopConsumeById(id);
        if (!developConsume)
            return resResult(STATUS.WRONG_PARMS); 
        let res:any = await lockData(serverId, DATA_NAME.GUILD_REFINE, code);//加锁
        if (!!res.err) 
            return resResult(STATUS.REDLOCK_ERR); 
        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 developConsume.prePositions) {
            let scienceTree = findWhere(guildRefine.scienceTrees, {id: prePosition});
            if (!scienceTree||scienceTree.endTime > nowTime) {
                res.releaseCallback();
                return resResult(STATUS.GUILD_PERSITION_TREE_NOT_LIGHT);//前置科技树未点亮
            }
        }
        //点亮消耗
        const costResult = await GuildModel.costFund(code, developConsume.fundConsume);
        if(!costResult) {
            res.releaseCallback();
            return resResult(STATUS.GUILD_FUND_NOT_ENOUGH);
        }
        let scienceTree = { id, endTime: nowTime + developConsume.timeConsume, assistRoleIds: []}
        let { scienceTrees } = await GuildRefineModel.pushRefine(code, scienceTree);
        res.releaseCallback();
        return resResult(STATUS.SUCCESS, { scienceTrees }); 
    }
    /**
     * 协助点亮科技树
     * @param msg 
     * @param session 
     */
    async assistRefine(msg: {id: number}, session: BackendSession) {
        let { id } = msg;
        const roleId: string = session.get('roleId');
        const serverId: number = session.get('serverId');
        const sid: string = session.get('sid');
        const funcs: number[] = session.get('funcs');
        let userGuild = await UserGuildModel.getMyGuild(roleId, 'guildCode');
        if (!userGuild) 
            return resResult(STATUS.WRONG_PARMS); 
        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}]);
        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(roleId, sid, funcs, TASK_TYPE.GUILD_ASSIST_REFINE, 1, true, {});

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