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

import com.yem.wm.es.Util.CreditBackFillUtils;
import com.yem.wm.es.Util.TotalUtil;
import com.yem.wm.utils.GiftAmount;
import com.yem.wm.utils.YEM;
import kd.bos.armor.core.util.StringUtil;
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.EndOperationTransactionArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;

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

/**
 * 单据操作
 */
public class StorageTransUnAuditOp extends AbstractOperationServicePlugIn implements Plugin {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_customer");
    }
    @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());
            backFillCsrCreditLine(dataEntitie);
            giftAmount(dataEntitie);
            giftSpecialAmount(dataEntitie);
        }
    }

    /**
     * @description 删除客户信保额度申请 与该储运托单相关数据
     * @author xwudd
     * @param[1] dataEntitie
     * return
     * @time 2023/9/1 16:59
     */

    public void backFillCsrCreditLine(DynamicObject dataEntitie){
        long id = dataEntitie.getLong("id");
        DynamicObject customer = dataEntitie.getDynamicObject("yem_customer");
        DynamicObject method = TotalUtil.getSettlementMethod(dataEntitie);
        DynamicObject company = dataEntitie.getDynamicObject("yem_company.yem_erporg");
        String swiftCode = TotalUtil.getSwiftCode(dataEntitie);
        DynamicObject csrCreditLine = TotalUtil.getCsrCreditLine(customer, method, company, swiftCode);
        if (YEM.isNotEmpty(csrCreditLine)) {
            List<DynamicObject> objs = new ArrayList<>();
            DynamicObjectCollection infos = csrCreditLine.getDynamicObjectCollection("yem_im_info");
            for (DynamicObject info : infos) {
                long storageTransId = info.getLong("yem_storagetransid");
                if(id == storageTransId){
                    objs.add(info);
                }
            }
            if(objs.size() > 0){
                infos.removeAll(objs);
                BigDecimal decimal = CreditBackFillUtils.calcRemainingAmount(csrCreditLine);
                csrCreditLine.set("yem_balance", decimal);
                SaveServiceHelper.save(new DynamicObject[]{csrCreditLine});
            }
        }
    }

    /**
     * @description 反审核删除礼品资金池 反写礼品资金池 普通规则
     * @author power
     * return
     * @time 2023/9/28
     */
    public void giftAmount(DynamicObject dataEntitie) {
//        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");

        DynamicObjectCollection giveamounts = dataEntitie.getDynamicObjectCollection("yem_es_salesorder_l");


        for (DynamicObject giveamount:giveamounts) {

            Long products = giveamount.getLong("yem_bd_products.id");
            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)});

            Long id = giveamount.getLong("id");
            String contractnumbers = giveamount.getString("yem_contractnumbers");
            if (giftamountss!=null){
                DynamicObjectCollection entryentitys = giftamountss.getDynamicObjectCollection("yem_im_giftamount_o");
                for (DynamicObject entryentity:entryentitys) {
                    String yem_originno = entryentity.getString("yem_originno");
                    if (contractnumbers.equals(yem_originno)){
                        DynamicObjectCollection enablegiftinfors = entryentity.getDynamicObjectCollection("yem_enablegiftinfor");
//                        int i=-1;
                        for (int j = 0; j <enablegiftinfors.size(); j++) {
//                            i=i+1;
                            if (id.equals(Long.valueOf(enablegiftinfors.get(j).getString("yem_im_giftapplyides")))){
                                enablegiftinfors.remove(j);
                            }
                        }
                    }
                }
            }
            SaveServiceHelper.save(new DynamicObject[] {giftamountss});
            GiftAmount.Calculate(customer,org,products);
        }
    }

    /**
     * @description 反审核删除礼品资金池 反写礼品资金池 特殊规则
     * @author power
     * return
     * @time 2023/10/10
     */
    public void giftSpecialAmount(DynamicObject dataEntitie) {
//        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");
        DynamicObjectCollection materialinfos =dataEntitie.getDynamicObjectCollection("yem_es_materialinfo");
        Long id = dataEntitie.getLong("id");

        DynamicObject[] storagetrans = BusinessDataServiceHelper.load("yem_es_storagetrans",
                "yem_es_materialinfo.yem_productmodel,yem_es_materialinfo.yem_qty,"+
                "yem_es_materialinfo.yem_contractnumbers_m",
                new QFilter[]{
                        new QFilter("billstatus", QCP.equals,"C"),
                        new QFilter("yem_customer", QCP.equals,customer),
                        new QFilter("id", QCP.not_equals,id),
                        new QFilter("org", QCP.equals,org),});

        Object[] pk = new Object[storagetrans.length];
        int rows = 0;
        for(DynamicObject dt:storagetrans){
            pk[rows] = dt.getPkValue();
            rows++;
        }

        for (DynamicObject materialinfo:materialinfos) {
            if ( materialinfo.getDynamicObject("yem_productmodel")!=null){
                String isgiftgive = materialinfo.getString("yem_isgiftgive");
                Long productmodels = materialinfo.getLong("yem_productmodel.yem_products.id");
                Long products = materialinfo.getLong("yem_products.id");
                BigDecimal masqty =materialinfo.getBigDecimal("yem_qty");

                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 (giftamountss!=null){
                    if (products.equals(giftamountss.getLong("yem_bd_products.id"))){
                        if ("A".equals(isgiftgive)){
                            if (StringUtil.isNotEmpty(materialinfo.getString("yem_contractnumbers_m"))){
                                String conBillno = materialinfo.getString("yem_contractnumbers_m");
                                DynamicObject data = BusinessDataServiceHelper.loadSingle("yem_es_salesorder","yem_isnewagent",
                                        new QFilter[]{new QFilter("billno", QCP.equals, conBillno),});
                                if (data!=null){
                                    String isnewagent = data.getString("yem_isnewagent");

                                    DynamicObject giftruless = BusinessDataServiceHelper.loadSingle("yem_bd_giftrules",
                                            new QFilter[]{
                                                    new QFilter("status", QCP.equals,"C"),
                                                    new QFilter("yem_classify",QCP.equals,products),
                                                    new QFilter("yem_ynnewdealer",QCP.equals,isnewagent)});
                                    //是经销商
                                    if ("A".equals(isnewagent)){
                                        if (giftruless!=null){
                                            for (DynamicObject giftrules : giftruless.getDynamicObjectCollection("yem_bd_giftrules_b")) {
                                                BigDecimal sumqty =BigDecimal.ZERO;
                                                for (DynamicObject giftrule:giftrules.getDynamicObjectCollection("yem_bd_giftrules_c")) {
                                                    Long producttypea = giftrule.getLong("yem_producttypea.id");
                                                    if (storagetrans!=null&&storagetrans.length>0){
                                                        DynamicObject[] load = BusinessDataServiceHelper.load(pk, storagetrans[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)){
                                                                        String conBillnofo = yem_es_materialinfos.getString("yem_contractnumbers_m");
                                                                        DynamicObject datafo = BusinessDataServiceHelper.loadSingle("yem_es_salesorder","yem_isnewagent",
                                                                                new QFilter[]{new QFilter("billno", QCP.equals, conBillnofo),});
                                                                        if (datafo!=null){
                                                                            String isnewagentfo = data.getString("yem_isnewagent");
                                                                            if ("A".equals(isnewagentfo)){

                                                                                BigDecimal yem_qty = yem_es_materialinfos.getBigDecimal("yem_qty");
                                                                                sumqty=sumqty.add(yem_qty);
                                                                            }
                                                                        }

                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }


                                                }
                                                BigDecimal yem_qtyb = giftrules.getBigDecimal("yem_qtyb");
                                                if (sumqty.compareTo(yem_qtyb) < 1) {
                                                    BigDecimal giveamo = giftrules.getBigDecimal("yem_giveamob");
                                                    if (giftamountss!=null){
                                                        DynamicObjectCollection entryentitys = giftamountss.getDynamicObjectCollection("yem_im_giftamount_o");
                                                        int row = 0;
                                                        for ( DynamicObject entryentity:entryentitys) {
                                                            if (giveamo.compareTo(entryentity.getBigDecimal("yem_originamt")) == 0 && "D".equals(entryentity.getString("yem_origintype"))) {


                                                                entryentity.set("yem_entrygiftenable",BigDecimal.ZERO);
                                                                entryentity.set("yem_sneycrgiftenable",BigDecimal.ZERO);
//                                                                entryentitys.set(row,entryentity);
                                                                entryentity.set("seq",row);
                                                                break;
                                                            }

                                                            row ++;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
//                    SaveServiceHelper.save(new DynamicObject[] {giftamountss});
//                    GiftAmount.Calculate(customer,org,products);
                    SaveServiceHelper.save(new DynamicObject[] {giftamountss});
                    GiftAmount.Calculate(customer,org,products);
                }
            }
        }

    }

}