package com.yem.em.task;

import com.yem.rf.utils.RFUtils;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.YEM;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 1.根据《PLM变更单》中的
 * 【PLM工艺变更单号】+【总成编码】+【子项零件编码】+【子件数量】
 * 匹配《BOM》变更单
 * 【更改单号】+【总成编码】+【子项零件编码】+【数量】+【启用停用状态=‘停用’】更新 《PLM变更单》【启用停用状态】【启用停用时间】；
 * <p>
 * 2.根据《PLM变更单》中的
 * 【PLM工艺变更单号】+【替换后总成编码】+【替换后子项零件编码】+【替换子件数量】
 * 匹配《BOM》变更单
 * 【更改单号】+【总成编码】+【子项零件编码】+【数量】+【启用停用状态=‘启用’】更新 《PLM变更单》【替换件启用停用状态】【替换件启用停用时间】；
 * @Date: 2024/8/29 15:08
 * @Created: by ZZSLL
 */

public class MatchingPLMChangeUpdateTaskEdit extends AbstractTask {

    private static Logger logger = LoggerFactory.getLogger(MatchingPLMChangeUpdateTaskEdit.class);

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        DynamicObject[] plms = queryPLMChange();
        DynamicObject[] boms = queryBOMChange();

        for (DynamicObject bomObj : boms) {
            DynamicObjectCollection bom_entry = bomObj.getDynamicObjectCollection("yem_entryentity");
            for (DynamicObject bom : bom_entry) {
                for (DynamicObject plmObj : plms) {
                    DynamicObjectCollection plm_entry = plmObj.getDynamicObjectCollection("yem_change_detail");
                    for (DynamicObject plm : plm_entry) {
                        String plm_billno = plmObj.getString("yem_gybg_no");//PLM工艺变更单号
                        String plm_parent = plm.getString("yem_textfield");//总成编码
                        String bom_enablesta = bom.getString("yem_enablesta");//启用停用状态
                        Date bom_completetime = bom.getDate("yem_completetime");
                        String exestate = bom.getString("yem_exestate");
                        Date invoktime = plm.getDate("yem_invoktime");//执行时间
                        String invokstatus = plm.getString("yem_invokstatus");//执行状态
                        if (YEM.isNotEmpty(invoktime) && "B".equals(invokstatus)) {
                            //已完成跳过
                            continue;
                        }
                        Boolean plmMatchBom = isPlmMatchBom(plmObj, bom, plm);
                        exestate = "30".equals(exestate) ? "B" : "A";
                        if (plmMatchBom != null && !plmMatchBom) {
                            Date downdate = bom.getDate("yem_downdate");
                            if (YEM.isNotEmpty(downdate)) {
                                plm.set("yem_enablestatus_before", bom_enablesta);
                                plm.set("yem_stoptime", downdate);
                            } else {
                                logger.info("停用_无时间，不更新，{}，{}", plm_billno, plm_parent);
                            }
                        }

                        if (plmMatchBom != null && plmMatchBom) {
                            Date enableddate = bom.getDate("yem_enableddate");
                            if (YEM.isNotEmpty(enableddate)) {
                                plm.set("yem_enablesta", bom_enablesta);
                                plm.set("yem_starttime", enableddate);
                            } else {
                                logger.info("启用_无时间，不更新，{}，{}", plm_billno, plm_parent);
                            }
                        }

                        if (plmMatchBom != null && YEM.isNotEmpty(bom_completetime)) {
                            plm.set("yem_invoktime", bom_completetime);
                            plm.set("yem_invokstatus", exestate);
                        }
                    }
                }
            }
        }
        SaveServiceHelper.save(plms);
    }

    /**
     * PLM匹配BOM，
     *
     * @param plmObj
     * @param bom
     * @param plm
     * @return 匹配到停用返回false，启用返回true，未匹配到返回null
     */
    public static Boolean isPlmMatchBom(DynamicObject plmObj, DynamicObject bom, DynamicObject plm) {
        String plm_billno = plmObj.getString("yem_gybg_no");//PLM工艺变更单号
        String bom_billno = bom.getString("yem_changeno");//更改单号
        String bom_parent = bom.getString("yem_parentno");//父件编码
        String bom_child = bom.getString("yem_subno");//子项零件编码
//        BigDecimal bom_qty = bom.getBigDecimal("yem_qty");//数量
        String bom_enablesta = bom.getString("yem_enablesta");//启用停用状态
        String plm_parent = plm.getString("yem_textfield");//总成编码
        String plm_child = plm.getString("yem_child_before");//子项零件编码
//        BigDecimal plm_qty = plm.getBigDecimal("yem_qty_before");//子件数量
        String plm_after_parent_now = plm.getString("yem_parent_now");//父项编码
        String plm_after_child_now = plm.getString("yem_child_now");//子项编码
//        BigDecimal plm_after_qty = plm.getBigDecimal("yem_qty_new");

        String bom_before_parent_no = bom.getString("yem_parentno");//总成编码
        String bom_before_child_no = bom.getString("yem_subno");//子件编码
//        BigDecimal bom_before_qty = bom.getBigDecimal("yem_qty");
//        logger.info("停用_compare: {} {}, {} {}, {} {}, {} {}", plm_billno, bom_billno, plm_parent, bom_parent, plm_child, bom_child, bom_child, bom_enablesta);
        if (eq(plm_billno, bom_billno) && eq(plm_parent, bom_parent) && eq(plm_child, bom_child) && "B".equals(bom_enablesta)) {
            logger.info("停用_PLM匹配到BOM，{} {}, {} {}, {} {}", plm_billno, bom_billno, plm_parent, bom_parent, plm_child, bom_child);
            return false;
        }

//        logger.info("启用_compare：{} {}, {} {}, {} {}, {} {}, {}", plm_billno, bom_billno,plm_after_parent_now, bom_before_parent_no, plm_after_child_now, bom_before_child_no, plm_after_qty, bom_before_qty, bom_enablesta);
        if (eq(plm_billno, bom_billno) && eq(plm_after_parent_now, bom_before_parent_no) && eq(plm_after_child_now, bom_before_child_no) && "A".equals(bom_enablesta)) {
            logger.info("启用_PLM匹配到BOM，{} {}, {} {}, {} {}", plm_billno, bom_billno, plm_after_parent_now, bom_before_parent_no, plm_after_child_now, bom_before_child_no);
            return true;
        }

        return null;
    }

    public static boolean eq(Object str1, Object str2) {
        if (str1 instanceof String && str2 instanceof String) {
            return str1.equals(str2);
        }
        if (str1 instanceof BigDecimal && str2 instanceof BigDecimal) {
            return ((BigDecimal) str1).compareTo((BigDecimal) str2) == 0;
        }
        return false;
    }

    public static DynamicObject[] queryPLMChange() {
        final String formId = "yem_changecompare";
        final String entryId = "yem_change_detail";
        String selectfields = DynamicObjectUtil.getSelectfields(formId);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, formId, entryId);
        QFilter qFilter = RFUtils.getBaseQFilter();
        return BusinessDataServiceHelper.load(formId, selectfields, qFilter.toArray());
    }

    public static DynamicObject[] queryBOMChange() {
        final String formId = "yem_em_bomchange";
        final String entryId = "yem_entryentity";
        String selectfields = DynamicObjectUtil.getSelectfields(formId);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, formId, entryId);
        QFilter qFilter = new QFilter("status", "=", "C");
        return BusinessDataServiceHelper.load(formId, selectfields, qFilter.toArray());
    }
}
