package com.yem.wm.es.storagetrans.op;

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.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.bouncycastle.bcpg.sig.IntendedRecipientFingerprint;

import java.util.*;

/**
 * @Description TODO
 * @Date 2024/3/15 17:40
 * @Created by ZZSLL
 */

public class StorageTransSubmitOp extends AbstractOperationServicePlugIn
{
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e)
    {
        super.onPreparePropertys(e);
        List<String> keys = e.getFieldKeys();
        keys.add("yem_creditbackstatus");
        keys.add("billno");
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        e.addValidator(new AbstractValidator() {
            @Override
            public void validate() {
                ExtendedDataEntity[] extendedDataEntities = this.getDataEntities();
                for (ExtendedDataEntity extendedDataEntity : extendedDataEntities) {
                    DynamicObject dataEntity = extendedDataEntity.getDataEntity();
                    dataEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), dataEntity.getDataEntityType().getName());
                    String[] res = validatorSwiftCode(dataEntity);
                    if (!res[0].isEmpty()) {
                        this.addErrorMessage(extendedDataEntity, res[0]);
                    }
                    if (!res[1].isEmpty()) {
                        this.addErrorMessage(extendedDataEntity, res[1]);
                    }
                }
            }
        });
    }

    public static String[] validatorSwiftCode(DynamicObject dataEntity) {
        StringBuilder input = new StringBuilder();
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_salescontrac_s");
        Map<String, List<Integer>> map = new HashMap<>();
        Map<String, Set<String>> setMap = new HashMap<>();

        for (DynamicObject dynamicObject : collection) {
            int index = collection.indexOf(dynamicObject) + 1;
            String issinosure = dynamicObject.getString("yem_issinosure");//是否信保
            long rapstyleId = dynamicObject.getLong("yem_rapstyle.id");//结算方式
            String swiftcode = dynamicObject.getString("yem_swiftcode");
            if ("A".equals(issinosure)) {
                if (YEM.isNotEmpty(rapstyleId) && YEM.isNotEmpty(swiftcode)) {
                    Set<String> set = new HashSet<>();
                    String key = String.valueOf(rapstyleId);
                    List<Integer> list = new ArrayList<>();
                    if (map.containsKey(key)) {
                        list = map.get(key);
                        set = setMap.get(key);
                    }
                    list.add(index);
                    set.add(swiftcode);
                    map.put(key, list);
                    setMap.put(key, set);
                }

                String rapstyleName = dynamicObject.getString("yem_rapstyle.name");

                if ("信用证".equals(rapstyleName) && YEM.isEmpty(swiftcode)) {
                    input.append(String.format("收款明细第 %s 行，SWIFT CODE必录，请填写后提交!!", index)).append("\r\n");
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Set<String>> entry : setMap.entrySet()) {
            Set<String> value = entry.getValue();
            String key = entry.getKey();
            if (value.size() > 1) {
                sb.append(String.format("收款计划第 %s 行，结算方式 SWIFT CODE 需要唯一，请修改后提交!!", map.get(key))).append("\r\n");
            }
        }
//        if (sb.length() > 0) {
//            this.addErrorMessage(extendedDataEntity, sb.toString());
//        }
//        if (input.length() > 0) {
//            this.addErrorMessage(extendedDataEntity, input.toString());
//        }
        return new String[]{sb.toString(), input.toString()};
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e)
    {
        super.beforeExecuteOperationTransaction(e);
        DynamicObject[] eDataEntities = e.getDataEntities();

        for (DynamicObject eDataEntity : eDataEntities) {
            eDataEntity = BusinessDataServiceHelper.loadSingle(eDataEntity.getPkValue(), eDataEntity.getDynamicObjectType().getName());

            DynamicObjectCollection collection = eDataEntity.getDynamicObjectCollection("yem_creditdetail");

            if (!collection.isEmpty()) {
                String creditbackstatus = eDataEntity.getString("yem_creditbackstatus");
                String billno = eDataEntity.getString("billno");
                if (!"A".equals(creditbackstatus)) {
                    e.setCancelMessage("单据 [ "+ billno +" ] 未进行信保回填确认，不允许提交！");
                    e.setCancel(true);
                }
            }
        }
    }
}
