package com.yem.wm.im.clientdemand.convert;

import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.botp.plugin.AbstractConvertPlugIn;
import kd.bos.entity.botp.plugin.args.AfterConvertEventArgs;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 客户需求单和外销合同，下推询价单时，根据物料自动携带配件分类；
 * @Date 2024/3/7 9:34
 * @Created by ZZSLL
 */

public class ClientDemandToInquiryListConvert extends AbstractConvertPlugIn
{
    @Override
    public void afterConvert(AfterConvertEventArgs e)
    {
        super.afterConvert(e);
        String name = this.getTgtMainType().getName();
        ExtendedDataEntity[] findByEntityKeys = e.getTargetExtDataEntitySet().FindByEntityKey(name);
        for (ExtendedDataEntity entityKey : findByEntityKeys) {
            DynamicObject dataEntity = entityKey.getDataEntity();
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_im_detailedinfor");

            List<Long> materialIds = new ArrayList<>();

            for (DynamicObject dynamicObject : collection) {
                DynamicObject material = dynamicObject.getDynamicObject("yem_material");
                if (YEM.isEmpty(material)) continue;

                materialIds.add(material.getLong("id"));


            }

            QFilter qFilter = new QFilter("yem_material.id", QFilter.in, materialIds);
            DynamicObject[] loads = BusinessDataServiceHelper.load("yem_bd_materialsort", "yem_material.id, yem_markup", qFilter.toArray());

            for (DynamicObject dynamicObject : collection) {
                for (DynamicObject load : loads) {
                    DynamicObject material = dynamicObject.getDynamicObject("yem_material");
                    if (YEM.isEmpty(material)) continue;
                    long id = material.getLong("id");

                    DynamicObject loadMaterial = load.getDynamicObject("yem_material");
                    if (YEM.isEmpty(loadMaterial)) continue;
                    long loadId = loadMaterial.getLong("id");

                    if (id == loadId) {
                        DynamicObject markup = load.getDynamicObject("yem_markup");
                        if (markup == null) continue;

                        dynamicObject.set("yem_classification", markup);
                    }
                }
            }
        }
    }
}
