import {ObjectId} from 'mongodb';
import {ApiCall} from 'tsrpc';
import {CollectionEquip} from '../module/collection_equip';
import {HeroFun} from './hero';
import {call} from './player';

type equipChange = Partial<Omit<{
    [k in keyof CollectionEquip]: CollectionEquip[k]
}, '_id'>>;

export class EquipFun {
    /**
     * 修改装备属性
     */
    static async changeEquipAttr(call: call, equip: Pick<CollectionEquip, '_id'> & Partial<Omit<CollectionEquip, '_id'>>, change: equipChange, changeHero = true) {
        if (Object.keys(change).length < 1) return;

        //穿戴装备时该装备穿戴在另一个英雄身上
        if (change.wearaId != undefined && equip.wearaId && equip.wearaId != change.wearaId && changeHero) {
            let takeHero = await HeroFun.getHero(call, equip.wearaId);
            if (takeHero) {
                let _equip = Object.assign({}, takeHero.equip);
                _equip[G.gc.equip[equip.equipId].type] = '';
                await HeroFun.changeHeroAttr(call, takeHero, {equip: _equip});
            }
        }

        Object.assign(equip, change);

        G.mongodb.collection('equip').updateOne({uid: call.uid, _id: new ObjectId(equip._id)}, {$set: {...change}});
        call.addEventMsg('msg_s2c/EquipChange', equip._id, change);
    }

    /**
     * 获取装备
     */
    static async getEquip(call: ApiCall, oid?: string): Promise<CollectionEquip>;
    static async getEquip(call: ApiCall, oid?: string[]): Promise<CollectionEquip[]>;
    static async getEquip(call: ApiCall, oid?: string | string[]) {
        if (typeof oid == 'string') {
            let {_id, ...info} = await G.mongodb.collection('equip').findOne({
                _id: G.mongodb.conversionId(oid)
            })
            let data = Object.assign({_id: _id.toHexString()}, info)
            return data
        } else {
            let filter = {
                uid: call.uid,
            }
            if(oid && oid.length > 0){
                filter['_id'] = {$in: oid.map(v => G.mongodb.conversionId(v))}
            }
            let equips = await G.mongodb.collection('equip').find(filter).toArray();
            return equips.map(v => G.mongodb.conversionIdObj(v));
        }
    }

    /**
     * 获取所有的装备
     * 并对返回结果进行格式化，兼容原来的redis返回的格式
     */
    static async getAllEquips(call: ApiCall):Promise<k_v<CollectionEquip>>{
        let res = {};
        let equips:CollectionEquip[] = await this.getEquip(call,[]);
        equips.map(v => {
            res['_'+v._id] = v;
        });
        return res;
    }
}