import {ApiCall} from "tsrpc";
import {ReqGetList, ResGetList} from "../../shared/protocols/peijian/PtlGetList";

export default async function (call: ApiCall<ReqGetList, ResGetList>) {
    let _maxLv = 0
    let color = {}
    let peijianCon = G.gc.peijian

    let dbList = (await G.mongodb.collection('peijian').find({uid: call.uid}).toArray()).map(p => {
        let np = G.mongodb.conversionIdObj(p);
        let {uid, ...ops} = np;

        if (np.lv > _maxLv) _maxLv = np.lv
        if (!color[peijianCon[np.peijianId].colour]) color[peijianCon[np.peijianId].colour] = 0
        color[peijianCon[np.peijianId].colour] = np.lv > color[peijianCon[np.peijianId].colour] ? np.lv : color[peijianCon[np.peijianId].colour]
        return ops;
    });

    // 修复配件穿戴在不存在的英雄身上
    let heroIds = R.values(call.conn.gud.heroPos)
    let fixIds = dbList.filter(i => i.wearId && !heroIds.includes(i.wearId)).map(i => G.mongodb.conversionId(i._id))
    if (fixIds.length) {
        await G.mongodb.collection('peijian').updateMany({_id: {$in: fixIds}}, {$set: {wearId: ''}})
    }

    // 记录玩家最大等级，颜色相关数据 注册任务用
    await G.mongodb.collection('playerInfo', 'usertasklog').updateOne({uid: call.conn.uid, type: 'usertasklog'},
        {$set: {maxpeijianlv: _maxLv, peijiancolor: color}}, {upsert: true})

    let list = Object.fromEntries(dbList.map(p => [G.formatRedisKey(p._id), p]));
    G.redis.set('peijian', call.uid, list);

    let recLshd = await G.mongodb.collection('playerInfo', 'lshd_peijian').findOne({
        uid: call.conn.uid,
        type: 'lshd_peijian'
    });
    let {uid, _id, type, ...peijians} = (recLshd || {});

    call.conn.lshd.peijian = peijians || {};
    call.succ({
        list: Object.fromEntries(dbList.map(p => [p._id, p])),
        lshd: peijians || {}
    });
}