package com.yem.wm.es.shippingdetails.validator;

import com.yem.wm.utils.DynamicObjectUtil;
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.validate.AbstractValidator;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author xwudd
 * @date 14:59
 * @Description
 **/
public class ShippingDetailSubmitValidator extends AbstractValidator {
    @Override
    public void validate() {
        ExtendedDataEntity[] dataEntities = this.getDataEntities();
        for(ExtendedDataEntity dataEntitie : dataEntities){
            DynamicObject dataEntity = dataEntitie.getDataEntity();
            DynamicObjectCollection materialInfos = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            String billtype = dataEntity.getString("yem_billtype.number");
//            if("yem_shippingdetails_zj".equals(billtype)||"yem_shippingdetails_nmzj".equals(billtype)){
//                for (int i = 0; i < materialInfos.size(); i++) {
//                    DynamicObject materialInfo = materialInfos.get(i);
//                    String businesssort = materialInfo.getString("yem_businesssort");
//                    if ("Z".equals(businesssort)){
//                        BigDecimal qty = materialInfo.getBigDecimal("yem_qty");
//                        DynamicObject resourceNog = materialInfo.getDynamicObject("yem_resourcenog");
//                        String resourceNogNumber = YEM.isNotEmpty(resourceNog)?resourceNog.getString("number"):"";
//                        DynamicObjectCollection  completeProductions  = materialInfo.getDynamicObjectCollection("yem_es_salesorder_z");
//                        int completeProductionRows = completeProductions.size();
//                        if(qty.compareTo(new BigDecimal(completeProductionRows)) != 0){
//                            this.addErrorMessage(dataEntitie,String.format("明细信息第%s行%s资源号的出运数量与对应的整机数量不一致，请检查数据后,点击保存，在点击提交！！",i+1,resourceNogNumber));
//                        }
//                    }
//                }
//            }
            vehicleNoSingle(dataEntitie);
            validateTaxRefundRate(dataEntitie);
        }
    }

    /**
     * 发运明细：是否报关为是，提交时需要校验商品信息非赠品行，退税率必须都有值
     * @param dataEntitie
     */
    private void validateTaxRefundRate(ExtendedDataEntity dataEntitie) {
        DynamicObject dataEntity = dataEntitie.getDataEntity();
        String isdeclare = dataEntity.getString("yem_isdeclare");
        if (!"A".equals(isdeclare)) return;
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        StringBuilder sb = new StringBuilder();
        for (DynamicObject dynamicObject : collection) {
            int index = collection.indexOf(dynamicObject);
            boolean ifgift = dynamicObject.getBoolean("yem_ifgift");
            if (!ifgift) {
//                BigDecimal degrate = dynamicObject.getBigDecimal("yem_degrate");
                DynamicObject hscode = dynamicObject.getDynamicObject("yem_hscode");
                if (YEM.isEmpty(hscode)) {
                    sb.append(String.format("商品明细第 [ %s ] 行，海关编码为空，请填写后提交！", index + 1)).append("\r\n");
                }
            }
        }

        if (sb.length() > 0) {
            this.addErrorMessage(dataEntitie, sb.toString());
        }
    }

    /**
     * @description 整机生产信息中整机编号唯一性校验
     * @author xwudd
     * @param[1] dataEntitie
     * return
     * @time 2023/10/19 18:19
     */

    public void vehicleNoSingle(ExtendedDataEntity dataEntitie){
        DynamicObject dataEntity = dataEntitie.getDataEntity();
        String name = dataEntity.getDynamicObjectType().getName();
        Map<String, Map<Integer, List<String>>> map = new HashMap();
        String selectfields = DynamicObjectUtil.getSelectfields(name,false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,name,"yem_es_materialinfo",false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,name,"yem_es_materialinfo","yem_es_salesorder_z",false);
        DynamicObject[] shippingDetails = BusinessDataServiceHelper.load(name, selectfields,
                new QFilter[]{new QFilter("billno", QCP.not_equals,dataEntity.getString("billno")),
                        new QFilter("billstatus", QCP.in,new String[]{"B","C"})});
        for(DynamicObject shippingDetail : shippingDetails){
            String billNo = shippingDetail.getString("billno");
            DynamicObjectCollection materialInfos = shippingDetail.getDynamicObjectCollection("yem_es_materialinfo");
            HashMap<Integer, List<String>> materialInfoMap = new HashMap<>();
            for (int i = 0; i < materialInfos.size(); i++) {
                DynamicObject materialInfo = materialInfos.get(i);
                DynamicObjectCollection machineProductInfos = materialInfo.getDynamicObjectCollection("yem_es_salesorder_z");
                List<String> vehicleNoList = new ArrayList<>();
                for(DynamicObject machineProductInfo : machineProductInfos){
                    String vehicleNo = machineProductInfo.getString("yem_vehicleno");
                    vehicleNoList.add(vehicleNo);
                }
                materialInfoMap.put(i + 1,vehicleNoList);
            }
            map.put(billNo,materialInfoMap);
        }

        DynamicObjectCollection materialInfos = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        for (int i = 0; i < materialInfos.size(); i++) {
            DynamicObject materialInfo = materialInfos.get(i);
            DynamicObjectCollection machineProductInfos = materialInfo.getDynamicObjectCollection("yem_es_salesorder_z");
            for (int j = 0; j < machineProductInfos.size(); j++) {
                DynamicObject machineProductInfo = machineProductInfos.get(j);
                String vehicleNo = machineProductInfo.getString("yem_vehicleno");
                if(YEM.isNotEmpty(vehicleNo)){
                    Set<String> mapKeys = map.keySet();
                    for(String mapKey : mapKeys){
                        Map<Integer, List<String>> materialInfoMap = map.get(mapKey);
                        Set<Integer> materialInfoMapKeys = materialInfoMap.keySet();
                        for (Integer materialInfoMapKey : materialInfoMapKeys){
                            List<String> vehicleNoList = materialInfoMap.get(materialInfoMapKey);
                            if(vehicleNoList.contains(vehicleNo)){
                                this.addErrorMessage(dataEntitie,
                                        String.format("明细信息第%s行的子分录整机生产信息第%s行的整机编号【%s】，与出运明细单号【%s】的明细信息第%s行的子分录整机生产信息中的整机编号【%s】重复！",i + 1,j + 1,vehicleNo,mapKey,materialInfoMapKey,vehicleNo));
                            }
                        }
                    }
                }
            }
        }

        List<String> list = new ArrayList();
        for (int i = 0; i < materialInfos.size(); i++) {
            DynamicObject materialInfo = materialInfos.get(i);
            DynamicObjectCollection machineProductInfos = materialInfo.getDynamicObjectCollection("yem_es_salesorder_z");
            for (int j = 0; j < machineProductInfos.size(); j++) {
                DynamicObject machineProductInfo = machineProductInfos.get(j);
                String vehicleNo = machineProductInfo.getString("yem_vehicleno");
                if(YEM.isNotEmpty(vehicleNo)){
                    if(list.contains(vehicleNo)){
                        this.addErrorMessage(dataEntitie,
                                String.format("商品明细第%s行的子分录整机生产信息第%s行的整机编号【%s】与本单的整机生产信息中的整机编号重复！",i + 1,j + 1,vehicleNo));
                    }else{
                        list.add(vehicleNo);
                    }
                }
            }
        }
    }
}
