import { ApiCall, TsrpcError } from 'tsrpc';
import { gonghuiBase, gonghuiSetting } from '../../shared/protocols/gonghui/type';
import { hongdianVal } from '../../shared/protocols/hongdian/PtlGet';
import { ActionLog } from '../actionLog/actionLog';
import { PlayerFun } from '../player';


export class GongHuiFun {
    static init() {

    }
    static get db() {
        return G.mongodb.collection('gonghui');
    }
    /**
     * 检查创建公会或设置公会时的数据合法性
     */
    static async checkSetArgs(args: Partial<Pick<gonghuiBase, 'name'> & { setting: Partial<gonghuiSetting>; }>) {
        if (args.name != undefined) {
            if (args.name.trim().length == 0) throw new TsrpcError('名字不可为空');
            if ((await this.db.findOne({ name: args.name })) != null) throw new TsrpcError(globalThis.lng.gonghui_29);
        }
        if (args.setting != undefined) {
            if (args.setting.badge != undefined) {
                if (args.setting.badge.trim().length == 0 || !G.gc.shilihuizhang[args.setting.badge]) throw new TsrpcError('setting.badge 参数错误');
            }
            if (args.setting.notice != undefined) {
                if (args.setting.notice == '') args.setting.notice = G.gc.shili_com.defaultNotice;
            }
        }
    }

    // 工会物资红点
    static async getWuZiHD(call: ApiCall, res: hongdianVal) {
        let _ghwz = Object.keys(call.conn.gud.ghwz);
        // 工会物资
        for (let index = 0; index < _ghwz.length; index++) {
            const element = _ghwz[index];
            const conf = G.gc.shili_wz[element];
            const nextLv = call.conn.gud.ghwz[element] + 1;
            if (!conf[nextLv]) continue;  // 已满级
            let meet = await PlayerFun.checkNeedIsMeet(call, conf[nextLv].need, false);
            if (meet.isOk) {
                res.show = true;
                res.val.ghwz = 1;
                break;
            }
        }
        return res;
    }

    // 工会boss红点
    static async getBossHD(call: ApiCall, res: hongdianVal) {
        let gh = await call.conn.gonghui;
        if (!gh || gh.data.lv < 2) return res;
        let conf = G.gc.shili_fb[gh.data.fuben.id];
        if (conf) {
            // 有boss
            let dbData = await G.mongodb.collection('gonghuiUser').findOne({ uid: call.uid });
            if ((dbData?.fuben?.fightNum == undefined ? 2 : dbData?.fuben?.fightNum) >= 1) {
                res.show = true;
                res.val.fuben = 1;
            }
        }
        return res;
    }

    // 工会捐献财务部红点  只计算普通捐献
    static async getCaiWuHD(call: ApiCall, res: hongdianVal) {
        const data = await G.mongodb.collection('gonghuiUser').findOne({ uid: call.uid });
        const jx = data?.jx || { refreshTime: G.time, record: {} };
        // let _chk = Object.keys(jx.record)
        let _chk = [0];
        for (let index = 0; index < _chk.length; index++) {
            const element = _chk[index];
            const conf = G.gc.shili_com.juanxian[element];
            if (conf && (jx.record[element] || 0) < conf.maxNum) {
                res.show = true;
                res.val.jx = 1;
                break;
            }
        }
        return res;
    }

    // 会议桌子函数  任务是否完成
    static async getFinish(call: ApiCall, _taskCon: any[], _val: number, _type: string) {
        let ishd: 0 | 1 = 0;
        const data = await G.mongodb.collection('gonghuiUser').findOne({ uid: call.uid });
        for (let indexTask = 0; indexTask < _taskCon.length; indexTask++) {
            const elementTask = _taskCon[indexTask];
            if (_type == "my") {
                _val = await ActionLog.getDayLog(call.uid, elementTask.taskId);
            }
            if (elementTask.total > _val) continue;
            if ((data?.task?.myRec || []).includes(indexTask)) continue;
            ishd = 1;
            break;
        }
        return ishd;
    }

    // 工会红点  会议桌 工会任务
    static async getHuiyiHD(call: ApiCall, res: hongdianVal) {
        const _type = ["my", "gh"];
        for (let index = 0; index < _type.length; index++) {
            const element = _type[index];
            let _taskCon: any[];
            let _val: number;
            if (element == "gh") {
                _taskCon = G.gc.shili_com.ghTask;
                _val = (await call.conn.gonghui).data?.task?.finised || 0;
            } else {
                _taskCon = G.gc.shili_com.task;
                _val = 0;  // 后面会复写
            }
            let ishd = await this.getFinish(call, _taskCon, _val, element);
            if (ishd == 1) {
                res.show = true;
                res.val.task = 1;
                break;
            }
        }
        return res;
    }

    // 工会红点  出海                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
    static async getChuHaiHD(call: ApiCall, res: hongdianVal) {
        let dbData = await G.mongodb.collection('ganhai').findOne({ uid: call.uid });
        if (dbData?.ship?.sTime && dbData.ship.sTime + G.gc.ganhai.ships[dbData.ship.index].time < G.time) {
            res.show = true;
            res.val.ganhai = 1;
        }
        // 次数
        if ((dbData?.useEscortNum || 0) + 1 <= G.gc.ganhai.escortNum) {
            res.show = true;
            res.val.ganhai = 1;
        }
        return res;
    }

    // 工会红点  事务所（可以审批加红点）                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
    static async getBanGongShiHD(call: ApiCall, res: hongdianVal) {

        if (call.conn.gud.ghLevel > 2 || call.conn.gud.ghLevel == 0){
            //权限不足，不用显示红点
            return res;
        }

        if ((await call.conn.gonghui).data.applyList?.length > 0) {
            res.show = true;
            res.val.bangongshi = 1;
        }
        return res;
    }

    // 工会红点  工会宝藏
    static async getGHBZHD(call: ApiCall, res: hongdianVal) {
        // let need: atn[];
        // need = JSON.parse(JSON.stringify(G.gc.com.GuildDraw_Cos.value));
        // need[0].n *= 10
        // @ts-ignore
        let need = (G.gc.com.GuildDraw_Cos.value).map(_n => { return { ..._n, n: _n.n * 10 }; });
        let meet = await PlayerFun.checkNeedIsMeet(call, need, false);
        if (meet.isOk == true) {
            res.show = true;
            res.val.gonghuibaozang = 1;
        }
        return res;
    }

    /**红点 */
    static async getHongDian(call: ApiCall) {
        let _res: hongdianVal = {
            show: false,
            val: {}
        };
        let gh = await call.conn.gonghui;
        if (!gh) return _res;
        _res = await this.getCaiWuHD(call, _res);
        _res = await this.getChuHaiHD(call, _res);
        if (gh.data.lv >= 2) {    // 工会宝藏 势力2级开启 策划没配置。。。
            _res = await this.getGHBZHD(call, _res);
        }
        if (gh.data.lv >= 3) _res = await this.getHuiyiHD(call, _res);
        if (gh.data.lv >= 3) _res = await this.getWuZiHD(call, _res);
        if (gh.data.lv >= 2) _res = await this.getBossHD(call, _res);
        _res = await this.getBanGongShiHD(call, _res);
        return _res;
    }
}

