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

import com.yem.or.utils.OrderUtils;
import com.yem.tws.common1.BigDecimalUtils;
import com.yem.wm.im.debcrednotenew.utils.DebCredUtils;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.basedata.BaseDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.fi.gl.accountref.handler.SaveBalDataHandler;
import kd.fi.gl.balcal.carriedintoleaf.SaveBalanceHandler;
import kd.hr.hies.common.enu.Operate;

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

/**
 * @author zhouc
 * @date 2024/3/27 19:59
 * @className SaleOrdeAddGenerateOp
 * @description 生成贷记单
 */
public class SaleOrdeAddGenerateOp extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_es_materialinfo");
        fieldKeys.add("yem_intauditbusano");
        fieldKeys.add("yem_intauditbusaid");
    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntitie : dataEntities) {
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
            AddGenerate(dataEntitie);

            StringBuilder sb = new StringBuilder();
            DynamicObjectCollection collection = dataEntitie.getDynamicObjectCollection("yem_accfunddetail");
            for (DynamicObject dynamicObject : collection) {
                String debcrednoteno = dynamicObject.getString("yem_debcrednoteno");
                sb.append(debcrednoteno).append("&");
            }
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.lastIndexOf("&"));
            }
            dataEntitie.set("yem_debcrednotenostr", sb.toString());
            SaveServiceHelper.save(new DynamicObject[]{dataEntitie});
        }
    }

    /**
     * 生成贷记单
     *
     * @param dataEntitie
     */
    public void AddGenerate(DynamicObject dataEntitie) {
        Map<Long, Map<String, String>> map = new HashMap<>();
        DynamicObjectCollection yem_accfunddetail = dataEntitie.getDynamicObjectCollection("yem_accfunddetail");
        for (int i = 0; i < yem_accfunddetail.size(); i++) {
            DynamicObject accfunddetail = yem_accfunddetail.get(i);
            long yem_debcreditid = accfunddetail.getLong("yem_debcreditid");
            if (yem_debcreditid == 0) {
                DynamicObject debcrednote = BusinessDataServiceHelper.newDynamicObject("yem_debcrednote");
                debcrednote.set("billstatus", "A");
                debcrednote.set("yem_billtype", seelctDyn("bos_billtype", "number", "yem_debcrednote_d"));
                debcrednote.set("yem_customer", dataEntitie.getDynamicObject("yem_customer"));
                debcrednote.set("yem_bizdate", new Date());
                debcrednote.set("yem_operator", dataEntitie.getDynamicObject("yem_operator"));
                debcrednote.set("yem_debcredtype", accfunddetail.getString("yem_debcred"));
                debcrednote.set("yem_credittype", accfunddetail.getDynamicObject("yem_debcredtype"));
                debcrednote.set("org", dataEntitie.getDynamicObject("org"));
                debcrednote.set("yem_sourcecreditno", DebCredUtils.getsourcecreditno(dataEntitie, accfunddetail.getDynamicObject("yem_debcredtype"),accfunddetail.getString("yem_debcred")));
                debcrednote.set("yem_sourcebillno", dataEntitie.getString("billno"));
                debcrednote.set("yem_source", dataEntitie.getString("billno"));
                String products = "";
                DynamicObject yem_bd_products = dataEntitie.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";
                    }
                }
                debcrednote.set("yem_bd_products", seelctDyn("yem_bd_productsgroup", "number", products));
                debcrednote.set("yem_groupcusfields", dataEntitie.getDynamicObject("yem_customer").getDynamicObject("yem_groupcustomers"));
                DynamicObject yem_currency = accfunddetail.getDynamicObject("yem_debcrednotecurr");
                DynamicObject yem_currencybase = OrderUtils.seelctDyn("bd_currency", "number", "CNY");
                DynamicObject yem_exratetable = OrderUtils.seelctDyn("bd_exratetable", "number", "001");
                debcrednote.set("yem_currency", yem_currency);
                debcrednote.set("yem_currencybase", yem_currencybase);
                debcrednote.set("yem_exratetable", yem_exratetable);
                debcrednote.set("yem_exratedate", new Date());
                debcrednote.set("yem_quotation", "0");
                BigDecimal yem_userate = accfunddetail.getBigDecimal("yem_userate");
                if (yem_userate.compareTo(BigDecimal.ZERO) == 0) {
                    if (yem_currency != null && yem_currencybase != null && yem_exratetable != null) {
                        if (yem_currency.getLong("id") == yem_currencybase.getLong("id")) {
                            debcrednote.set("yem_exrate", BigDecimal.ONE);
                        } else {
                            yem_userate = BaseDataServiceHelper.getExchangeRate(yem_exratetable.getLong("id"), yem_currency.getLong("id"), yem_currencybase.getLong("id"), new Date());
                            debcrednote.set("yem_exrate", yem_userate);
                        }
                    }
                } else {
                    debcrednote.set("yem_exrate", yem_userate);
                }
                debcrednote.set("creator", YEM.getCurrentUserId());
                debcrednote.set("createtime", new Date());
                debcrednote.set("yem_generate", "B");
                debcrednote.set("validstatus", "A");
                debcrednote.set("yem_version", "1");
                debcrednote.set("changestatus", "A");
                debcrednote.set("yem_counstat", "A");
                debcrednote.set("yem_sourcebillid", dataEntitie.getLong("id"));
                DynamicObjectCollection yem_creditnotedes = debcrednote.getDynamicObjectCollection("yem_creditnotedes");
                DynamicObject creditnotedes = yem_creditnotedes.addNew();
                creditnotedes.set("yem_contractno_d", dataEntitie);
                creditnotedes.set("yem_creditnotecont_d", accfunddetail.getString("yem_remark"));
                creditnotedes.set("yem_amount_d", accfunddetail.getBigDecimal("yem_debcuseamt"));
                creditnotedes.set("yem_amountbase_d", BigDecimalUtils.multiply(accfunddetail.getBigDecimal("yem_debcuseamt"), yem_userate, 8));
               BigDecimal yem_amount_sub=BigDecimal.ZERO;
                BigDecimal yem_amountbase_sub=BigDecimal.ZERO;
                for (int j = 0; j < yem_creditnotedes.size(); j++) {
                    DynamicObject object = yem_creditnotedes.get(j);
                    BigDecimal yem_amount_d = object.getBigDecimal("yem_amount_d");
                    BigDecimal yem_amountbase_d = object.getBigDecimal("yem_amountbase_d");
                    yem_amount_sub=yem_amount_sub.add(yem_amount_d);
                    yem_amountbase_sub=yem_amountbase_sub.add(yem_amountbase_d);
                }
                debcrednote.set("yem_amount_sub",yem_amount_sub);
                debcrednote.set("yem_amountbase_sub",yem_amountbase_sub);
                OperationResult Operate = OperationServiceHelper.executeOperate("save", debcrednote.getDynamicObjectType().getName(), new DynamicObject[]{debcrednote}, OperateOption.create());
                if (Operate.isSuccess()) {
                    OperationResult submitResult = OperationServiceHelper.executeOperate("submit", "yem_debcrednote", new Object[]{debcrednote.getPkValue()}, OperateOption.create());
                    if (submitResult.isSuccess()) {
                        OperationResult auditResult = OperationServiceHelper.executeOperate("audit", "yem_debcrednote", new Object[]{debcrednote.getPkValue()}, OperateOption.create());
                        if (auditResult.isSuccess()) {
                            Map smap = new HashMap<>();
                            smap.put("billno", debcrednote.getString("billno"));
                            smap.put("id", debcrednote.getString("id"));
                            map.put(accfunddetail.getLong("id"), smap);
                            //切换正式需去掉
//                        OperationResult estimatedResult = OperationServiceHelper.executeOperate("zyestimated", "yem_debcrednote", new Object[]{debcrednote.getPkValue()}, OperateOption.create());
//                        if (estimatedResult.isSuccess()) {
//
//                        }
                        } else {
                            List<IOperateInfo> allErrorOrValidateInfo = auditResult.getAllErrorOrValidateInfo();
                            String message = auditResult.getMessage();
                            throw new KDBizException("贷记单审核失败，" + message + "，" + allErrorOrValidateInfo);
                        }
                    } else {
                        List<IOperateInfo> allErrorOrValidateInfo = submitResult.getAllErrorOrValidateInfo();
                        String message = submitResult.getMessage();
                        throw new KDBizException("贷记单提交失败，" + message + "，" + allErrorOrValidateInfo);
                    }
                } else {
                    List<IOperateInfo> allErrorOrValidateInfo = Operate.getAllErrorOrValidateInfo();
                    String message = Operate.getMessage();
                    throw new KDBizException("贷记单保存失败，" + message + "，" + allErrorOrValidateInfo);
                }
            }
        }
        if (map.size() > 0) {
            for (int j = 0; j < yem_accfunddetail.size(); j++) {
                DynamicObject dynamicObject = yem_accfunddetail.get(j);
                long id = dynamicObject.getLong("id");
                if (map.containsKey(id)) {
                    Map<String, String> stringStringMap = map.get(id);
                    dynamicObject.set("yem_debcrednoteno", stringStringMap.get("billno"));
                    dynamicObject.set("yem_debcreditid", stringStringMap.get("id"));
                }
            }
            SaveServiceHelper.update(dataEntitie);
        }
    }

    public DynamicObject getsourcecreditno(DynamicObject dataEntitie, DynamicObject yem_debcredtype) {
        DynamicObject object = null;
        //组织
        DynamicObject org = dataEntitie.getDynamicObject("org");
        //客户
        DynamicObject yem_groupcustomers = null;
        DynamicObject yem_customer = dataEntitie.getDynamicObject("yem_customer");
        if (yem_customer != null) {
            yem_groupcustomers = yem_customer.getDynamicObject("yem_groupcustomers");
        }
        //产品类型
        DynamicObject yem_bd_products = dataEntitie.getDynamicObject("yem_bd_products");
        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.id", QCP.equals, yem_bd_products.getLong("id")));
        qFilter.and(new QFilter("yem_credittype.id", QCP.equals, yem_debcredtype.getLong("id")));
        String selectfield = DynamicObjectUtil.getSelectfields("yem_debcrednote", false);
        String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, "yem_debcrednote", "yem_creditnotedes", false);
        DynamicObjectCollection data = QueryServiceHelper.query("yem_debcrednote", "id," + selectfields, new QFilter[]{qFilter}, "billno DESC");
        if (data.size() > 0) {
            object = BusinessDataServiceHelper.loadSingle(data.get(0).getString("id"), "yem_debcrednote");
        }
        return object;
    }

    /**
     * 根据条件查询是否包含
     *
     * @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;
    }
}
