package com.yem.wm.es.Util;

import com.yem.wm.es.shippingdetails.util.PaymentControlUtil;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.*;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author xwudd
 * @date 14:45
 * @Description
 **/
public class TotalUtil {

    /**
     * @description 计算收汇金额
     * @author xwudd
     * return
     * @time 2023/8/7 18:04
     */

    public static void countRapAmt(IDataModel model, String entryKey) {
        DynamicObject recCondition = (DynamicObject) model.getValue("yem_reccondition");
        if (YEM.isNotEmpty(recCondition)) {
            String basis = recCondition.getString("basis");
            BigDecimal billAmt = (BigDecimal) model.getValue("yem_offeramount");
            if ("A".equals(basis) && billAmt.compareTo(BigDecimal.ZERO) > 0) {
//                int salescontracs = model.getEntryRowCount(entryKey);
//                for (int i = 0; i < salescontracs; i++) {
//                    BigDecimal rapRate = (BigDecimal) model.getValue("yem_raprate", i);
//                    model.setValue("yem_rapamt", billAmt.multiply(rapRate.divide(new BigDecimal(100))), i);
//                }
//                DynamicObject dataEntity = model.getDataEntity(true);
//                DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
                BigDecimal offeramount = billAmt;
//
//                for (DynamicObject dynamicObject : collection) {
//                    offeramount = offeramount.add(dynamicObject.getBigDecimal("yem_saamtpriceclause"));
//                }

                int rowCount = model.getEntryRowCount(entryKey);
                BigDecimal excludeLastRow = BigDecimal.ZERO;
                for (int i = 0; i < rowCount - 1; i++) {
//                    BigDecimal rowRaprate = (BigDecimal) model.getValue("yem_raprate", i);
                    BigDecimal raprate = (BigDecimal) model.getValue("yem_raprate", i);
                    excludeLastRow = excludeLastRow.add(PaymentControlUtil.getAdvancePayment(raprate, offeramount).setScale(2, RoundingMode.HALF_UP));
                    model.setValue("yem_rapamt", PaymentControlUtil.getAdvancePayment(raprate, offeramount), i);
                }
                model.setValue("yem_rapamt", offeramount.subtract(excludeLastRow).setScale(2, RoundingMode.UP), rowCount - 1);
            }
        }
    }

    /**
     * @description 计算收汇比率
     * @author xwudd
     * return
     * @time 2023/8/7 18:04
     */

    public static void countRapRate(IDataModel model, String entryKey) {
        DynamicObject recCondition = (DynamicObject) model.getValue("yem_reccondition");
        if (YEM.isNotEmpty(recCondition)) {
            String basis = recCondition.getString("basis");
            BigDecimal total = BigDecimal.ZERO;
            BigDecimal exLastRow = BigDecimal.ZERO;
            if ("B".equals(basis)) {
                int salescontracs = model.getEntryRowCount(entryKey);
                for (int i = 0; i < salescontracs; i++) {
                    BigDecimal rapAmt = (BigDecimal) model.getValue("yem_rapamt", i);
                    total = total.add(rapAmt);
                }
                for (int i = 0; i < salescontracs; i++) {
                    if (i == salescontracs - 1) {
                        model.setValue("yem_raprate", new BigDecimal("100").subtract(exLastRow), i);
                    } else {
                        BigDecimal rapAmt = (BigDecimal) model.getValue("yem_rapamt", i);
                        BigDecimal divide = rapAmt.multiply(new BigDecimal(100)).divide(total, 10, RoundingMode.HALF_DOWN);
                        model.setValue("yem_raprate", divide, i);
                        exLastRow = exLastRow.add(divide);
                    }
                }
            }
        }
    }

    /**
     * @Description 汇总表头大柜数量
     */
    public static void countBigCabinetQty(IDataModel model) {
        BigDecimal totalQty = BigDecimal.ZERO;
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        for (int i = 0; i < materialInfoRows; i++) {
            totalQty = totalQty.add((BigDecimal) model.getValue("yem_bigcabinetnumbers", i));
        }
        model.setValue("yem_bigcabinetnumber", totalQty);
    }

    /**
     * @Description 汇总表头小柜数量
     */
    public static void countSmallCabinetQty(IDataModel model) {
        BigDecimal totalQty = BigDecimal.ZERO;
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        for (int i = 0; i < materialInfoRows; i++) {
            totalQty = totalQty.add((BigDecimal) model.getValue("yem_mincabinetnumbers", i));
        }
        model.setValue("yem_mincabinetnumber", totalQty);
    }

    /**
     * @description 根据明细信息的 基础机型和数量 带出礼品赠送分录
     * @author xwudd
     * return
     * @time 2023/8/8 10:56
     */

    public static void setGiftGiving(IDataModel model) {
        String isGiftGive = (String) model.getValue("yem_isgiftgive");
        if ("A".equals(isGiftGive)) {
            model.deleteEntryData("yem_es_salesorder_l");
            Map<Long, BigDecimal> map = new HashMap<>();
            int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
            for (int i = 0; i < materialInfoRows; i++) {
                DynamicObject productModel = (DynamicObject) model.getValue("yem_productmodel", i);
                if (YEM.isNotEmpty(productModel)) {
                    DynamicObject products = productModel.getDynamicObject("yem_products");
                    if (YEM.isNotEmpty(products)) {
                        Long productsId = products.getLong("id");
                        BigDecimal qty = (BigDecimal) model.getValue("yem_qty", i);
                        if (map.containsKey(productsId)) {
                            qty = map.get(productsId).add(qty);
                        }
                        map.put(productsId, qty);
                    }
                }
            }
            BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");
            Set<Long> productModelIds = map.keySet();
            DynamicObject[] giftRules = BusinessDataServiceHelper.load("yem_bd_giftrules", "id,yem_bd_giftrules_a.yem_producttype,yem_bd_giftrules_a.yem_qty,yem_bd_giftrules_a.yem_giveamo,yem_bd_giftrules_a.yem_remarka",
                    new QFilter[]{new QFilter("yem_bd_giftrules_a.yem_producttype", QCP.in, productModelIds.toArray(new Long[productModelIds.size()]))});
            for (DynamicObject giftRule : giftRules) {
                DynamicObjectCollection giftRules_as = giftRule.getDynamicObjectCollection("yem_bd_giftrules_a");
                for (DynamicObject giftRules_a : giftRules_as) {
                    DynamicObject productType = giftRules_a.getDynamicObject("yem_producttype");
                    if (YEM.isNotEmpty(productType)) {
                        Long id = productType.getLong("id");
                        if (map.containsKey(id)) {
                            int entryRow = model.createNewEntryRow("yem_es_salesorder_l");
                            BigDecimal tsagerQty = map.get(id);
                            BigDecimal giveAmoBase = giftRules_a.getBigDecimal("yem_giveamo");
                            BigDecimal giveAmo = giveAmoBase.divide(exrate, RoundingMode.HALF_DOWN);
                            model.setValue("yem_giftproactype", productType, entryRow);//产品机型
                            model.setValue("yem_tsagerqty", tsagerQty, entryRow);//台数
                            model.setValue("yem_singlegiftamt", giveAmo, entryRow);//单台礼品金额
                            model.setValue("yem_singlegiftamtloc", giveAmoBase, entryRow);//单台礼品金额本位币
                            model.setValue("yem_giftamt", tsagerQty.multiply(giveAmo), entryRow);//礼品金额
                            model.setValue("yem_giftamtbase", tsagerQty.multiply(giveAmoBase), entryRow);//礼品金额本位币
                        }
                    }
                }
            }
        }
    }


    /**
     * @description 计算体积m3
     * @author xwudd
     * @param[1] model
     * @param[2] rowIndex
     * @param[3] fieldKeys
     * return
     * @time 2023/8/30 11:51
     */
    public static void countVolM3(IDataModel model, int rowIndex, String... fieldKeys) {
        BigDecimal VolM3 = BigDecimal.ZERO;
        DynamicObject longType = (DynamicObject) model.getValue(fieldKeys[0]);
        String longTypeNumber = YEM.isNotEmpty(longType) ? longType.getString("number") : "";
        BigDecimal vol = (BigDecimal) model.getValue(fieldKeys[1], rowIndex);
        if ("mm".equals(longTypeNumber)) {
            VolM3 = vol.divide(new BigDecimal(1000000000), RoundingMode.HALF_UP);
        }
        if ("cm".equals(longTypeNumber)) {
            VolM3 = vol.divide(new BigDecimal(1000000), RoundingMode.HALF_UP);
        }
        if ("dm".equals(longTypeNumber)) {
            VolM3 = vol.divide(new BigDecimal(1000), RoundingMode.HALF_UP);
        }
        if ("m".equals(longTypeNumber)) {
            VolM3 = vol;
        }
        if ("km".equals(longTypeNumber)) {
            VolM3 = vol.multiply(new BigDecimal(1000000000));
        }
        model.setValue(fieldKeys[2], VolM3, rowIndex);
    }


    public void countMultiplyEntry(IDataModel model, int rowIndex, String... fieldKeys) {
        BigDecimal totalValue = BigDecimal.ONE;
        for (int i = 0; i < fieldKeys.length - 1; i++) {
            BigDecimal value = (BigDecimal) model.getValue(fieldKeys[i], rowIndex);
            totalValue = totalValue.multiply(value);
        }
        model.setValue(fieldKeys[fieldKeys.length - 1], totalValue);
    }

    public void countDivEntry(IDataModel model, int rowIndex, String... fieldKeys) {
        BigDecimal value1 = (BigDecimal) model.getValue(fieldKeys[0], rowIndex);
        BigDecimal value2 = (BigDecimal) model.getValue(fieldKeys[1], rowIndex);
        if (value1.compareTo(BigDecimal.ZERO) != 0 && value2.compareTo(BigDecimal.ZERO) != 0) {
            model.setValue(fieldKeys[2], value1.divide(value2, RoundingMode.HALF_UP), rowIndex);
        }
    }


    /**
     * @description 获取所属国家地区的信保费率基础资料
     * @author xwudd
     * @param[1] commCountry 国家和地区基础资料
     * return
     * @time 2023/8/31 11:04
     */

    public static DynamicObject getCountrySignals(DynamicObject commCountry) {
        if (YEM.isNotEmpty(commCountry)) {
            DynamicObject signals = BusinessDataServiceHelper.loadSingle("yem_bd_signals", "yem_country,yem_bd_signals_em.yem_payment,yem_bd_signals_em.yem_term,yem_bd_signals_em.yem_rate",
                    new QFilter[]{new QFilter("yem_country", QCP.equals, commCountry.getPkValue())});
            return signals;
        } else {
            return null;
        }
    }


    /**
     * @description 获取该信保费率基础资料中结算方式和信用期限相匹配的信保费率
     * @author xwudd
     * @param[1] signals 信保费率基础资料
     * @param[2] rapStyle 结算方式
     * @param[3] term 信保费率
     * return
     * @time 2023/8/31 11:06
     */

    public static BigDecimal getSignals(DynamicObject signals, DynamicObject rapStyle, DynamicObject term) {
        BigDecimal rate = BigDecimal.ZERO;
        if (YEM.isNotEmpty(signals)) {
            DynamicObjectCollection signals_ems = signals.getDynamicObjectCollection("yem_bd_signals_em");
            if (YEM.isNotEmpty(rapStyle) && YEM.isNotEmpty(term)) {
                for (DynamicObject signals_em : signals_ems) {
                    DynamicObject yem_payment = signals_em.getDynamicObject("yem_payment");
                    DynamicObject yem_term = signals_em.getDynamicObject("yem_term");
                    if (YEM.isNotEmpty(yem_payment) && YEM.isNotEmpty(yem_term)) {
                        if (rapStyle.getLong("id") == yem_payment.getLong("id") &&
                                term.getLong("id") == yem_term.getLong("id")) {
                            rate = signals_em.getBigDecimal("yem_rate");
                        }
                    }
                }
            }
        }
        return rate;
    }


    /**
     * @description 根据客户查询 客户信保额度申请
     * @author xwudd
     * @param[1] customer
     * return
     * @time 2023/9/1 16:44
     */

    public static DynamicObject getCsrCreditLine(DynamicObject customer, DynamicObject method, DynamicObject company, String swiftCode) {
        if (YEM.isNotEmpty(customer) && YEM.isNotEmpty(method) && YEM.isNotEmpty(company)) {
            String selectfields = DynamicObjectUtil.getSelectfields("yem_im_csrcreditline", false);
            selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_im_csrcreditline", "yem_im_info", false);
            QFilter qFilter = new QFilter("yem_customer", QCP.equals, customer.getPkValue());
            qFilter.and(new QFilter("yem_payment.id", QCP.equals, method.getPkValue()));
            qFilter.and(new QFilter("org", QCP.equals, company.getPkValue()));
            qFilter.and(new QFilter("billstatus", QCP.equals, "C"));
            if ("信用证".equals(method.getString("name"))) {
                qFilter.and(new QFilter("yem_swiftcode", QCP.equals, swiftCode));
            }

            return BusinessDataServiceHelper.loadSingle("yem_im_csrcreditline", "id," + selectfields, qFilter.toArray());
        } else {
            return null;
        }
    }

    public static DynamicObject getSettlementMethod(DynamicObject storagetrans) {
        storagetrans = BusinessDataServiceHelper.loadSingle(storagetrans.getPkValue(), storagetrans.getDataEntityType().getName());
        DynamicObjectCollection collection = storagetrans.getDynamicObjectCollection("yem_es_salescontrac_s");
        for (DynamicObject object : collection) {
            String issinosure = object.getString("yem_issinosure");
            if ("A".equals(issinosure)) {
                return object.getDynamicObject("yem_rapstyle");
            }
        }
        return null;
    }

    public static String getSwiftCode(DynamicObject storagetrans) {
        storagetrans = BusinessDataServiceHelper.loadSingle(storagetrans.getPkValue(), storagetrans.getDataEntityType().getName());
        DynamicObjectCollection collection = storagetrans.getDynamicObjectCollection("yem_es_salescontrac_s");
        for (DynamicObject object : collection) {
            String issinosure = object.getString("yem_issinosure");
            String swiftcode = object.getString("yem_swiftcode");
            if ("A".equals(issinosure) && YEM.isNotEmpty(swiftcode)) {
                return swiftcode;
            }
        }
        return null;
    }


    public void getPlanPinMaps(String productCode) {
        Map<String, String> map = new HashMap();
        map.put("product_code", productCode);
    }

    /**
     * @description 使用额度  折扣金额校验
     * @author xwudd
     * @param[1] dataEntity
     * @param[2] entryKey
     * return
     * @time 2023/9/21 15:37
     */

    public static String fundPoolAmtValidator(DynamicObject dataEntity, String entryKey) {
        String fundUseType = dataEntity.getString("yem_fundusetype");
        if ("B".equals(fundUseType)) {
            BigDecimal fundPoolAmt = dataEntity.getBigDecimal("yem_fundpoolamt");
            if (fundPoolAmt.compareTo(BigDecimal.ZERO) <= 0) {
                return "使用配件资金池，使用额度必须不能为空！";
            } else {
                BigDecimal disAmtTotal = BigDecimal.ZERO;
                DynamicObjectCollection entrys = dataEntity.getDynamicObjectCollection(entryKey);
                for (DynamicObject entry : entrys) {
                    disAmtTotal = disAmtTotal.add(entry.getBigDecimal("yem_disamt"));
                }
                if (!(disAmtTotal.compareTo(fundPoolAmt) == 0)) {
                    return String.format("配件资金使用额度【%s】与明细信息折扣金额汇总金额【%s】不一致，请调整数据！", fundPoolAmt, disAmtTotal);
                }
            }
        }
        return null;
    }


    public static void toolTip(AbstractBillPlugIn abp, PropertyChangedArgs e) {
        IFormView view = abp.getView();
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        IPageCache pageCache = abp.getPageCache();
        DynamicObject oldValue = (DynamicObject) changeData.getOldValue();
        pageCache.put("productsOldValue", oldValue != null ? oldValue.getPkValue() + "" : "");
        view.showConfirm("切换产品分类，将清空明细信息分录，请确认是否继续？", MessageBoxOptions.YesNo,
                new ConfirmCallBackListener(name, abp));
    }

    public static void confirmCallBackFunc(MessageBoxClosedEvent e, String... entryKeys) {
        String callBackId = e.getCallBackId();
        MessageBoxResult result = e.getResult();
        IFormView view = (IFormView) e.getSource();
        IDataModel model = view.getModel();
        IPageCache pageCache = view.getPageCache();
        if (result == MessageBoxResult.Yes) {
            if ("yem_bd_products".equals(callBackId)) {
                for (String entryKey : entryKeys) {
                    model.deleteEntryData(entryKey);
                }
            }
        }
        if (result == MessageBoxResult.No) {
            if ("yem_bd_products".equals(callBackId)) {
                model.beginInit();
                String productsOldValue = pageCache.get("productsOldValue");
                if (YEM.isEmpty(productsOldValue)) {
                    model.setValue("yem_bd_products", null);
                } else {
                    model.setValue("yem_bd_products", Long.parseLong(productsOldValue));
                }
                model.endInit();
                view.updateView("yem_bd_products");
            }
        }
    }


    /**
     * @description 物料为空时  计量单位  基本计量单位 为台
     * @author xwudd
     * @param[1] model
     * @param[2] rowIndex
     * return
     * @time 2023/11/28 11:16
     */

    public static void setUnit(IDataModel model, int rowIndex) {
        DynamicObject materiel = (DynamicObject) model.getValue("yem_materiel", rowIndex);
        if (YEM.isEmpty(materiel)) {
            DynamicObject unit = BusinessDataServiceHelper.loadSingle("bd_measureunits", "id",
                    new QFilter[]{new QFilter("number", QCP.equals, "TAI"),
                            new QFilter("enable", QCP.equals, "1")});
            model.setValue("yem_unit", unit, rowIndex);
            model.setValue("yem_baseunit", unit, rowIndex);
        }
    }
}
