import { strict } from 'assert';
import {ApiCall, BaseConnection} from 'tsrpc';
import { ReqAddHuoDong } from '../../../monopoly/protocols/PtlAddHuoDong';
import { HuoDongFun } from '../../../public/huodongfun';
import { TaskFun } from '../../../public/task';
import { christmas } from '../../../shared/protocols/event/christmas/PtlOpen';
import { PublicShared } from '../../../shared/public/public';
import {player} from '../../../shared/protocols/user/type';
import {PlayerFun} from "../../../public/player";

export class Christmasfun {
    /**配置 */
    static async getCon(call: ApiCall) {
        let _con: { [id: string]: ReqAddHuoDong } = {}
        let _hd = await HuoDongFun.gethdList(call, 8)
        for (let index = 0; index < _hd.length; index++) {
            const element = _hd[index];
            if (element && element._id) delete element._id
            _con[element.hdid] = element
        }
        return _con
    }
    /**获取所有符合时间的活动 */
    static async gethdids(call: ApiCall) {
        let _hdids = []
        let _hd = await HuoDongFun.gethdList(call, 8)
        for (let index = 0; index < _hd.length; index++) {
            const element = _hd[index];
            _hdids.push(element.hdid)
        }
        return _hdids
    }

    /**获取我的数据 */
    static async getMyData(call: ApiCall, hdid: number) {
        let db: any = await G.mongodb.cEvent(`christmas${hdid}`).findOne({ uid: call.uid, type: `christmas${hdid}`, hdid: hdid });
        if (!db) {
            db = await this.initData(call, hdid)
            await G.mongodb.cEvent(`christmas${hdid}`).updateOne(
                { uid: call.uid, type: `christmas${hdid}`, hdid: hdid },
                { $set: db },
                { upsert: true }
            )
        }
        let { _id, ..._myData } = db
        if (!PublicShared.chkSameDate(_myData.refresh, G.time)) {
            // 刷新每日任务
            _myData = await this.refreTask(call, _myData, hdid)

        }
        return _myData
    }

    /**初始数据 */
    static async initData(call: ApiCall, hdid: number) {
        let _initCon = await this.getCon(call)
        let _con = _initCon[hdid]
        let _r: christmas = {
            type: `christmas${hdid}`,
            uid: call.uid,
            hdid: hdid,
            taskval: await this.getTaskVal(call, hdid),
            taskfinish: [],
            refresh: G.time,
            gamenum: 0,
            pt: [],
            gj: [],
            pay: false,
            select:{},
            val: 0,
            qiandao: [],
            libao:{}
        }
        return _r
    }

    /**设置数据 */
    static async setMyData(uid: string, hdid: number, set: {}) {
        await G.mongodb.cEvent(`christmas${hdid}`).updateOne(
            { uid: uid, type: `christmas${hdid}`, hdid: hdid },
            set
        )
    }

    /**获取所有taskid 及对应的值 */
    static async getTaskVal(call: ApiCall, hdid: number) {
        let _initCon = await this.getCon(call)
        let _tasks = _initCon[hdid].data.task
        let _res = {}
        for (let index = 0; index < Object.keys(_tasks).length; index++) {
            const element = Object.keys(_tasks)[index];
            let _tmp = _tasks[element]
            _tmp["id"] = element
            // 每日登录直接完成
            if (element == "1"){
                _res[element] = 1
            }
            else{
                _res[element] = 0
            }


        }
        return _res
    }

    /**刷新每日任务 */
    static async refreTask(call: ApiCall, mydata: christmas, hdid: number) {
        let _initCon = await this.getCon(call)
        let _con = _initCon[hdid].data.task
        if (!_con) return mydata
        mydata.taskfinish = []
        mydata.taskval = await this.getTaskVal(call, hdid)
        mydata.refresh = G.time
        mydata.gamenum = 0
        mydata.libao = {}
        await this.setMyData(call.uid, hdid, { $set: {
                refresh: mydata.refresh,
                taskfinish: mydata.taskfinish,
                taskval: mydata.taskval,
                gamenum: mydata.gamenum,
                libao:mydata.libao} })
        return mydata
    }

    static async payChristmas(payid, call: any) {
         let _hd = await HuoDongFun.gethdList(call, 8)
         for (let index = 0; index < _hd.length; index++) {
            const hdinfo = _hd[index];
            const _hdid = hdinfo.hdid
            if (payid == hdinfo.data.zlpayid){
                let _mydata = await Christmasfun.getMyData(call, _hdid)
                if (_mydata.pay) continue
                await this.setMyData(call.uid, _hdid, { $set: { pay: true} })
                // let _prize = hdinfo.data.zlpayprize
                // await PlayerFun.sendPrize(call, _prize);
            }
            else{
                const libaos = hdinfo.data.libao
                for (let index = 0; index < Object.keys(libaos).length; index++){
                    const lbid = Object.keys(libaos)[index];
                    let _tmp = libaos[lbid]
                    if (_tmp['payid'] != payid) continue
                    let _mydata = await Christmasfun.getMyData(call, _hdid)
                    let _buyNum = _mydata.libao[lbid] || 0
                    if (_buyNum >= _tmp["buynum"]) continue
                    _mydata.libao[lbid] = _buyNum + 1
                    this.setMyData(call.uid, _hdid, { $set: { libao: _mydata.libao} })
                    let _select = _mydata.select[lbid] || {}
                    let _prize: atn[] = _tmp["basep"]
                    for (let key in _select) {
                       _prize.push(_tmp["dlz"][parseInt(key)][_select[key]])
                    }
                    await PlayerFun.sendPrize(call, _prize);
                    break

                }
            }
        }
    }


    /**设置任务 */
    static async setTaskVal(call: ApiCall, stype: number, val: number, chkCall: Function, chkval: number = 0, isinc: number = 0, alchangeVal: Function, arg) {
        let hdids = await this.gethdids(call)
        if (hdids.length <= 0) return         // 活动过期，不计数
        let _initCon = await this.getCon(call)

        for (let index = 0; index < hdids.length; index++) {
            const hdid = hdids[index];
            let _mydata = await Christmasfun.getMyData(call, hdid)
            let _tasks = _initCon[hdid].data.task

            let _setData= {
                $inc: {},
                $set: {}
            }
            let isset = 0
            for (let indextask = 0; indextask < Object.keys(_tasks).length; indextask++) {
                const ele = Object.keys(_tasks)[indextask];
                // 具体任务配置
                let _taskCon = _tasks[ele]
                if (_taskCon.stype != stype) continue

                let _pval = _taskCon.pval
                // 不符合任务要求
                if (!(await chkCall(_taskCon["cond"], chkval, arg))) continue

                // 根据需求改写
                val = await alchangeVal(call, _taskCon, val, arg)

                isset = 1
                if (isinc == 1) {    // 累加
                    _setData["$inc"][`taskval.${ele}`] = val
                } else {
                    _setData["$set"][`taskval.${ele}`] = val
                }
            }

            // 设置任务
            if (isset == 1) {
                await G.mongodb.collection('event').updateMany(
                    { uid: call.uid, type: { $regex: "christmas" }, hdid: parseInt(hdid) },
                    _setData
                )
            }
        }
    }



}
