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

import com.alibaba.csp.sentinel.util.StringUtil;
import com.yem.wm.utils.GiftAmount;
import com.yem.wm.utils.YEM;
import kd.bos.coderule.api.CodeRuleInfo;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

import static com.yem.wm.es.salesorder.utils.SalesOrderUtils.setCustomBillno;

/**
 * @author xwudd
 * @date 11:37
 * @Description
 **/
public class SalesOrderAuditOp extends AbstractOperationServicePlugIn {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_customer");
        fieldKeys.add("id");
        fieldKeys.add("org");
        fieldKeys.add("yem_bd_products");
        fieldKeys.add("billno");
        fieldKeys.add("yem_bizdate");
        fieldKeys.add("yem_giftcurrency");
        fieldKeys.add("yem_giftdecimal");
        fieldKeys.add("yem_operator");
        fieldKeys.add("yem_department");
        fieldKeys.add("yem_giftamountsum");
        fieldKeys.add("yem_giftamountsumbase");
        fieldKeys.add("yem_es_salesorder_l");
        fieldKeys.add("yem_isnewagent");
        fieldKeys.add("yem_offeramount");
        fieldKeys.add("yem_managersign");
        fieldKeys.add("billstatus");
        fieldKeys.add("yem_signdate");
    }

    @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());
            frameworkContract(dataEntitie);
            giftAmount(dataEntitie);
            giftSpecialAmount(dataEntitie);
        }

    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e)
    {
        super.afterExecuteOperationTransaction(e);
        DynamicObject[] entities = e.getDataEntities();
        for (DynamicObject entity : entities) {
            DynamicObject load = BusinessDataServiceHelper.loadSingle(entity.getPkValue(), entity.getDynamicObjectType().getName());
            String billstatus = load.getString("billstatus");
            if ("C".equals(billstatus)) {
                // 衣晓明
                DynamicObject user = BusinessDataServiceHelper.loadSingle("bos_user", new QFilter[]{new QFilter("number", QCP.equals, "10437")});
                if (user != null) {
                    String signature = user.getString("yem_signature");
                    load.set("yem_managersign", signature);
                }
                SaveServiceHelper.save(new DynamicObject[]{load});
            }
        }
    }

    /**
     * @description 反写框架合同外销合同明细分录
     * @author xwudd
     * * @param[1] dataEntitie
     * return
     * @time 2023/7/25 15:05
     */

    public void frameworkContract(DynamicObject dataEntitie){
        DynamicObject agreementEw = dataEntitie.getDynamicObject("yem_agreementew");
        if(agreementEw != null){
            agreementEw = BusinessDataServiceHelper.loadSingle(agreementEw.getPkValue(),agreementEw.getDynamicObjectType().getName());
            DynamicObject exrateTable = dataEntitie.getDynamicObject("yem_exratetable");//外销合同汇率表
            DynamicObject sourceCurrency = dataEntitie.getDynamicObject("yem_currency");//外销合同结算币别
            DynamicObject targetCrrency = agreementEw.getDynamicObject("yem_currency");//框架合同结算币别
            DynamicObject saleCurrencyBase = dataEntitie.getDynamicObject("yem_currencybase");//外销合同本位币
            Date exrateDate = dataEntitie.getDate("yem_exratedate");//外销合同汇率日期
            BigDecimal exchangeRate = YEM.getExchangeRate(exrateTable, sourceCurrency, targetCrrency, exrateDate);
            BigDecimal fraExrateRate = agreementEw.getBigDecimal("yem_exrate");//框架合同汇率
            BigDecimal saleBillExrate = dataEntitie.getBigDecimal("yem_exrate");//外销合同汇率
            Date yemSigndate = dataEntitie.getDate("yem_signdate");
            DynamicObjectCollection entryEntitys = agreementEw.getDynamicObjectCollection("yem_entryentitys");
            DynamicObject addNew = entryEntitys.addNew();
            setCustomBillno(dataEntitie, null);
            addNew.set("yem_salecontract",dataEntitie);
            BigDecimal billAmt = dataEntitie.getBigDecimal("yem_offeramount");
            BigDecimal fraAmt = billAmt.multiply(exchangeRate);
            addNew.set("yem_fraamt",fraAmt);
            addNew.set("yem_fraamtbase",fraAmt.multiply(fraExrateRate));
            addNew.set("yem_contractamount",billAmt);
            addNew.set("yem_contractamountbase",billAmt.multiply(saleBillExrate));
            addNew.set("yem_salecurrency",sourceCurrency);
            addNew.set("yem_salecurrencybase",saleCurrencyBase);
            addNew.set("yem_salerate",saleBillExrate);
            addNew.set("yem_datesigning",yemSigndate);
            SaveServiceHelper.save(new DynamicObject[]{agreementEw});
        }
    }

    /**
     * @description 审核生成客户资金池- 普通规则
     * @author power
     * @time 2023/9/27
     */
    public void giftAmount(DynamicObject dataEntitie) {
        String id = String.valueOf(dataEntitie.getLong("id"));
        DynamicObject saleorderCustomer = dataEntitie.getDynamicObject("yem_customer");
        Long customer = null;//
        if (saleorderCustomer != null) {
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(saleorderCustomer.getPkValue(), saleorderCustomer.getDynamicObjectType().getName());
            if (dynamicObject != null) {
                DynamicObject groupcusfields = dynamicObject.getDynamicObject("yem_groupcustomers");
                if (groupcusfields  != null) {
                    customer = groupcusfields.getLong("id");
                }
            }
        }
//        Long customer = dataEntitie.getLong("yem_customer.id");
        Long org = dataEntitie.getLong("org.id");
        Long products = dataEntitie.getLong("yem_bd_products.id");
        String billno = dataEntitie.getString("billno");
        Date bizdate = dataEntitie.getDate("yem_bizdate");
        Long currency = dataEntitie.getLong("yem_giftcurrency.id");
        BigDecimal exrate = dataEntitie.getBigDecimal("yem_giftdecimal");
        Long operator = dataEntitie.getLong("yem_operator.id");
        Long department = dataEntitie.getLong("yem_department.id");
        BigDecimal giftamt =dataEntitie.getBigDecimal("yem_giftamountsum");
        BigDecimal giftamtbase =dataEntitie.getBigDecimal("yem_giftamountsumbase");
        DynamicObjectCollection giveamounts = dataEntitie.getDynamicObjectCollection("yem_es_salesorder_l");
        DynamicObject giftamountss = BusinessDataServiceHelper.loadSingle("yem_im_giftamount",
                new QFilter[]{new QFilter("yem_groupcusfields", QCP.equals,customer),
                      new QFilter("org", QCP.equals,org),
                                new QFilter("yem_bd_products", QCP.equals,products)});

        if (giveamounts!=null){

            if (giftamountss==null){
                DynamicObject datas = BusinessDataServiceHelper.newDynamicObject("yem_im_giftamount");
                QFilter qFilter = new QFilter("number",QCP.equals,"yem_im_giftamount_BT");
                DynamicObject billType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id", qFilter.toArray());
                datas.set("yem_billtype",billType);
                // 调用自动编码规则
                CodeRuleInfo codeRule = CodeRuleServiceHelper.getCodeRule(datas.getDataEntityType().getName(), datas, null);
                // 获取单据编码
                String number = CodeRuleServiceHelper.getNumber(codeRule, datas);
                datas.set("billno",number);
                datas.set("billstatus","C");
                datas.set("org",org);
                datas.set("yem_bizdate",bizdate);
                datas.set("yem_customer",saleorderCustomer);
                datas.set("yem_department",department);
                datas.set("yem_currency",currency);
                datas.set("yem_currency",currency);
                datas.set("yem_bd_products",products);
                datas.set("yem_giftuse",giftamt);
                datas.set("yem_giftenable",giftamt);
                datas.set("yem_giftuseable",BigDecimal.ZERO);
                datas.set("creator",operator);
                datas.set("yem_groupcusfields", customer);

                DynamicObjectCollection entryentity = datas.getDynamicObjectCollection("yem_im_giftamount_o");
                DynamicObject newEntryEntity =  entryentity.addNew();
                newEntryEntity.set("yem_origintype", "A");
                newEntryEntity.set("yem_producttype", products);
                newEntryEntity.set("yem_originno", billno);
                newEntryEntity.set("yem_datetime", bizdate);
                newEntryEntity.set("yem_origincurr", currency);
                newEntryEntity.set("yem_originamt", giftamt);
                newEntryEntity.set("yem_amountbase", giftamtbase);
                newEntryEntity.set("yem_originexrate", exrate);
                newEntryEntity.set("yem_userman", operator);
                newEntryEntity.set("yem_departmentes", department);
                newEntryEntity.set("yem_im_giftapplyids", id);


                SaveServiceHelper.save(new DynamicObject[]{datas});
                GiftAmount.Calculate(customer,org,products);

            }
            if (giftamountss!=null){
                DynamicObjectCollection entryentity = giftamountss.getDynamicObjectCollection("yem_im_giftamount_o");
                DynamicObject newEntryEntity =  entryentity.addNew();
                newEntryEntity.set("yem_origintype", "A");
                newEntryEntity.set("yem_producttype", products);
                newEntryEntity.set("yem_originno", billno);
                newEntryEntity.set("yem_datetime", bizdate);
                newEntryEntity.set("yem_origincurr", currency);
                newEntryEntity.set("yem_originamt", giftamt);
                newEntryEntity.set("yem_amountbase", giftamtbase);
                newEntryEntity.set("yem_originexrate", exrate);
                newEntryEntity.set("yem_userman", operator);
                newEntryEntity.set("yem_departmentes", department);
                newEntryEntity.set("yem_im_giftapplyids", id);
                SaveServiceHelper.save(new DynamicObject[] {giftamountss});
                GiftAmount.Calculate(customer,org,products);
            }
        }


    }


    /**
     * @description 审核生成客户资金池- 特殊规则
     * @author power
     * @time 2023/9/27
     */
    public void giftSpecialAmount(DynamicObject dataEntitie) {
        Long id = dataEntitie.getLong("id");
//        Long customer = dataEntitie.getLong("yem_customer.id");
        DynamicObject saleorderCustomer = dataEntitie.getDynamicObject("yem_customer");
        Long customer = null;//
        if (saleorderCustomer != null) {
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(saleorderCustomer.getPkValue(), saleorderCustomer.getDynamicObjectType().getName());
            if (dynamicObject != null) {
                DynamicObject groupcusfields = dynamicObject.getDynamicObject("yem_groupcustomers");
                if (groupcusfields  != null) {
                    customer = groupcusfields.getLong("id");
                }
            }
        }

        Long org = dataEntitie.getLong("org.id");
        Long products = dataEntitie.getLong("yem_bd_products.id");
        Date bizdate = dataEntitie.getDate("yem_bizdate");
        Long currency = dataEntitie.getLong("yem_giftcurrency.id");
        BigDecimal exrate = dataEntitie.getBigDecimal("yem_giftdecimal");
        Long operator = dataEntitie.getLong("yem_operator.id");
        Long department = dataEntitie.getLong("yem_department.id");
        if (StringUtil.isNotEmpty(dataEntitie.getString("yem_isnewagent"))){
            String isnewagent = dataEntitie.getString("yem_isnewagent");
            if("A".equals(isnewagent)){
                DynamicObjectCollection materialinfos = dataEntitie.getDynamicObjectCollection("yem_es_materialinfo");

                DynamicObject giftruless = BusinessDataServiceHelper.loadSingle("yem_bd_giftrules",
                        new QFilter[]{
                                new QFilter("yem_classify", QCP.equals,products),
                                new QFilter("status", QCP.equals,"C"),
                                new QFilter("yem_ynnewdealer", QCP.equals,isnewagent)});

                DynamicObject[] qty = BusinessDataServiceHelper.load("yem_es_salesorder",
                        "yem_es_materialinfo.yem_productmodel,yem_es_materialinfo.yem_qty,billno",
                        new QFilter[]{new QFilter("yem_customer.id", QCP.equals,customer),
                                new QFilter("org.id", QCP.equals,org),
                                new QFilter("yem_bd_products.id", QCP.equals,products),
                                new QFilter("id", QCP.not_equals,id),
                                new QFilter("billstatus", QCP.equals,"C"),
                                new QFilter("yem_cancelstatus", QCP.equals,"A"),
                                new QFilter("yem_isnewagent", QCP.equals,isnewagent)
                        });
                Object[] pk = new Object[qty.length];
                int row = 0;
                for(DynamicObject dt:qty){
                    pk[row] = dt.getPkValue();
                    row++;
                }
                if (qty!=null&&qty.length>0){
                    DynamicObject[] load = BusinessDataServiceHelper.load(pk, qty[0].getDynamicObjectType());
                    for (DynamicObject loads:load) {
                        DynamicObjectCollection yem_es_materialinfo = loads.getDynamicObjectCollection("yem_es_materialinfo");
                        for (DynamicObject yem_es_materialinfos:yem_es_materialinfo) {
                            DynamicObject yem_productmodel = yem_es_materialinfos.getDynamicObject("yem_productmodel");

                        }
                    }
                }

                DynamicObject giftamountss = BusinessDataServiceHelper.loadSingle("yem_im_giftamount",
                        new QFilter[]{new QFilter("yem_groupcusfields", QCP.equals,customer),
                                new QFilter("org", QCP.equals,org),
                                new QFilter("yem_bd_products", QCP.equals,products)});





                if (giftruless!=null){
                    for (DynamicObject giftrules : giftruless.getDynamicObjectCollection("yem_bd_giftrules_b")) {
                        BigDecimal sumqty =BigDecimal.ZERO;
                        BigDecimal masqty =BigDecimal.ZERO;
                        String ruledescribed = giftrules.getString("yem_ruledescribed");
                        for (DynamicObject giftrule:giftrules.getDynamicObjectCollection("yem_bd_giftrules_c")) {
                            Long producttypea = giftrule.getLong("yem_producttypea.id");
                            if (qty!=null&&qty.length>0){
                                DynamicObject[] load = BusinessDataServiceHelper.load(pk, qty[0].getDynamicObjectType());
                                for (DynamicObject loads:load) {
                                    DynamicObjectCollection yem_es_materialinfo = loads.getDynamicObjectCollection("yem_es_materialinfo");
                                    for (DynamicObject yem_es_materialinfos:yem_es_materialinfo) {
                                        if (yem_es_materialinfos.getDynamicObject("yem_productmodel")!=null){
                                            Long maproduct = yem_es_materialinfos.getDynamicObject("yem_productmodel").getLong("yem_products.id");
                                            if (producttypea.equals(maproduct)){
                                                BigDecimal yem_qty = yem_es_materialinfos.getBigDecimal("yem_qty");
                                                sumqty=sumqty.add(yem_qty);
                                            }
                                        }
                                    }
                                }
                            }
                            for (DynamicObject materialinfo:materialinfos) {
                                if ("Z".equals(materialinfo.getString("yem_businesssort"))){
                                    if (materialinfo.getDynamicObject("yem_productmodel")!=null){
                                        Long product = materialinfo.getDynamicObject("yem_productmodel").getLong("yem_products.id");
                                        if (product.equals(producttypea)){
                                            BigDecimal yem_qtywx =materialinfo.getBigDecimal("yem_qty");
                                            masqty=masqty.add(yem_qtywx);
                                        }
                                    }
                                }
                            }
                        }
                        BigDecimal yem_qtyb = giftrules.getBigDecimal("yem_qtyb");
                        BigDecimal qtys =masqty.add(sumqty);
                        if (qtys.compareTo(yem_qtyb) == 1&& sumqty.compareTo(yem_qtyb)  < 1) {

                            BigDecimal giveamo = giftrules.getBigDecimal("yem_giveamob");
                            BigDecimal giveamobase = giveamo.multiply(exrate);

                            if (giftamountss==null){
                                DynamicObject datas = BusinessDataServiceHelper.newDynamicObject("yem_im_giftamount");
                                QFilter qFilter = new QFilter("number",QCP.equals,"yem_im_giftamount_BT");
                                DynamicObject billType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id", qFilter.toArray());
                                datas.set("yem_billtype",billType);
                                // 调用自动编码规则
                                CodeRuleInfo codeRule = CodeRuleServiceHelper.getCodeRule(datas.getDataEntityType().getName(), datas, null);
                                // 获取单据编码
                                String number = CodeRuleServiceHelper.getNumber(codeRule, datas);
                                datas.set("billno",number);
                                datas.set("billstatus","C");
                                datas.set("org",org);
                                datas.set("yem_bizdate",bizdate);


                                datas.set("yem_customer", saleorderCustomer);
                                datas.set("yem_groupcusfields", customer);

                                datas.set("yem_department",department);
                                datas.set("yem_currency",currency);
                                datas.set("yem_currency",currency);
                                datas.set("yem_bd_products",products);

                                datas.set("creator",operator);

                                DynamicObjectCollection entryentity = datas.getDynamicObjectCollection("yem_im_giftamount_o");
                                DynamicObject newEntryEntity =  entryentity.addNew();
                                newEntryEntity.set("yem_origintype", "D");
                                newEntryEntity.set("yem_producttype", products);
                                newEntryEntity.set("yem_ruledescribed", ruledescribed);
                                newEntryEntity.set("yem_origincurr", currency);
                                newEntryEntity.set("yem_originamt", giveamo);
                                newEntryEntity.set("yem_amountbase", giveamobase);
                                newEntryEntity.set("yem_originexrate", exrate);
                                newEntryEntity.set("yem_userman", operator);
                                newEntryEntity.set("yem_departmentes", department);
                                SaveServiceHelper.save(new DynamicObject[] {datas});
                                GiftAmount.Calculate(customer,org,products);

                            }
                            if (giftamountss!=null){
                                DynamicObjectCollection entryentity = giftamountss.getDynamicObjectCollection("yem_im_giftamount_o");

                                DynamicObject newEntryEntity =  entryentity.addNew();
                                newEntryEntity.set("yem_origintype", "D");
                                newEntryEntity.set("yem_producttype", products);
                                newEntryEntity.set("yem_ruledescribed", ruledescribed);
                                newEntryEntity.set("yem_origincurr", currency);
                                newEntryEntity.set("yem_originamt", giveamo);
                                newEntryEntity.set("yem_amountbase", giveamobase);
                                newEntryEntity.set("yem_originexrate", exrate);
                                newEntryEntity.set("yem_userman", operator);
                                newEntryEntity.set("yem_departmentes", department);
                            }
                        }
                    }
                }
                SaveServiceHelper.save(new DynamicObject[] {giftamountss});
                GiftAmount.Calculate(customer,org,products);
            }
        }
    }
}
