import {ApiCall} from "tsrpc";
import {EventFun} from '../public/event/event';
import {PayFun} from '../public/pay';
import {ReqSyncBtn, ResSyncBtn, syncBtnKeys} from "../shared/protocols/PtlSyncBtn";
import {PublicShared} from '../shared/public/public';
import {HuoDongFun} from "../public/huodongfun";

const defaultKeys: syncBtnKeys[] = [
    'huobanzhaomu', 'yibaichou', 'shouchong',
    'dayjijin', 'dengjijijin', 'guanqiajijin', 'tianshujijin',
    'zhanling',
    'xianshilibao',
    'xianshizhaomu',
    'G123Gift',
    'christmas',

    // 'kaifukuanghuan',
    //  'qiridenglu',
    //  'leijichongzhi', 'xinshoulibao', 'jierihuodong', 'yuedujijin', 'zixuanlibao', 'diaoluoduihuan', 'chuanshuozhilu',
    // 'yangchengmubiao'
];

export default async function (call: ApiCall<ReqSyncBtn, ResSyncBtn>) {
    let change: ResSyncBtn = {};
    let keys = call.req.length < 1 ? defaultKeys : call.req;
    let data = await G.mongodb.collection('syncBtns').findOne({uid: call.uid});

    if (!data) data = {} as any;

    for (let key of keys) {
        switch (key) {
            case 'huobanzhaomu':
            case 'yibaichou':
            case 'shouchong':
                //领完消失
                if (!data[key]) {
                    data[key] = {active: true};
                    change[key] = data[key];
                }
                break;
            case 'christmas':
                //领完消失
                data[key] = {active: false};
                change[key] = data[key];
                let _hdList = await HuoDongFun.gethdList(call, 8)
                if (_hdList.length > 0) {
                    // 无此活动
                    data[key] = {active: true};
                    change[key] = data[key];
                    }
                break;
            case 'dayjijin':
            case 'dengjijijin':
            case 'guanqiajijin':
            case 'tianshujijin':
                //领完消失
                if (!PublicShared.getEventIsOpen(G.gc.eventOpen[key], call.conn.gud)) {
                    data[key] = {active: false};
                } else {
                    if (!data[key]) {
                        data[key] = {active: true};
                        change[key] = data[key];
                    }
                }
                break;
            case 'zhanling':
                //30天一轮循环，不管奖励。常驻活动
                if (!PublicShared.getEventIsOpen(G.gc.zhanling.eventOpen, call.conn.gud)) {
                    data[key] = {active: false};
                } else {
                    let zls = await G.mongodb.collection('scheduler').findOne({type: 'zhanling'});
                    if (!data[key] || data[key].round != zls.round) {
                        let lastRunTime = zls && zls.lastRunTime? zls.lastRunTime : G.time
                        let round = zls && zls.lastRunTime? zls.round : 1
                        data[key] = {active: true, sTime: lastRunTime, round: round};
                        change[key] = data[key];

                        PayFun.delPayLog(call.uid, {payId: G.gc.zhanling.payId, val: []});

                        G.mongodb.cEvent('zhanling').findOne({uid: call.uid, type: 'zhanling'}).then(data => {
                            //新一轮战令 不管玩家多久没上线 只补发玩家上一轮没有领取的奖励
                            data && EventFun.reissueZhanLingPrize(data, call.conn.gud);

                            G.mongodb.cEvent('zhanling').updateOne(
                                {uid: call.uid, type: 'zhanling'},
                                {
                                    $set: {
                                        lv: 1,
                                        exp: 0,
                                        rec: {},
                                        isPay: false,
                                        taskRec: [],
                                        refreshTime: G.time
                                    }
                                },
                                {upsert: true}
                            );
                        });
                    }
                }
                break;
            case 'xianshilibao':
                // 到时间消失
                if (!data.xianshilibao) {
                    data.xianshilibao = change.xianshilibao = {pays: []};
                } else {
                    change.xianshilibao = data.xianshilibao;
                    data.xianshilibao.pays = data.xianshilibao.pays.filter(p => {
                        return p.eTime > G.time;
                    });
                }
                break;
            case 'xianshizhaomu':
                // 不确定
                if (G.time < PublicShared.getToDayZeroTime(G.openTime) + G.gc.xianshizhaomu.time.slice(-1)[0]) {
                    data[key] = {active: false};
                } else {
                    data[key] = {active: false};
                }
                break;
            case 'G123Gift':
                data[key] = {active: false, giftInfo:[]};
                let giftList = await G.mongodb.collection('giftLog').find({
                    game_user_id: call.uid,
                    $or: [{endTime: {$gte: G.time}}, {endTime: {$exists: false}}]
                }).toArray();
                if (giftList.length>0) {
                    data[key] = {active: true, giftInfo: giftList.filter(i=>(i.buyNumber||0)<i.purchaseLimitAmount)};
                }
                for (let item of giftList){
                    if (item && !item.endTime) {
                        G.mongodb.collection('giftLog').updateOne({_id: item._id}, {
                            $set: {
                                showTime: G.time,
                                endTime: G.time + item.duration
                            }
                        }, {upsert: true});
                    }
                }
                break
            default:
                data[key] = {active: true};
                break;
        }
    }

    if (Object.keys(change).length > 0) {
        G.mongodb.collection('syncBtns').updateOne({uid: call.uid}, {$set: change}, {upsert: true});
    }

    call.succ(Object.fromEntries(keys.map(key => [key, data[key]])));
}