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

import com.yem.wm.bc.companytitle.form.CompanyTitleEdit;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.OperateOption;
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.entity.operate.result.OperationResult;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xwudd
 * @date 16:38
 * @Description
 **/
public class ClientDemandSaleOrderConvert extends AbstractConvertPlugIn
{
    private static Log log = LogFactory.getLog(CompanyTitleEdit.class);

    @Override
    public void afterConvert(AfterConvertEventArgs e)
    {
        super.afterConvert(e);
        String targetName = this.getTgtMainType().getName();
        String name = this.getSrcMainType().getName();
        ExtendedDataEntity[] findByEntityKeys = e.getTargetExtDataEntitySet().FindByEntityKey(targetName);
        for (ExtendedDataEntity findByEntityKey : findByEntityKeys) {
            DynamicObject dataEntity = findByEntityKey.getDataEntity();
            DynamicObjectCollection materialInfos = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            List<DynamicObject> clientDemands = (List<DynamicObject>) findByEntityKey.getValue("ConvertSource");
            for (DynamicObject materialInfo : materialInfos) {
//                long sourceEntryId = materialInfo.getLong("yem_sourceentryid");
                DynamicObject clientDemand = clientDemands.get(0);
                clientDemand = BusinessDataServiceHelper.loadSingleFromCache(clientDemand.getLong("id"), name);
                DynamicObject billType = clientDemand.getDynamicObject("yem_billtype");
                if (YEM.isNotEmpty(billType)) {
                    String number = billType.getString("number");
                    if ("yem_im_clientdeman_zj".equals(number)) {
                        dataEntity.set("yem_billtypetext", "整机合同");
                    }
                    if ("yem_im_clientdema_pj".equals(number)) {
                        dataEntity.set("yem_billtypetext", "配件合同");
                    }
                }
//                DynamicObjectCollection detailedInfos = clientDemand.getDynamicObjectCollection("yem_im_detailedinfor");
//                Map<Long, DynamicObject> ids = detailedInfos.stream().collect(Collectors.toMap(x -> x.getLong("id"), y -> y));
//                if (ids.containsKey(sourceEntryId)) {
//                    DynamicObject detailedInfo = ids.get(sourceEntryId);
//                    String intAuditBuSaNo = detailedInfo.getString("yem_intauditbusano");
//                    Object intAuditBuSaIdObj = detailedInfo.get("yem_intauditbusaid");
//                    if (YEM.isNotEmpty(intAuditBuSaNo) && YEM.isNotEmpty(intAuditBuSaIdObj)) {
//                        long intAuditBuSaId = detailedInfo.getLong("yem_intauditbusaid");
//                        DynamicObject fromIntAuditBuSa = BusinessDataServiceHelper.loadSingle(intAuditBuSaId, "yem_im_intauditbusa");
//                        if (fromIntAuditBuSa != null) {
//                            DynamicObject toIntAuditBuSa = BusinessDataServiceHelper.newDynamicObject("yem_im_intauditbusa");
//                            DynamicObjectUtil.copyDynamicObject(fromIntAuditBuSa, toIntAuditBuSa, 2, false, true, true);
//                            toIntAuditBuSa.set("yem_needbillintauditno", fromIntAuditBuSa.getString("billno"));
//                            toIntAuditBuSa.set("yem_needbillintauditid", fromIntAuditBuSa.getPkValue());
//                            FunctionalCommon.setBillInfo(toIntAuditBuSa, dataEntity, materialInfo.getLong("id"));
//                            OperationResult operationResult = OperationServiceHelper.executeOperate("save", "yem_im_intauditbusa", new DynamicObject[]{toIntAuditBuSa}, OperateOption.create());
//                            if (!operationResult.isSuccess()) {
//                                log.error(operationResult.getMessage());
//                            } else {
//                                materialInfo.set("yem_intauditbusano", toIntAuditBuSa.get("billno"));
//                                materialInfo.set("yem_intauditbusaid", toIntAuditBuSa.getPkValue());
//                            }
//                        }
//                    }
//                }

                DynamicObject[] loads = getDeclarationElements(materialInfo);

                if (loads.length == 1) {
                    DynamicObject load = loads[0];
                    load = BusinessDataServiceHelper.loadSingle(load.getPkValue(), load.getDynamicObjectType().getName());
                    DynamicObject customclass = load.getDynamicObject("yem_customclass");
                    if (YEM.isNotEmpty(customclass)) {
                        materialInfo.set("yem_customclass", customclass);
                    }
                    DynamicObject hscodebase = load.getDynamicObject("yem_hscodebase");
                    if (YEM.isNotEmpty(hscodebase)) {
                        hscodebase = BusinessDataServiceHelper.loadSingle(hscodebase.getPkValue(), hscodebase.getDynamicObjectType().getName());
                        materialInfo.set("yem_hscode", hscodebase);
                        materialInfo.set("yem_declarationele", load);
                        materialInfo.set("yem_actualfilingele", load.getString("name"));
                        materialInfo.set("yem_declareunit", hscodebase.getDynamicObject("yem_legalfirst"));
                    }
                }
            }
        }
    }

    public static DynamicObject[] getDeclarationElements(DynamicObject entry)
    {
        if (entry == null) return new  DynamicObject[]{};

        // 业务分类 Z | P
        String businesssort = entry.getString("yem_businesssort");

        // 基础机型
        DynamicObject productmodel = entry.getDynamicObject("yem_productmodel");
        // 物料
        DynamicObject material = entry.getDynamicObject("yem_materiel");
        // 报关分类
        DynamicObject customclass = entry.getDynamicObject("yem_customclass");
        // 海关编码
        DynamicObject hscode = entry.getDynamicObject("yem_hscode");
        long id = 0L;
        QFilter qFilter = null;
        if ("Z".equals(businesssort)) {
            if (YEM.isNotEmpty(productmodel)) {
                id = productmodel.getLong("yem_products.id");
                qFilter = new QFilter("yem_bd_declarationele.yem_productstree.id", QCP.equals, id);
                qFilter.and(new QFilter("enable", QCP.equals, "1"));
            }
        }

        if ("P".equals(businesssort)) {
            if (YEM.isNotEmpty(material)) {
                id = material.getLong("id");
                qFilter = new QFilter("yem_bd_declarationele.yem_material.id", QCP.equals, id);
                qFilter.and(new QFilter("enable", QCP.equals, "1"));
            }
        }

        if (qFilter != null) {
            if (customclass != null) {
                qFilter.and(new QFilter("yem_customclass.id", QCP.equals, customclass.getLong("id")));
            }

            if (hscode != null) {
                qFilter.and(new QFilter("yem_hscodebase.id", QCP.equals, hscode.getLong("id")));
            }
        }

        String selectfields = DynamicObjectUtil.getSelectfields("yem_bd_declarationele");
        if (qFilter != null) {
            return BusinessDataServiceHelper.load("yem_bd_declarationele", selectfields, qFilter.toArray());
        } else {
            return new DynamicObject[]{};
        }
    }
}
