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

import com.alibaba.csp.sentinel.util.StringUtil;
import com.yem.wm.es.salesorder.utils.SalesOrderUtils;
import com.yem.wm.es.salesorder.validator.SalesOrderUnAuditValidator;
import com.yem.wm.utils.GiftAmount;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
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.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

/**
 * @author xwudd
 * @date 14:44
 * @Description
 **/
public class SalesOrderUnAuditOp 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_managersign");
        fieldKeys.add("billstatus");
        fieldKeys.add("yem_currency");
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        e.addValidator(new SalesOrderUnAuditValidator());
    }

    @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());
            delFrameworkContract(dataEntitie);
            dleGiftAmount(dataEntitie);
            giftSpecialAmount(dataEntitie);
            clearManagerSign(dataEntitie);
            updatePartsmerchant(e);
//            deleteIntauditbusaid(e);
            updateSignStatus(dataEntitie);
        }
    }

    /**
     * 更新 合同签章同步状态
     * @param dataEntitie
     */
    private void updateSignStatus(DynamicObject dataEntitie) {
        dataEntitie.set("yem_sigstatus", false);
        SaveServiceHelper.update(dataEntitie);
    }

    /**
     * 删除暂存的内审预算单
     * @param e
     */
    private void deleteIntauditbusaid(EndOperationTransactionArgs e) {
        DynamicObject[] entities = e.getDataEntities();
        for (DynamicObject entity : entities) {
            DynamicObjectCollection collection = entity.getDynamicObjectCollection("yem_es_materialinfo");
            DynamicObject billtype = entity.getDynamicObject("yem_billtype");
            String number = billtype.getString("number");
            if (number.equals("yem_es_salesorder_ZJ") || number.equals("yem_es_salesorder_PJ")
                    || number.equals("yem_es_salesorder_nmzj") || number.equals("yem_es_salesorder_nmpj")) {
                for (DynamicObject dynamicObject : collection) {
                    String intAuditBuSaNo = dynamicObject.getString("yem_intauditbusano");
                    long intAuditBuSaId = dynamicObject.getLong("yem_intauditbusaid");
                    if (YEM.isNotEmpty(intAuditBuSaNo) && YEM.isNotEmpty(intAuditBuSaId)) {
                        DynamicObject single = BusinessDataServiceHelper.loadSingle(intAuditBuSaId, "yem_im_intauditbusa");
                        String billstatus = single.getString("billstatus");
                        if ("A".equals(billstatus)) {
                            OperationResult result = OperationServiceHelper.executeOperate("delete", "yem_im_intauditbusa", new DynamicObject[]{single}, YEM.getOption());
                            if (!result.isSuccess()) {
                                throw new KDBizException(String.format("删除内审预算单 [ %s ] 失败，原因： [ %s ]", intAuditBuSaNo, result.getMessage()));
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 更新配件客商额度申请单
     * @param e
     */
    private void updatePartsmerchant(EndOperationTransactionArgs e)
    {
        String operationKey = e.getOperationKey();
        if ("unaudit".equals(operationKey)) {
            DynamicObject[] entities = e.getDataEntities();
            for (DynamicObject entity : entities) {
                entity = BusinessDataServiceHelper.loadSingle(entity.getPkValue(), entity.getDynamicObjectType().getName());
                String fundusetype = entity.getString("yem_fundusetype");
                if (!"A".equals(fundusetype)) {
                    return;
                }
                // 公司
                long orgId = entity.getLong("org.id");
                // 客户ID
                long customerId = entity.getLong("yem_customer.id");
                // 产品分类
                long productsId = entity.getLong("yem_bd_products.id");
                // 结算币别
                long currency = entity.getLong("yem_currency.id");
                // 业务组织 = 公司
                QFilter qFilters = new QFilter("org.id", QCP.equals, orgId);
                // 客户名称 = 客户名称
                qFilters.and(new QFilter("yem_client.id", QCP.equals, customerId));
                // 产品分类 = 产品分类
                qFilters.and(new QFilter("yem_productcategorie", QCP.equals, productsId));
                // 单据状态 = 已审核
                qFilters.and(new QFilter("billstatus", QCP.equals, "C"));
                // 合同上结算币别 = 额度申请上 额度币别
                qFilters.and(new QFilter("yem_currency.id", QCP.equals, currency));
                // 日期降序
//            qFilters.and(new QFilter("yem_bizdate", QCP.equals));
                // 根据组织+客户+产品分类，查询 配件客商额度申请单
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("yem_im_partsmerchant", qFilters.toArray());
                if (dynamicObject != null) {
                    // 配件客商额度申请单 - 分录
                    DynamicObjectCollection collection = dynamicObject.getDynamicObjectCollection("yem_im_entryentity_m");
                    // 删除分录中对应的外销合同
                    Iterator<DynamicObject> iterator = collection.iterator();
                    while (iterator.hasNext()) {
                        DynamicObject item = iterator.next();
                        long yem_cn = item.getLong("yem_cn.id");
                        if (yem_cn != 0) {
                            if (yem_cn == entity.getLong("id")) {
                                iterator.remove();
                            }
                        }
                    }
                    dynamicObject.set("yem_im_entryentity_m", collection);
                    SaveServiceHelper.save(new DynamicObject[]{dynamicObject});
                    SalesOrderUtils.calcCreditAmount(dynamicObject.getLong("id"));
                }
            }
        }
    }

    /**
     * 反审核的时候，清空外销合同-经理签章；
     * @param dataEntitie
     */
    private void clearManagerSign(DynamicObject dataEntitie)
    {
        dataEntitie.set("yem_managersign", null);
        SaveServiceHelper.save(new DynamicObject[]{dataEntitie});
    }


    /**
     * @description 反审核删除框架合同的外销合同分录关联信息
     * @author xwudd
     * * @param[1] dataEntitie
     * return
     * @time 2023/7/25 15:06
     */
    public void delFrameworkContract(DynamicObject dataEntitie){
        DynamicObject agreementEw = dataEntitie.getDynamicObject("yem_agreementew");
        if(agreementEw != null){
            agreementEw = BusinessDataServiceHelper.loadSingle(agreementEw.getPkValue(),agreementEw.getDynamicObjectType().getName());
            DynamicObjectCollection entryEntitys = agreementEw.getDynamicObjectCollection("yem_entryentitys");
            for(DynamicObject entryEntity : entryEntitys){
                DynamicObject saleContract = entryEntity.getDynamicObject("yem_salecontract");
                if(saleContract != null){
                    if(saleContract.getLong("id") == dataEntitie.getLong("id")){
                        entryEntitys.remove(entryEntity);
                        break;
                    }
                }
            }
            SaveServiceHelper.save(new DynamicObject[]{agreementEw});
        }
    }

    /**
     * @description 反审核删除礼品资金池 礼品资金来源分录 普通规则
     * @author power
     * return
     * @time 2023/9/28
     */
    public void dleGiftAmount(DynamicObject dataEntitie){
        String id = String.valueOf(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");

        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){
            DynamicObjectCollection entryentity = giftamountss.getDynamicObjectCollection("yem_im_giftamount_o");
            for (int j = 0; j < entryentity.size(); j++) {
                String yem_im_giftapplyids = entryentity.get(j).getString("yem_im_giftapplyids");
                if (entryentity.get(j).getString("yem_im_giftapplyids").equals(id)){
                    entryentity.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 id = dataEntitie.getLong("id");
        String bill = dataEntitie.getString("billno");
//        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");
        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",
                        new QFilter[]{new QFilter("yem_customer", QCP.equals,customer),
                                new QFilter("org", QCP.equals,org),
                                new QFilter("yem_bd_products", 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++;
                }


                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;

                        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);
                                            }
                                        }
                                    }
                                }
                            }

                        }


                        BigDecimal giveamo = giftrules.getBigDecimal("yem_giveamob");
                        BigDecimal yem_qtyb = giftrules.getBigDecimal("yem_qtyb");
                        if (sumqty.compareTo(yem_qtyb) < 1) {
                            if (giftamountss!=null){
                                DynamicObjectCollection entryentity = giftamountss.getDynamicObjectCollection("yem_im_giftamount_o");
                                for (int j = 0; j < entryentity.size(); j++) {
                                    if (giveamo.compareTo(entryentity.get(j).getBigDecimal("yem_originamt")) == 0
                                            && "D".equals(entryentity.get(j).getString("yem_origintype"))) {
                                        entryentity.remove(j);
                                        break;
                                    }
                                }
                                SaveServiceHelper.save(new DynamicObject[] {giftamountss});
                                GiftAmount.Calculate(customer,org,products);
                            }
                        }
                    }
                }
            }
        }
    }
}
