import { strict } from 'assert';
import { ApiCall } from 'tsrpc';
import { ReqAddHuoDong } from '../../../monopoly/protocols/PtlAddHuoDong';
import { HuoDongFun } from '../../../public/huodongfun';
import { TaskFun } from '../../../public/task';
import { yangchengmubiao } from '../../../shared/protocols/event/yangchengmubiao/PtlOpen';
import { PublicShared } from '../../../shared/public/public';


export class YangChengMuBiaofun {
    /**配置 */
    static async getCon(call: ApiCall) {
        let _con: { [id: string]: ReqAddHuoDong } = {}
        let _hd = await HuoDongFun.gethdList(call, 1)
        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, 1)
        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(`yangchengmubiao${hdid}`).findOne({ uid: call.uid, type: `yangchengmubiao${hdid}`, hdid: hdid });
        if (!db) {
            db = await this.initData(call, hdid)
            await G.mongodb.cEvent(`yangchengmubiao${hdid}`).updateOne(
                { uid: call.uid, type: `yangchengmubiao${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)
            _myData.refresh = G.time
            await this.setMyData(call.uid, hdid, { $set: { refresh: _myData.refresh, finishid: _myData.finishid, taskval: _myData.taskval } })
        }
        return _myData
    }

    /**初始数据 */
    static async initData(call: ApiCall, hdid: number) {
        let _initCon = await this.getCon(call)
        let _con = _initCon[hdid]
        let _r: yangchengmubiao = {
            type: `yangchengmubiao${hdid}`,
            uid: call.uid,
            hdid: hdid,
            taskval: await this.getTaskVal(call, hdid),
            finishid: {
                "1": [],
                "2": [],
                "3": [],
            },
            refresh: G.time,
            lunci: 1,
            record: {}
        }
        if (_con.data.tasklist["4"] && Object.keys(_con.data.tasklist["4"]).length > 0) _r.finishid["4"] = []
        return _r
    }

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

    /**获取所有taskid 及对应的值 */
    static async getTaskVal(call: ApiCall, hdid: number) {
        let _initCon = await this.getCon(call)
        let _con = _initCon[hdid].data.tasklist
        let _res = {}

        let _tasks = {}   // 所有任务 taskid 为key
        Object.values(_con).map(l => {
            return Object.assign(_tasks, l)
        })

        for (let index = 0; index < Object.keys(_tasks).length; index++) {
            const element = Object.keys(_tasks)[index];
            let _tmp = _tasks[element]
            _tmp["id"] = element
            _res[element] = await TaskFun.getTaskNval(call, _tmp)
        }
        return _res
    }

    /**刷新每日任务 */
    static async refreTask(call: ApiCall, mydata: yangchengmubiao, hdid: number, type: 1 | 2 = 1) {
        let _initCon = await this.getCon(call)
        let _con = _initCon[hdid].data.tasklist[type]
        if (!_con) return mydata
        for (let index = 0; index < Object.keys(_con).length; index++) {
            const element = Object.keys(_con)[index];
            let _tmp = _con[element]
            if (_tmp.type != type) continue

            mydata.finishid[type] = []
            let _initVal = (_tmp?.zero == 1) ? 0 : await TaskFun.getTaskNval(call, _tmp)
            mydata.taskval[element] = _initVal
        }
        return mydata
    }

    /**设置任务 */
    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 _con = _initCon[hdid].data.tasklist
            let _tasks = {}
            Object.values(_con).map(l => {
                return Object.assign(_tasks, l)
            })

            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: "yangchengmubiao" }, hdid: parseInt(hdid) },
                    _setData
                )
            }
        }
    }



}