package com.yem.wm.im.debcrednote.op;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.yem.wm.bc.companytitle.form.CompanyTitleEdit;
import com.yem.wm.im.debcrednote.validator.DebcrednoteValidator;
import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.YEM;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
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 java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author 张立攀
 * @version 1.0
 * @description  贷记单审核时，根据客户反写配件资金池
 * @date 2023-08-07 15:45
 */
public class DebCredAuditPlugin extends AbstractOperationServicePlugIn {
    private static final Log log = LogFactory.getLog(CompanyTitleEdit.class);
    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        DynamicObject[] dataEnties = e.getDataEntities();
        for(DynamicObject temp:dataEnties){
            String billtype = temp.getString("yem_billtype.number");
            if("yem_debcrednote_d".equals(billtype)){
                DynamicObject sourcecreditno = temp.getDynamicObject("yem_sourcecreditno");
                DynamicObjectCollection creditnotedes = temp.getDynamicObjectCollection("yem_creditnotedes");
                int into = creditnotedes.size();
                DynamicObject customer = temp.getDynamicObject("yem_customer");
                DynamicObject products = temp.getDynamicObject("yem_bd_products");
                if(customer != null && products != null){
                    List<QFilter> list = new ArrayList<>();
                    list.add(new QFilter("yem_customer.id", QCP.equals,customer.getLong("id")));
                    list.add(new QFilter("billstatus", QCP.equals,"C"));
                    list.add(new QFilter("yem_bd_products.id", QCP.equals,products.getPkValue()));
                    DynamicObject loadColl =  BusinessDataServiceHelper.loadSingle("yem_spcapitalpool","yem_spcapitalpool_o.yem_origintype",list.toArray(new QFilter[0]));
                    if(loadColl != null){
                        loadColl = BusinessDataServiceHelper.loadSingle(loadColl.getPkValue(), loadColl.getDynamicObjectType().getName());
                        findCutDoing(temp, into, loadColl,sourcecreditno);
                    }else {
                        DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject("yem_spcapitalpool");
                        dynamicObject.set("yem_customer",customer.getLong("id"));
                        unFindCutDoing(temp, into, dynamicObject);
                    }
                }

            }
        }
    }

    private static void findCutDoing(DynamicObject temp, int into, DynamicObject loadColl,DynamicObject sourcecreditno) {

        DynamicObjectCollection dynamicObjectCollection = temp.getDynamicObjectCollection("yem_creditnotesource");
        if(dynamicObjectCollection.size() > 0){
            //有来源、有去向
//            QFilter qFilter1 = new QFilter("number", QCP.equals, "yem_spcapitalpool_BT");
//            DynamicObject[] bos_billtype_s = BusinessDataServiceHelper.load("bos_billtype",
//                    "id,name,number", new QFilter[] { qFilter1 }, null);
            BigDecimal rate = YEM.getExchangeRate(1735643603226593280L,1735631923524405248L,1735631923524405248L,new Date());
            loadColl.set("yem_exrate",rate);
            DynamicObjectCollection spcapitalpool_a = loadColl.getDynamicObjectCollection("yem_spcapitalpool_o");
            DynamicObject addobject =  spcapitalpool_a.addNew();
            DynamicObject yem_credittype = temp.getDynamicObject("yem_credittype");
            DynamicObject yem_sourcecreditno = temp.getDynamicObject("yem_sourcecreditno");
            DynamicObject yem_currency = temp.getDynamicObject("yem_currency");
            BigDecimal yem_amount = temp.getBigDecimal("yem_amount");
            BigDecimal yem_amountbase = temp.getBigDecimal("yem_amountbase");
            if(rate.compareTo(BigDecimal.ZERO) !=0){
                addobject.set("yem_originexrate",rate);
            }
            if(yem_credittype != null){
                addobject.set("yem_origintype",yem_credittype);
            }
            addobject.set("yem_originno",temp.getString("billno"));
            addobject.set("yem_datetimefield", temp.getDate("yem_bizdate"));
            if(yem_currency != null){
                addobject.set("yem_origincurr",yem_currency);
            }
            if(yem_amount.compareTo(BigDecimal.ZERO) !=0 ){
                addobject.set("yem_originamt",yem_amount);
            }
            if(yem_amountbase.compareTo(BigDecimal.ZERO) !=0){
                addobject.set("yem_amountbase",yem_amountbase);
            }
            addobject.set("yem_sourcebillid_o", temp.getPkValue());

            addobject.set("yem_residueavaamt",yem_amount);
            addobject.set("yem_residueavaamtbase",yem_amountbase);

            //有去向单
            if(into >0){
                DynamicObjectCollection yem_spcapitalpool_o_t = addobject.getDynamicObjectCollection("yem_spcapitalpool_o_t");
                DynamicObject sonEntry = yem_spcapitalpool_o_t.addNew();
                BigDecimal yem_amount_sub = temp.getBigDecimal("yem_amount_sub");
                BigDecimal yem_amountbase_sub = temp.getBigDecimal("yem_amountbase_sub");
                if(yem_credittype != null){
                    sonEntry.set("yem_towardtype",yem_credittype);
                }
                sonEntry.set("yem_towardno",temp.getString("billno"));
                sonEntry.set("yem_towardbizdate", temp.getDate("yem_bizdate"));
                if(yem_amount_sub.compareTo(BigDecimal.ZERO) != 0){
                    sonEntry.set("yem_towardamt",yem_amount_sub);
                }
                if(yem_amountbase_sub.compareTo(BigDecimal.ZERO) != 0){
                    sonEntry.set("yem_towardamtbase",yem_amountbase_sub);
                }
                if(yem_sourcecreditno != null){
                    sonEntry.set("yem_yem_creditid",yem_sourcecreditno.getString("billno"));
                }
                if(rate.compareTo(BigDecimal.ZERO) !=0){
                    sonEntry.set("yem_towardexrate",rate);
                }

                BigDecimal yemTowardamtEnd = BigDecimal.ZERO;
                BigDecimal yemTowardamtbaseEnd = BigDecimal.ZERO;
                for(DynamicObject db:yem_spcapitalpool_o_t){
                    BigDecimal yemTowardamt = db.getBigDecimal("yem_towardamt");
                    BigDecimal yemTowardamtbase = db.getBigDecimal("yem_towardamtbase");
                    yemTowardamtEnd = yemTowardamtEnd.add(yemTowardamt);
                    yemTowardamtbaseEnd = yemTowardamtbaseEnd.add(yemTowardamtbase);
                }

                addobject.set("yem_chargeoffamt",yemTowardamtEnd);
                addobject.set("yem_chargeoffamtbase",yemTowardamtbaseEnd);
                addobject.set("yem_residueavaamt",yem_amount.subtract(yem_amount_sub));
                addobject.set("yem_residueavaamtbase",yem_amountbase.subtract(yem_amountbase_sub));
            }

        }else {
            //仅有去向
            DynamicObjectCollection spcapitalpool_a = loadColl.getDynamicObjectCollection("yem_spcapitalpool_o");
            String sourcecreditnoNumber = "";
            if(sourcecreditno != null){
                sourcecreditnoNumber = sourcecreditno.getString("billno");
            }
            DynamicObject addobject = null;
            BigDecimal originamt = BigDecimal.ZERO;
            BigDecimal amountbase = BigDecimal.ZERO;
            for(DynamicObject spcapitalpool:spcapitalpool_a){
                originamt = spcapitalpool.getBigDecimal("yem_originamt");
                amountbase = spcapitalpool.getBigDecimal("yem_amountbase");
                String originno = spcapitalpool.getString("yem_originno");
                if(YEM.isNotEmpty(sourcecreditnoNumber) && sourcecreditnoNumber.equals(originno)){
                    addobject =  spcapitalpool;
                    break;
                }
            }

            DynamicObject yem_credittype = temp.getDynamicObject("yem_credittype");
            DynamicObject yem_sourcecreditno = temp.getDynamicObject("yem_sourcecreditno");
            BigDecimal yem_exrate = temp.getBigDecimal("yem_exrate");

            //有去向单
            if(into >0){
                if(addobject != null){
                    DynamicObjectCollection yem_spcapitalpool_o_t = addobject.getDynamicObjectCollection("yem_spcapitalpool_o_t");
                    DynamicObject sonEntry = yem_spcapitalpool_o_t.addNew();
                    BigDecimal yem_amount_sub = temp.getBigDecimal("yem_amount_sub");
                    BigDecimal yem_amountbase_sub = temp.getBigDecimal("yem_amountbase_sub");
                    if(yem_credittype != null){
                        sonEntry.set("yem_towardtype",yem_credittype);
                    }
                    sonEntry.set("yem_towardno",temp.getString("billno"));
                    sonEntry.set("yem_towardbizdate", temp.getDate("yem_bizdate"));
                    if(yem_amount_sub.compareTo(BigDecimal.ZERO) != 0){
                        sonEntry.set("yem_towardamt",yem_amount_sub);
                    }
                    if(yem_amountbase_sub.compareTo(BigDecimal.ZERO) != 0){
                        sonEntry.set("yem_towardamtbase",yem_amountbase_sub);
                    }
                    if(yem_sourcecreditno != null){
                        sonEntry.set("yem_yem_creditid",yem_sourcecreditno.getString("billno"));
                    }
                    if(yem_exrate.compareTo(BigDecimal.ZERO) !=0){
                        sonEntry.set("yem_towardexrate",yem_exrate);
                    }
                    BigDecimal yemTowardamtEnd = BigDecimal.ZERO;
                    BigDecimal yemTowardamtbaseEnd = BigDecimal.ZERO;
                    for(DynamicObject db:yem_spcapitalpool_o_t){
                        BigDecimal yemTowardamt = db.getBigDecimal("yem_towardamt");
                        BigDecimal yemTowardamtbase = db.getBigDecimal("yem_towardamtbase");
                        yemTowardamtEnd = yemTowardamtEnd.add(yemTowardamt);
                        yemTowardamtbaseEnd = yemTowardamtbaseEnd.add(yemTowardamtbase);
                    }

                    addobject.set("yem_chargeoffamt",yemTowardamtEnd);
                    addobject.set("yem_chargeoffamtbase",yemTowardamtbaseEnd);


                    addobject.set("yem_residueavaamt",originamt.subtract(addobject.getBigDecimal("yem_chargeoffamt")));
                    addobject.set("yem_residueavaamtbase",amountbase.subtract(addobject.getBigDecimal("yem_chargeoffamtbase")));
                }

            }
        }

        FunctionalCommon.countTotalSpCapitalPool(loadColl);
        OperationResult operationResult1 = OperationServiceHelper.executeOperate("save", "yem_spcapitalpool", new DynamicObject[]{loadColl}, OperateOption.create());
        if(operationResult1.isSuccess()){
//            log.error("保存成功-"+operationResult1.getMessage());
        }else {
            log.error("保存失败-"+operationResult1.getMessage());
        }
    }

    private static void unFindCutDoing(DynamicObject temp, int into, DynamicObject loadColl) {
        DynamicObject yem_bd_products = temp.getDynamicObject("yem_bd_products");
        Long orgId = RequestContext.get().getOrgId();
        QFilter qFilter1 = new QFilter("number", QCP.equals, "yem_spcapitalpool_BT");
        DynamicObject[] bos_billtype_s = BusinessDataServiceHelper.load("bos_billtype",
                "id,name,number", new QFilter[] { qFilter1 }, null);
        if(bos_billtype_s != null && bos_billtype_s.length>0) {
            loadColl.set("yem_billtype",bos_billtype_s[0].get("id"));
        }
        Long UserId = RequestContext.get().getCurrUserId();
        loadColl.set("org",orgId);
        loadColl.set("yem_department",orgId);
        loadColl.set("billstatus","A");
        loadColl.set("yem_bizdate",new Date());
        loadColl.set("yem_operator",UserId);
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("bd_currency","id,number"
                ,new QFilter[]{new QFilter("number",QCP.equals,"CNY")});
        DynamicObject bd_exratetable =BusinessDataServiceHelper.loadSingle("bd_exratetable","id,number"
                ,new QFilter[]{new QFilter("name",QCP.equals,"标准汇率")});
        loadColl.set("yem_currency",dynamicObject.getLong("id"));
        loadColl.set("yem_currencybase",dynamicObject.getLong("id"));
        loadColl.set("yem_exratetable",bd_exratetable.getLong("id"));
        loadColl.set("yem_exratedate",new Date());
        loadColl.set("yem_quotation","0");
        loadColl.set("creator",UserId);

        if(yem_bd_products != null){
            loadColl.set("yem_bd_products",yem_bd_products);
        }
        BigDecimal rate = YEM.getExchangeRate(1735643603226593280L,1735631923524405248L,1735631923524405248L,new Date());
        loadColl.set("yem_exrate",rate);
        DynamicObjectCollection spcapitalpool_a = loadColl.getDynamicObjectCollection("yem_spcapitalpool_o");
        DynamicObject addobject =  spcapitalpool_a.addNew();
        DynamicObject yem_credittype = temp.getDynamicObject("yem_credittype");
        DynamicObject yem_sourcecreditno = temp.getDynamicObject("yem_sourcecreditno");
        DynamicObject yem_currency = temp.getDynamicObject("yem_currency");
        BigDecimal yem_amount = temp.getBigDecimal("yem_amount");
        BigDecimal yem_amountbase = temp.getBigDecimal("yem_amountbase");
        if(rate.compareTo(BigDecimal.ZERO) !=0){
            addobject.set("yem_originexrate",rate);
        }
        if(yem_credittype != null){
            addobject.set("yem_origintype",yem_credittype);
        }
        addobject.set("yem_originno",temp.getString("billno"));
        addobject.set("yem_datetimefield", temp.getDate("yem_bizdate"));
        if(yem_currency != null){
            addobject.set("yem_origincurr",yem_currency);
        }
        if(yem_amount.compareTo(BigDecimal.ZERO) !=0 ){
            addobject.set("yem_originamt",yem_amount);
        }
        if(yem_amountbase.compareTo(BigDecimal.ZERO) !=0){
            addobject.set("yem_amountbase",yem_amountbase);
        }
        addobject.set("yem_sourcebillid_o", temp.getPkValue());

        addobject.set("yem_residueavaamt",yem_amount);
        addobject.set("yem_residueavaamtbase",yem_amountbase);

        //有去向单
        if(into >0){
            DynamicObjectCollection yem_spcapitalpool_o_t = addobject.getDynamicObjectCollection("yem_spcapitalpool_o_t");
            DynamicObject sonEntry = yem_spcapitalpool_o_t.addNew();
            BigDecimal yem_amount_sub = temp.getBigDecimal("yem_amount_sub");
            BigDecimal yem_amountbase_sub = temp.getBigDecimal("yem_amountbase_sub");
            if(yem_credittype != null){
                sonEntry.set("yem_towardtype",yem_credittype);
            }
                sonEntry.set("yem_towardno",temp.getString("billno"));
            sonEntry.set("yem_towardbizdate", temp.getDate("yem_bizdate"));
            if(yem_amount_sub.compareTo(BigDecimal.ZERO) != 0){
                sonEntry.set("yem_towardamt",yem_amount_sub);
            }
            if(yem_amountbase_sub.compareTo(BigDecimal.ZERO) != 0){
                sonEntry.set("yem_towardamtbase",yem_amountbase_sub);
            }
            if(yem_sourcecreditno != null){
                sonEntry.set("yem_yem_creditid",yem_sourcecreditno.getString("billno"));
            }
            if(rate.compareTo(BigDecimal.ZERO) !=0){
                sonEntry.set("yem_towardexrate",rate);
            }

            BigDecimal yemTowardamtEnd = BigDecimal.ZERO;
            BigDecimal yemTowardamtbaseEnd = BigDecimal.ZERO;
            for(DynamicObject db:yem_spcapitalpool_o_t){
                BigDecimal yemTowardamt = db.getBigDecimal("yem_towardamt");
                BigDecimal yemTowardamtbase = db.getBigDecimal("yem_towardamtbase");
                yemTowardamtEnd = yemTowardamtEnd.add(yemTowardamt);
                yemTowardamtbaseEnd = yemTowardamtbaseEnd.add(yemTowardamtbase);
            }

            addobject.set("yem_chargeoffamt",yemTowardamtEnd);
            addobject.set("yem_chargeoffamtbase",yemTowardamtbaseEnd);
//            addobject.set("yem_chargeoffamt",yem_amount_sub);
//            addobject.set("yem_chargeoffamtbase",yem_amountbase_sub);
            addobject.set("yem_residueavaamt",yem_amount.subtract(yem_amount_sub));
            addobject.set("yem_residueavaamtbase",yem_amountbase.subtract(yem_amountbase_sub));
        }
        FunctionalCommon.countTotalSpCapitalPool(loadColl);
        OperationResult operationSave = OperationServiceHelper.executeOperate("save", "yem_spcapitalpool", new DynamicObject[]{loadColl}, OperateOption.create());
        if(operationSave.isSuccess()){
//            log.error("保存成功-"+operationSave.getMessage());
            OperationResult operationSubmit = OperationServiceHelper.executeOperate("submit", "yem_spcapitalpool",new Object[]{loadColl.getPkValue()}, OperateOption.create());
            if(operationSubmit.isSuccess()){
                loadColl.set("auditor",UserId);
                loadColl.set("auditdate",new Date());
//                log.error("提交成功-"+operationSubmit.getMessage());

                OperationResult operationAudit = OperationServiceHelper.executeOperate("audit", "yem_spcapitalpool", new Object[]{loadColl.getPkValue()}, OperateOption.create());
                if(operationAudit.isSuccess()){
//                    log.error("审核成功-"+operationAudit.getMessage());
                }else {
                    OperationResult operationUnSubmit = OperationServiceHelper.executeOperate("unsubmit", "yem_spcapitalpool", new Object[]{loadColl.getPkValue()}, OperateOption.create());
                    if(operationUnSubmit.isSuccess()){
//                        log.error("撤销成功");
                        OperationResult operationDelete = OperationServiceHelper.executeOperate("delete", "yem_spcapitalpool", new Object[]{loadColl.getPkValue()}, OperateOption.create());
                        if(operationDelete.isSuccess()){
//                            log.error("删除成功"+operationDelete.getMessage());
                        }else {
                            log.error("删除失败"+operationDelete.getMessage());
                            throw new KDBizException("反写配件资金池审核-删除失败");
                        }
                    }else {
                        log.error("撤销失败");
                    }
                    log.error("审核失败-"+operationAudit.getMessage());
                    throw new KDBizException("反写配件资金池审核失败");
                }
            }else {
                OperationResult operationDelete = OperationServiceHelper.executeOperate("delete", "yem_spcapitalpool", new Object[]{loadColl.getPkValue()}, OperateOption.create());
                if(operationDelete.isSuccess()){
//                    log.error("删除成功"+operationDelete.getMessage());
                }else {

                    log.error("删除失败"+operationDelete.getMessage());
                    throw new KDBizException("反写配件资金池提交-删除失败");
                }
                log.error("提交失败-"+operationSubmit.getMessage());
                throw new KDBizException("反写配件资金池提交失败");
            }
        }else {
            log.error("保存失败-"+operationSave.getMessage());
            throw new KDBizException("反写配件资金池保存失败");
        }

    }

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        e.getFieldKeys().add("yem_billtype");
        e.getFieldKeys().add("yem_billtype.number");
        e.getFieldKeys().add("yem_customer");
        e.getFieldKeys().add("yem_credittype");
        e.getFieldKeys().add("yem_creditnotesource");
        e.getFieldKeys().add("yem_creditnotedes");
        e.getFieldKeys().add("yem_sourcecreditno");
        e.getFieldKeys().add("yem_currency");
        e.getFieldKeys().add("yem_amount");
        e.getFieldKeys().add("yem_amountbase");
        e.getFieldKeys().add("yem_exrate");
        e.getFieldKeys().add("yem_bizdate");
        e.getFieldKeys().add("yem_amount_sub");
        e.getFieldKeys().add("yem_amountbase_sub");
        e.getFieldKeys().add("yem_towardexrate");
        e.getFieldKeys().add("yem_bd_products");
        e.getFieldKeys().add("yem_credittype");
    }
        @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        e.addValidator(new DebcrednoteValidator());
    }
}
