package com.yem.wm.im.debcrednotenew.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 kd.bos.servicehelper.QueryServiceHelper;

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

/**
 * @author zhouc
 * @date 2024/3/29 22:17
 * @className DebCredNewAuditValidatorOp
 * @description
 */
public class DebCredNewAuditValidatorOp extends AbstractValidator {

    @Override
    public void validate() {
        ExtendedDataEntity[] dataEntities = this.getDataEntities();
        for (ExtendedDataEntity dataEntitie : dataEntities) {
            DynamicObject dataEntity = dataEntitie.getDataEntity();
            dataEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), dataEntity.getDynamicObjectType().getName());
            DynamicObject yem_groupcusfields = dataEntity.getDynamicObject("yem_groupcusfields");
            if (yem_groupcusfields == null) {
                this.addErrorMessage(dataEntitie, "对应集团客户不能为空，如果没有集团客户请在《客户》维护后再尝试操作！");
            }
            //客户
            String customername = "";
            DynamicObject yem_customer = dataEntity.getDynamicObject("yem_customer");
            if (yem_customer != null) {
                customername = yem_customer.getString("name");
            }
            //产品类型
            String productsname = "";
            DynamicObject yem_bd_products = dataEntity.getDynamicObject("yem_bd_products");
            if (yem_bd_products != null) {
                String number = yem_bd_products.getString("number");
                if (number.contains("ZZJ")) {
                    productsname = "装载机";
                } else if (number.contains("CC")) {
                    productsname = "叉车";
                } else if (number.contains("TLJ")) {
                    productsname = "拖拉机";
                }
            }
            //借贷业务类型
            DynamicObject yem_credittype = dataEntity.getDynamicObject("yem_credittype");
            //借/贷类型
            String debcredtype = "";
            String yem_debcredtype = dataEntity.getString("yem_debcredtype");
            if (yem_debcredtype.equals("DN")) {
                debcredtype = "借记类型（-）";
            } else if (yem_debcredtype.equals("CN")) {
                debcredtype = "贷记类型（+）";
            }
            //转换贷记单
            String yem_billtype = dataEntity.getString("yem_billtype.number");
            if (yem_billtype.equals("yem_debcrednote_a")) {
                String yem_adjustdirection = dataEntity.getString("yem_adjustdirection");
                BigDecimal yem_adjustexrate = dataEntity.getBigDecimal("yem_adjustexrate");
                if (yem_adjustexrate.compareTo(BigDecimal.ZERO) == 0) {
                    this.addErrorMessage(dataEntitie, "转换贷记单，转换汇率必填!");
                }
                DynamicObjectCollection data = quespcapitalpool(dataEntity);
                if (data.size() > 0) {
                    //实际
                    Map<String, BigDecimal> map = new HashMap<>();
                    //预计
                    Map<String, BigDecimal> map1 = new HashMap<>();
                    for (int i = 0; i < data.size(); i++) {
                        DynamicObject dynamicObject = data.get(i);
                        String yem_curr = dynamicObject.getString("yem_spcapitalpool_a.yem_curr");
                        DynamicObject bd_currency = BusinessDataServiceHelper.loadSingle(yem_curr, "bd_currency");
                        String number = bd_currency.getString("number");
                        BigDecimal yem_noamo = dynamicObject.getBigDecimal("yem_spcapitalpool_a.yem_actremaamount");//实际剩余金额
                        BigDecimal yem_estamount = dynamicObject.getBigDecimal("yem_spcapitalpool_a.yem_estamount");//预计剩余金额
                        if (map.containsKey(number)) {
                            BigDecimal bigDecimal = map.get(number);
                            map.put(number, bigDecimal.add(yem_noamo));
                            BigDecimal bigDecimal1 = map1.get(number);
                            map1.put(number, bigDecimal1.add(yem_estamount));
                        } else {
                            map.put(number, yem_noamo);
                            map1.put(number, yem_estamount);
                        }
                    }
                    //调整人民币
                    BigDecimal yem_directionrmbamt = dataEntity.getBigDecimal("yem_directionrmbamt");
                    //调整美元
                    BigDecimal yem_directionusdamt = dataEntity.getBigDecimal("yem_directionusdamt");
                    BigDecimal cny = map.get("CNY");
                    BigDecimal usd = map.get("USD");
                    if (yem_adjustdirection.equals("CNY_USD")) {
                        if (yem_directionrmbamt.compareTo(cny) == 1) {
                            this.addErrorMessage(dataEntitie, "根据客户【" + customername + "】、" +
                                    "产品类型【" + productsname + "】、借/贷类型【" + debcredtype + "】、" +
                                    "借贷业务类型【" + yem_credittype.getString("name") + "】" +
                                    "查询到【人民币】实际剩余金额为【" + cny.setScale(2, BigDecimal.ROUND_HALF_UP) + "】" +
                                    "小于调整人民币金额【" + yem_directionrmbamt.setScale(2, BigDecimal.ROUND_HALF_UP) + "】" +
                                    "，无法生成《转换贷记单》，请修改后重试");
                        }
                    }
                    if (yem_adjustdirection.equals("USD_CNY")) {
                        if (yem_directionusdamt.compareTo(usd) == 1) {
                            this.addErrorMessage(dataEntitie, "根据客户【" + customername + "】、" +
                                    "产品类型【" + productsname + "】、借/贷类型【" + debcredtype + "】、" +
                                    "借贷业务类型【" + yem_credittype.getString("name") + "】" +
                                    "查询到【美元】实际剩余金额未【" + usd.setScale(2, BigDecimal.ROUND_HALF_UP) + "】" +
                                    "小于调整美元金额【" + yem_directionusdamt.setScale(2, BigDecimal.ROUND_HALF_UP) + "】" +
                                    "，无法生成《转换贷记单》，请修改后重试");
                        }
                    }
                } else {
                    this.addErrorMessage(dataEntitie, "根据客户【" + customername + "】、" +
                            "产品类型【" + productsname + "】、借/贷类型【" + debcredtype + "】、" +
                            "借贷业务类型【" + yem_credittype.getString("name") + "】" +
                            "未获取到满足条件的配件资金池，无法生成《转换贷记单》，请修改后重试");
                }
            }
            //贷记单
            if (yem_billtype.equals("yem_debcrednote_d")) {
                DynamicObjectCollection data = quespcapitalpool(dataEntity);
                if (data.size() > 0) {
                    //预计
                    Map<String, BigDecimal> map1 = new HashMap<>();
                    for (int i = 0; i < data.size(); i++) {
                        DynamicObject dynamicObject = data.get(i);
                        String yem_curr = dynamicObject.getString("yem_spcapitalpool_a.yem_curr");
                        BigDecimal yem_estamount = dynamicObject.getBigDecimal("yem_spcapitalpool_a.yem_estamount");//预计剩余金额
                        if (map1.containsKey(yem_curr)) {
                            BigDecimal bigDecimal1 = map1.get(yem_curr);
                            map1.put(yem_curr, bigDecimal1.add(yem_estamount));
                        } else {
                            map1.put(yem_curr, yem_estamount);
                        }
                    }
                    String yem_currency = dataEntity.getString("yem_currency.number");
                    String currency = dataEntity.getString("yem_currency.id");
                    BigDecimal yem_amount = dataEntity.getBigDecimal("yem_amount");//配件资金池增加金额
                    BigDecimal yem_amount_sub = dataEntity.getBigDecimal("yem_amount_sub");//配件资金池扣减金额
                    if (yem_currency.equals("CNY")) {

                        BigDecimal bigDecimal = BigDecimal.ZERO;
                        if (map1.containsKey(currency)) {
                            bigDecimal = map1.get(currency);
                        }
                        BigDecimal sumamount = yem_amount.add(bigDecimal);
                        if (sumamount.compareTo(yem_amount_sub) == -1) {
                            this.addErrorMessage(dataEntitie, "根据客户【" + customername + "】、" +
                                    "产品类型【" + productsname + "】、借/贷类型【" + debcredtype + "】、" +
                                    "借贷业务类型【" + yem_credittype.getString("name") + "】" +
                                    "查询到【人民币】预计剩余金额【" + bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP) + "】" +
                                    "加上本次来源金额汇总【" + yem_amount.setScale(2, BigDecimal.ROUND_HALF_UP) + "】" +
                                    "小于去向汇总金额【" + yem_amount_sub.setScale(2, BigDecimal.ROUND_HALF_UP) + "】" +
                                    "，请修改后重试");
                        }
                    }
                    if (yem_currency.equals("USD")) {
                        BigDecimal bigDecimal = BigDecimal.ZERO;
                        if (map1.containsKey(currency)) {
                            bigDecimal = map1.get(currency);
                        }
                        BigDecimal sumamount = yem_amount.add(bigDecimal);
                        if (sumamount.compareTo(yem_amount_sub) == -1) {
                            this.addErrorMessage(dataEntitie, "根据客户【" + customername + "】、" +
                                    "产品类型【" + productsname + "】、借/贷类型【" + debcredtype + "】、" +
                                    "借贷业务类型【" + yem_credittype.getString("name") + "】" +
                                    "查询到【美元】预计剩余金额【" + bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP) + "】" +
                                    "加上本次来源金额汇总【" + yem_amount.setScale(2, BigDecimal.ROUND_HALF_UP) + "】" +
                                    "小于去向汇总金额【" + yem_amount_sub.setScale(2, BigDecimal.ROUND_HALF_UP) + "】" +
                                    "，请修改后重试");
                        }
                    }
                }
            }

            //校验核销金额
            List list = new ArrayList<>();
            Map<Long, BigDecimal> map = new HashMap<>();
            DynamicObjectCollection yem_creditnotedes = dataEntity.getDynamicObjectCollection("yem_creditnotedes");
            for (int i = 0; i < yem_creditnotedes.size(); i++) {
                DynamicObject dynamicObject = yem_creditnotedes.get(i);
                BigDecimal yem_amount_d = dynamicObject.getBigDecimal("yem_amount_d");
                DynamicObject yem_debcrednoteno = dynamicObject.getDynamicObject("yem_debcrednoteno");
                if (yem_debcrednoteno != null) {
                    long id = yem_debcrednoteno.getLong("id");
                    list.add(id);
                    if (map.containsKey(id)) {
                        BigDecimal bigDecimal = map.get(id);
                        map.put(id, bigDecimal.add(yem_amount_d));
                    } else {
                        map.put(id, yem_amount_d);
                    }
                }
            }
            QFilter qFilter = new QFilter("id", QCP.in, list);//
            String selectfield = DynamicObjectUtil.getSelectfields("yem_debcrednote", false);
            String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, "yem_debcrednote", "yem_creditnotedes", false);
            DynamicObjectCollection Object = QueryServiceHelper.query("yem_debcrednote", "id,"+selectfields, qFilter.toArray());
            if (Object.size() > 0) {
                for(DynamicObject dynamicObject:Object){
                    String billno = dynamicObject.getString("billno");
                    long id = dynamicObject.getLong("id");
                    if(map.containsKey(id)){
                        BigDecimal yem_amount = dynamicObject.getBigDecimal("yem_amount");//配件资金池增加金额
                        BigDecimal yem_towardwriteamt = dynamicObject.getBigDecimal("yem_towardwriteamt");//预计核销金额
                        BigDecimal add = yem_towardwriteamt.add(map.get(id));
                        if(yem_amount.subtract(add).compareTo(BigDecimal.ZERO) == -1){
                            this.addErrorMessage(dataEntitie, "选择借记单【"+billno+"】，来源总金额为【"+yem_amount.setScale(2, BigDecimal.ROUND_HALF_UP)+"】" +
                                    "，已核销【"+yem_towardwriteamt.setScale(2, BigDecimal.ROUND_HALF_UP)+"】，" +
                                    "加上本次核销【"+map.get(id).setScale(2, BigDecimal.ROUND_HALF_UP)+"】，小于零，请修改后重试!l");
                        }

                    }
                }
            }
        }
    }

    public DynamicObjectCollection quespcapitalpool(DynamicObject dataEntity) {
        //组织
        DynamicObject org = dataEntity.getDynamicObject("org");
        //客户
        DynamicObject yem_groupcustomers = null;
        DynamicObject yem_customer = dataEntity.getDynamicObject("yem_customer");
        if (yem_customer != null) {
            yem_groupcustomers = yem_customer.getDynamicObject("yem_groupcustomers");
        }
        //产品类型
        String products = "";
        DynamicObject yem_bd_products = dataEntity.getDynamicObject("yem_bd_products");
        if (yem_bd_products != null) {
            String number = yem_bd_products.getString("number");
            if (number.contains("ZZJ")) {
                products = "ZZJ";
            } else if (number.contains("CC")) {
                products = "CC";
            } else if (number.contains("TLJ")) {
                products = "TLJ";
            }
        }
        //借贷业务类型
        DynamicObject yem_credittype = dataEntity.getDynamicObject("yem_credittype");
        //借/贷类型l
        String yem_debcredtype = dataEntity.getString("yem_debcredtype");
        QFilter qFilter = new QFilter("billstatus", QCP.equals, "C");//
        qFilter.and(new QFilter("org.id", QCP.equals, org.getLong("id")));
        qFilter.and(new QFilter("yem_customer.id", QCP.equals, yem_groupcustomers.getLong("id")));
        qFilter.and(new QFilter("yem_bd_products.number", QCP.equals, products));
        qFilter.and(new QFilter("yem_spcapitalpool_a.yem_creditype.id", QCP.equals, yem_credittype.getLong("id")));
        qFilter.and(new QFilter("yem_spcapitalpool_a.yem_debcredtype", QCP.equals, yem_debcredtype));
        String selectfield = DynamicObjectUtil.getSelectfields("yem_spcapitalpool", false);
        String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, "yem_spcapitalpool", "yem_spcapitalpool_a", false);
        DynamicObjectCollection data = QueryServiceHelper.query("yem_spcapitalpool", selectfields, new QFilter[]{qFilter}, "billno");
        return data;
    }
}
