import { ApiCall } from "tsrpc";
import { PlayerFun } from "../../../public/player";
import { ReqRec, ResRec } from "../../../shared/protocols/event/yangchengmubiao/PtlRec";
import { HongDianChange } from "../../hongdian/fun";
import { YangChengMuBiaofun } from "./fun";

export default async function (call: ApiCall<ReqRec, ResRec>) {
    // let hdids = await gethdids()
    // if (!hdids.includes(call.req.hdid)) {
    //     // 活动时间过期
    //     return call.error('', { code: -1, message: globalThis.lng.yangchengmubiao_1 })
    // }
    let _yangchengcon = await YangChengMuBiaofun.getCon(call)
    let _initCon = _yangchengcon[call.req.hdid]     // 活动配置
    let _con = _initCon.data.tasklist[call.req.type][call.req.taskid]   // 任务配置
    if (!_con) {
        // 任务id 不存在
        return call.error('', { code: -2, message: globalThis.lng.yangchengmubiao_2 })
    }
    let _mydata = await YangChengMuBiaofun.getMyData(call, call.req.hdid)
    if (_mydata.taskval[call.req.taskid] < _con.pval) {
        // 任务未完成
        return call.error('', { code: -3, message: globalThis.lng.yangchengmubiao_3 })
    }
    if (_mydata.finishid[_con.type].includes(call.req.taskid)) {
        // 任务已领取
        return call.error('', { code: -4, message: globalThis.lng.yangchengmubiao_4 })
    }

    _mydata.finishid[_con.type].push(call.req.taskid)
    let _setData = {}
    // 轮次任务重置
    if (_con.type == 2 && _mydata.lunci < _initCon.data.maxlun[1] && _mydata.finishid[call.req.type].length >= Object.keys(_initCon.data.tasklist[call.req.type]).length) {
        _mydata = await YangChengMuBiaofun.refreTask(call, _mydata, call.req.hdid, 2)
        _mydata.lunci += 1
        _setData["taskval"] = _mydata.taskval
        _setData["lunci"] = _mydata.lunci
    }

    // 设置任务改变数据
    _setData["finishid"] = _mydata.finishid
    await YangChengMuBiaofun.setMyData(call.uid, call.req.hdid, { $set: _setData })

    // 发奖
    let _prize: atn[] = _con.prize
    await PlayerFun.sendPrize(call, _prize);

    let changedata = { mydata: _mydata, prize: _prize }
    HongDianChange.sendChangeKey(call.uid, ['huodonghd']);
    call.succ(changedata);
}