import {ApiCall} from "tsrpc";
import {HeroFun} from '../../public/hero';
import {PeijianFun} from '../../public/peijian';
import {ReqOneKeyWear, ResOneKeyWear} from "../../shared/protocols/peijian/PtlOneKeyWear";
import {PeijianShared} from '../../shared/public/peijian';
import {re} from "mathjs";

export default async function (call: ApiCall<ReqOneKeyWear, ResOneKeyWear>) {

    let hero = await HeroFun.getHero(call, call.req.h_id);
    if (!hero) return call.errorCode(-2);

    if (call.conn.gud.lv < G.gc.peijiancom.gridCond['1'].lv) return call.errorCode(-3);

    let wears = hero.peijian || {};

    //选出未穿戴的100条配件，按执行顺序降序
    let peijianArr = await PeijianFun.getAvbPeijian(call, 100);

    //取wear值，_切开后的第0位，表示所有穿戴中的配件的_id
    //最终，这里返回的是这个英雄正在穿戴中的配件
    let wearsPijian = await PeijianFun.getPeijian(call, Object.values(wears).map(i => i.split('_')[0]))

    //联合起来，即表示该英雄此时可以穿戴的所有（含原已穿戴的）
    peijianArr = [...wearsPijian, ...peijianArr]

    //按品质 -> lv 排序
    peijianArr.sort((a, b) => {
        let x = Number(a.peijianId.slice(0, 1))
        let y = Number(b.peijianId.slice(0, 1))
        if (x != y) return y - x
        if (a.jinglian != b.jinglian) return b.jinglian - a.jinglian
        return b.lv - a.lv
    })

    //相同部位去重
    let uniqueArr = []
    peijianArr.map(i => {
        let pos = G.gc.peijian[i.peijianId].pos
        let a = uniqueArr.findIndex(j => j.pos == pos)
        if (a == -1) uniqueArr.push({...i, pos})
    })
    peijianArr = uniqueArr

    // 检查配件位置是否可以穿戴
    // 返回：[1,2,3,4,5,6] 表示哪些格子可以装配
    let posArr = []
    for (let i = 1; i < 7; i++) {
        //如果我的等级>配置的开启等级  或 花费了钻石提前解锁的格子
        if (call.conn.gud.lv >= G.gc.peijiancom.gridCond[i.toString()].lv || (call.conn.gud.peijianUnlock?.[i.toString()] != undefined)) {
            posArr.push(i)
        }
    }
    if (peijianArr.length == 0 || posArr.length == 0) return call.succ({});

    let newPeiJian = [];
    for (let posIndex=0;posIndex<posArr.length;posIndex++){
        //pos=第几个格子
        let pos = posArr[posIndex];
        if (!peijianArr.length) break
        for (let index =0;index<peijianArr.length;index++) {
            //如果newPeiJian已有相同pos的了，则跳过
            if (newPeiJian.filter(i => i.pos == peijianArr[index].pos).length) continue
            
            newPeiJian.push( peijianArr[index] );
            break;
        }
    }

    //当前正在穿戴的
    let oids = wearsPijian.map(i => G.mongodb.conversionId(i._id));
    let oid = oids.sort().join("_");

    //将newPeiJian里的所有_id转字符串后连起来
    let nids = newPeiJian.map(i => G.mongodb.conversionId(i._id));
    let nid = nids.sort().join("_");
    if(oid == nid){
        //新的和原来的一样，啥都不干
        call.succ({});
        return;
    }

    for(let i=0;i<wearsPijian.length;i++){
        //将原来的所有配件卸下
        await PeijianFun.changeAttr(call, wearsPijian[i], {wearId: ''}, false);
    }

    let newPeiJianFild = {};
    for(let i=0;i<newPeiJian.length;i++){
        //将所有新的配件装上
        await PeijianFun.changeAttr(call, newPeiJian[i], {wearId: call.req.h_id}, false);
        newPeiJianFild[ (i+1).toString() ] = PeijianShared.fmt( newPeiJian[i] );
    }

    //更新英雄的peijian字段
    await HeroFun.changeHeroAttr(call, hero, {peijian: newPeiJianFild});

    call.succ({});
}