import { ApiCall, BaseConnection } from "tsrpc";
import { ReqOpen, ResOpen } from "../../../shared/protocols/gongyu/mingdao/PtlOpen";
import { hongdianVal } from '../../../shared/protocols/hongdian/PtlGet';
import { getFinished } from './fun';

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    let db = await G.mongodb.collection('mingdao').findOne({ uid: call.uid });
    let types = [...new Set(Object.values(G.gc.mingdao).map(conf => conf.condition.map(cond => cond[0])).reduce((a, b) => a.concat(b)))];

    call.succ({
        list: Object.fromEntries(Object.keys(G.gc.mingdao).map(id => {
            return [id, {
                pre: db?.list?.[id]?.pre || 0,
                recPrize: db?.list?.[id]?.recPrize || []
            }];
        })),
        taskFinished: await getFinished(call.conn, types)
    });
}

export async function md_redPoint(call: BaseConnection): Promise<hongdianVal> {
    if (Object.keys(call.gud.shoucangping || {}).length >= Object.keys(G.gc.mingdao).length) return { show: false };


    let next = Object.keys(call.gud.shoucangping || {}).length + 1;
    let front = next - 1;
    let conf = G.gc.mingdao[next];
    if (G.gc.mingdao[front] && call.gud.shoucangping[front] < G.gc.mingdao[front].level) return { show: false };

    let types = [...conf.condition.map(v => v[0])];
    let finish = await getFinished(call, types);
    let meetLen = conf.condition.filter(v => finish[v[0]] >= v[1]).length;
    if (meetLen < conf.condition.length) return { show: false };

    return { show: true };
}

function md_cur_condArr(call: BaseConnection) {
    let next = Object.keys(call.gud.shoucangping || {}).length + 1;
    let conf = G.gc.mingdao[next];

    if (!conf) return [];
    return conf.condition.map(v => v[0]);
}

export function md_redPoint_check(call: BaseConnection, type: string) {
    if (!call || !md_cur_condArr(call).includes(type)) return;
    G.server.sendMsgByUid(call.uid, 'msg_s2c/HongDianChange', ['mingdao']);
}