package com.yem.wm.es.salesorder.from;

import com.yem.wm.utils.DynamicObjectUtil;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.IFormView;
import kd.bos.form.field.*;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
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.*;

/**
 * @author zhouc
 * @date 2024/3/22 16:55
 * @className SaleOrderCreditFromEdit
 * @description 合同贷记功能表单插件
 */
public class SaleOrderCreditFromEdit extends AbstractBillPlugIn implements BeforeF7SelectListener {

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObject yem_billtype = dataEntity.getDynamicObject("yem_billtype");
        if (yem_billtype != null) {
            String number = yem_billtype.getString("number");
            if (number.equals("yem_es_salesorder_ZJ") || number.equals("yem_es_salesorder_nmzj")) {
                Map map = new HashMap<>();
                map.put("客户配件资金池", "B");
                fillEntityCombo(map, "yem_fundusetype");
                Map map1 = new HashMap<>();
                map1.put("按金额（全额抵扣）", "C");
                fillEntityCombo(map1, "yem_accamtusetype");
            }
        }
    }

    /**
     * @param map 下拉项值
     */
    private void fillEntityCombo(Map<String, Object> map, String key) {
        ComboEdit mainentry = (ComboEdit) this.getView().getControl(key);
        if (map.size() > 0) {
            List<ComboItem> entryItems = this.buildEntryComboItems(map);
            mainentry.setComboItems(entryItems);
        } else {
            mainentry.setComboItems(null);
        }
    }

    /**
     * @param entitys
     * @return
     */
    private List<ComboItem> buildEntryComboItems(Map<String, Object> entitys) {
        ArrayList<ComboItem> entryItems = new ArrayList<>();
        ComboItem blankItem = new ComboItem();
        blankItem.setValue("");
        blankItem.setCaption(new LocaleString());
        entryItems.add(blankItem);
        if (entitys != null && entitys.size() > 0) {
            for (Map.Entry entry : entitys.entrySet()) {
                String mapKey = (String) entry.getKey();
                String mapValue = (String) entry.getValue();
                ComboItem entryItem = new ComboItem();
                entryItem.setValue(mapValue);
                entryItem.setCaption(new LocaleString(mapKey));
                entryItems.add(entryItem);
            }
        }
        return entryItems;
    }

    @Override
    public void registerListener(EventObject e) {
        BasedataEdit yem_debcredtype = this.getControl("yem_debcredtype");
        yem_debcredtype.addBeforeF7SelectListener(this);

    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String name = e.getProperty().getName();
        int row = e.getRow();
        DynamicObject DataEntity = this.getModel().getDataEntity(true);
        if ("yem_debcredtype".equals(name)) {
            f7debcredtype(e);
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        ChangeData[] changeData = e.getChangeSet();
        Object newValue = changeData[0].getNewValue();
        int row = changeData[0].getRowIndex();
        String key = e.getProperty().getName();
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        DynamicObject DataEntity = this.getModel().getDataEntity(true);
        if ("yem_debcredtype".equals(key)) {
            String yem_debcred = (String) model.getValue("yem_debcred", row);
            if (yem_debcred == null) {
                model.setValue("yem_debcredtype", null, row);
                this.getView().showErrorNotification("请先选择【借/贷类型】！");
                return;
            }
            //组织
            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_debcredtype = (DynamicObject) newValue;
            if (org != null && yem_customer != null && yem_groupcustomers != null && yem_debcredtype != null && yem_debcred != null) {
                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_debcredtype.getLong("id")));
                qFilter.and(new QFilter("yem_spcapitalpool_a.yem_debcredtype", QCP.equals, yem_debcred));
                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");
                Map<Long, BigDecimal> map = new HashMap<>();
                Map<Long, BigDecimal> map1 = new HashMap<>();
                if (data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        DynamicObject dynamicObject = data.get(i);
                        long yem_curr = dynamicObject.getLong("yem_spcapitalpool_a.yem_curr");
                        BigDecimal yem_noamo = dynamicObject.getBigDecimal("yem_spcapitalpool_a.yem_actremaamount");//实际剩余金额
                        BigDecimal yem_estamount = dynamicObject.getBigDecimal("yem_spcapitalpool_a.yem_estamount");//预计剩余金额
                        if (map.containsKey(yem_curr)) {
                            BigDecimal bigDecimal = map.get(yem_curr);
                            map.put(yem_curr, bigDecimal.add(yem_noamo));
                            BigDecimal bigDecimal1 = map1.get(yem_curr);
                            map1.put(yem_curr, bigDecimal1.add(yem_estamount));
                        } else {
                            map.put(yem_curr, yem_noamo);
                            map1.put(yem_curr, yem_estamount);
                        }
                    }
                }
                if (map.size() > 0) {
                    model.setValue("yem_creditrmbamt", null, row);
                    model.setValue("yem_creditusdamt", null, row);
                    for (Long mapkey : map.keySet()) {
                        BigDecimal bigDecimal = map.get(mapkey);
                        DynamicObject yem_em_replace = BusinessDataServiceHelper.loadSingle(mapkey, "bd_currency");
                        if (yem_em_replace != null) {
                            String number = yem_em_replace.getString("number");
                            if (number.equals("CNY")) {
                                model.setValue("yem_creditrmbamt", bigDecimal, row);
                            }
                            if (number.equals("USD")) {
                                model.setValue("yem_creditusdamt", bigDecimal, row);
                            }
                        }
                    }
                }
                if (map1.size() > 0) {
                    model.setValue("yem_yzycreditrmbamt", null, row);
                    model.setValue("yem_yzycreditusdamt", null, row);
                    for (Long mapkey : map1.keySet()) {
                        BigDecimal bigDecimal = map1.get(mapkey);
                        DynamicObject yem_em_replace = BusinessDataServiceHelper.loadSingle(mapkey, "bd_currency");
                        if (yem_em_replace != null) {
                            String number = yem_em_replace.getString("number");
                            if (number.equals("CNY")) {
                                model.setValue("yem_yzycreditrmbamt", bigDecimal, row);
                            }
                            if (number.equals("USD")) {
                                model.setValue("yem_yzycreditusdamt", bigDecimal, row);
                            }
                        }
                    }
                }
                QFilter qFilter1 = new QFilter("billstatus", QCP.equals, "C");
                qFilter1.and(new QFilter("yem_credittype.id", QCP.equals, yem_debcredtype.getLong("id")));
                qFilter1.and(new QFilter("yem_customer.id", QCP.equals, yem_groupcustomers.getLong("id")));
                qFilter1.and(new QFilter("yem_debcredtype", QCP.equals, yem_debcred));
                String selectfielddebcrednote = DynamicObjectUtil.getSelectfields("yem_debcrednote", false);
                DynamicObjectCollection debcrednote = QueryServiceHelper.query("yem_debcrednote",
                        selectfielddebcrednote, new QFilter[]{qFilter1}, "billno desc");
                if (debcrednote.size() > 0) {
                    model.setValue("yem_creditno", debcrednote.get(0).getString("billno"), row);
                }
            } else {
                model.setValue("yem_creditrmbamt", null, row);
                model.setValue("yem_creditusdamt", null, row);
                model.setValue("yem_creditno", null, row);
            }
        }
        if ("yem_debcred".equals(key)) {
            model.setValue("yem_creditrmbamt", null, row);
            model.setValue("yem_creditusdamt", null, row);
            model.setValue("yem_creditno", null, row);
            model.setValue("yem_debcredtype", null, row);
        }

    }

    /**
     * 过滤贷记单类型
     */
    public void f7debcredtype(BeforeF7SelectEvent e) {
        List list = new ArrayList<>();
        List notlist = new ArrayList<>();
        List zzlist = new ArrayList<>();
        DynamicObject DataEntity = this.getModel().getDataEntity(true);
        DynamicObject yem_customer = DataEntity.getDynamicObject("yem_customer");
        if (yem_customer == null) {
            this.getView().showErrorNotification("未选择客户禁止选择贷记单类型！");
            e.setCancel(true);
        }
        String yem_billtype = DataEntity.getString("yem_billtype.number");//单据类型
        String yem_fundusetype = DataEntity.getString("yem_fundusetype");//资金使用类型
        String yem_accamtusetype = DataEntity.getString("yem_accamtusetype");//配件资金使用方式
        String yem_billbusstype = DataEntity.getString("yem_billbusstype.number");//单据业务类型
        //客户配件资金池
        if ("B".equals(yem_fundusetype)) {
            QFilter qFilter = new QFilter("yem_contracttype", QCP.equals, yem_billtype);//
            qFilter.and(new QFilter("yem_accamtusetype", QCP.equals, yem_accamtusetype));
            qFilter.and(new QFilter("yem_billbusstype.number", QCP.equals, yem_billbusstype));
            String selectfield = DynamicObjectUtil.getSelectfields("yem_bd_credittypeconfig", false);
            String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, "yem_bd_credittypeconfig", "yem_credittypeentry", false);
            DynamicObjectCollection data = QueryServiceHelper.query("yem_bd_credittypeconfig",
                    selectfields, new QFilter[]{qFilter}, null);
            if (data.size() > 0) {
                boolean yem_mixture = data.get(0).getBoolean("yem_mixture");
                DynamicObjectCollection yem_accfunddetail = DataEntity.getDynamicObjectCollection("yem_accfunddetail");
                for (int i = 0; i < yem_accfunddetail.size(); i++) {
                    DynamicObject accfunddetail = yem_accfunddetail.get(i);
                    DynamicObject debcredtype = accfunddetail.getDynamicObject("yem_debcredtype");
                    if (debcredtype != null) {
                        notlist.add(debcredtype.getLong("id"));
                        if (!yem_mixture) {
                            String nummber = debcredtype.getString("number");
                            //服务维修
                            if (nummber.equals("JDJLX-0003")) {
                                notlist.add(seelctDyn("yem_bd_debcredtype", "number", "JDJLX-0002").getLong("id"));
                                notlist.add(seelctDyn("yem_bd_debcredtype", "number", "JDJLX-0007").getLong("id"));
                            }
                            //整机赠送 整机海运费
                            if (nummber.equals("JDJLX-0002") || nummber.equals("JDJLX-0007")) {
                                notlist.add(seelctDyn("yem_bd_debcredtype", "number", "JDJLX-0003").getLong("id"));
                            }
                        }
                    }
                }
                for (int i = 0; i < data.size(); i++) {
                    DynamicObject dynamicObject = data.get(i);
                    long number = dynamicObject.getLong("yem_credittypeentry.yem_credittype");
                    list.add(number);
                }
                QFilter qFilters = new QFilter("id", QCP.in, list);
                if (notlist.size() > 0) {
                    qFilters.and(new QFilter("id", QCP.not_in, notlist));
                }
                //查询配件资金池余额的贷记单 yem_bd_debcredtype
                List debcredtypelist = new ArrayList<>();
                DynamicObjectCollection yem_debcredtype = QueryServiceHelper.query("yem_bd_debcredtype",
                        "id", new QFilter[]{qFilters}, null);
                if (yem_debcredtype.size() > 0) {
                    for (int i = 0; i < yem_debcredtype.size(); i++) {
                        DynamicObject dynamicObject = yem_debcredtype.get(i);
                        debcredtypelist.add(dynamicObject.getLong("id"));
                    }
                }
                if (debcredtypelist.size() > 0) {
                    int rowIndex = this.getModel().getEntryCurrentRowIndex("yem_accfunddetail");
                    String yem_debcred = (String) this.getView().getModel().getValue("yem_debcred", rowIndex);
                    //组织
                    DynamicObject org = DataEntity.getDynamicObject("org");
                    //客户
                    DynamicObject yem_groupcustomers = null;
                    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";
                        }
                    }
                    QFilter qFilter2 = new QFilter("billstatus", QCP.equals, "C");//
                    qFilter2.and(new QFilter("org.id", QCP.equals, org.getLong("id")));
                    qFilter2.and(new QFilter("yem_customer.id", QCP.equals, yem_groupcustomers.getLong("id")));
                    qFilter2.and(new QFilter("yem_bd_products.number", QCP.equals, products));
                    qFilter2.and(new QFilter("yem_spcapitalpool_a.yem_creditype.id", QCP.in, debcredtypelist));
                    qFilter2.and(new QFilter("yem_spcapitalpool_a.yem_debcredtype", QCP.equals, yem_debcred));
                    String selectfield1 = DynamicObjectUtil.getSelectfields("yem_spcapitalpool", false);
                    String selectfields1 = DynamicObjectUtil.getEntrySelectfields(selectfield1, "yem_spcapitalpool", "yem_spcapitalpool_a", false);
                    DynamicObjectCollection data1 = QueryServiceHelper.query("yem_spcapitalpool", selectfields1, new QFilter[]{qFilter2}, "billno");
                    Map<String, BigDecimal> map = new HashMap<>();
                    for (DynamicObject dynamicObject : data1) {
                        long yem_curr = dynamicObject.getLong("yem_spcapitalpool_a.yem_curr");
                        long yem_creditype = dynamicObject.getLong("yem_spcapitalpool_a.yem_creditype");
                        String key = yem_curr + "_" + yem_creditype;
                        BigDecimal yem_noamo = dynamicObject.getBigDecimal("yem_spcapitalpool_a.yem_actremaamount");//实际剩余金额
//                        BigDecimal yem_estamount = dynamicObject.getBigDecimal("yem_spcapitalpool_a.yem_estamount");//预计剩余金额
                        if (map.containsKey(key)) {
                            BigDecimal bigDecimal = map.get(yem_curr);
                            map.put(key, bigDecimal.add(yem_noamo));
                        } else {
                            map.put(key, yem_noamo);
                        }
                    }
                    if (map.size() > 0) {
                        for (String mapkey : map.keySet()) {
                            String[] s = mapkey.split("_");
                            String s1 = s[1];
                            BigDecimal bigDecimal = map.get(mapkey);
                            if (bigDecimal.compareTo(BigDecimal.ZERO)==1) {
                                zzlist.add(Long.valueOf(s1));
                            }
                        }
                    }
                }
            }
        }
        QFilter qFilterzz = new QFilter("id", QCP.in, zzlist);//
        e.addCustomQFilter(qFilterzz);
    }

    /**
     * 根据条件查询是否包含
     *
     * @param entryname 单据表示
     * @param filename  查询条件字段
     * @param value     查询条件值
     * @return 返沪动态对象
     */
    public static DynamicObject seelctDyn(String entryname, String filename, Object value) {
        QFilter qFilter = new QFilter(filename, QCP.equals, value);
        DynamicObject Object = BusinessDataServiceHelper.loadSingle(entryname, "id,number,name", qFilter.toArray());
        return Object;
    }

}
