import {ObjectId} from 'mongodb';
import {PeiJian} from '../shared/protocols/peijian/PtlGetList';
import {PeijianShared} from '../shared/public/peijian';
import {HeroFun} from './hero';
import {call} from './player';


export class PeijianFun {
    static async changeAttr(call: call, peijian: Omit<PeiJian, 'wearId'> & { wearId?: string; }, change: Partial<Omit<PeiJian, '_id'>>, changeHero = true) {
        if (Object.keys(change).length < 1) return;

        if (peijian.wearId && changeHero) {
            let hero = await HeroFun.getHero(call, peijian.wearId);
            let peijianData = hero.peijian;
            let wearData = Object.entries(peijianData).find(v => v[1].split('_')[0] == peijian._id);

            if (change.wearId == '') {
                peijianData[wearData[0]] = '';
            } else {
                Object.assign(peijian, change);
                peijianData[wearData[0]] = PeijianShared.fmt(peijian);
            }

            await HeroFun.changeHeroAttr(call, hero, {peijian: peijianData});
        }

        G.redis.get('peijian', call.uid, peijian._id).then(v => {
            Object.assign(v, change);
            G.redis.set('peijian', call.uid, peijian._id, v);
        });

        G.mongodb.collection('peijian').updateOne({uid: call.uid, _id: new ObjectId(peijian._id)}, {$set: {...change}});

        call.addEventMsg('msg_s2c/PeijianChange', peijian._id, change);
    }
    static async getPeijian(call: call, _id: string): Promise<PeiJian>;
    static async getPeijian(call: call, _id: string[]): Promise<PeiJian[]>;
    static async getPeijian(call: call, _id: string | string[]) {
        if (typeof _id == 'string') {
            return await G.redis.get('peijian', call.uid, _id);
        } else {
            let ss = await G.mongodb.collection('peijian').find({_id: {$in: _id.map(v => G.mongodb.conversionId(v))}}).toArray();
            return ss.map(v => G.mongodb.conversionIdObj(v) as PeiJian);
        }
    }

    static async getAvbPeijian(call: call, limit: number): Promise<PeiJian[]>;
    static async getAvbPeijian(call: call, limit: number) {
        let peijian = Object.values(G.gc.peijian)
        //筛选出pos=0的id集合
        let ids = peijian.filter(i => i.pos == 0).map(i => i.id.toString())
        let ss = await G.mongodb.collection('peijian').find({
            uid: call.conn.uid,
            wearId: '',
            peijianId: {$nin: ids}
        }).limit(limit).sort({peijianId: -1, jinglian: -1, lv: -1}).toArray();
        return ss.map(v => G.mongodb.conversionIdObj(v) as PeiJian);
    }

}