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

import com.yem.wm.utils.DynamicObjectUtil;
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.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.BeginOperationTransactionArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.entity.validate.ValidateResultCollection;
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 kd.sdk.plugin.Plugin;

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

/**
 * 单据操作
 */
public class CreateCreditNoteBillOp extends AbstractOperationServicePlugIn implements Plugin {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_accfunddetail");
        fieldKeys.add("yem_userate");
        fieldKeys.add("yem_debcuseamt");
        fieldKeys.add("org");
        fieldKeys.add("yem_customer");
        fieldKeys.add("yem_bizdate");
        fieldKeys.add("yem_currencybase");
        fieldKeys.add("yem_operator");
        fieldKeys.add("yem_bd_products");
        fieldKeys.add("yem_quotation");
        fieldKeys.add("yem_exratetable");
        fieldKeys.add("yem_usedebcrednoteno");
        fieldKeys.add("yem_debcredtype");
        fieldKeys.add("yem_ordercurr");
        fieldKeys.add("yem_remark");
        fieldKeys.add("billno");
        fieldKeys.add("yem_debcreditid");
        fieldKeys.add("yem_debcrednotecurr");
        fieldKeys.add("yem_debcrednoteno");
    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        DynamicObject creditNoteBillType = getCreditNoteBillType();
        String debCredNoteFields = DynamicObjectUtil.getSelectfields("yem_debcrednote", false);
        debCredNoteFields = DynamicObjectUtil.getEntrySelectfields(debCredNoteFields,"yem_debcrednote","yem_creditnotedes",false);
        for (DynamicObject dataEntitie : dataEntities){
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(),dataEntitie.getDynamicObjectType().getName());
            DynamicObjectCollection accFundDetails = dataEntitie.getDynamicObjectCollection("yem_accfunddetail");
            for (DynamicObject accFundDetail : accFundDetails){
                BigDecimal useRate = BigDecimal.ZERO;
                BigDecimal debCUseAmt = accFundDetail.getBigDecimal("yem_debcuseamt");
//                DynamicObject debCredNote = BusinessDataServiceHelper.loadSingle("yem_debcrednote", debCredNoteFields,
//                        new QFilter[]{new QFilter("yem_accfunddetailid", QCP.equals, accFundDetail.getPkValue())});
//                if(YEM.isNotEmpty(debCredNote)){
//
//                }else{
                DynamicObject debCredNote = BusinessDataServiceHelper.newDynamicObject("yem_debcrednote");
//                }
                setBaseInfo(debCredNote);
                debCredNote.set("yem_billtype",creditNoteBillType);
                debCredNote.set("org",dataEntitie.get("org"));
                debCredNote.set("yem_customer",dataEntitie.get("yem_customer"));
                debCredNote.set("yem_bizdate",dataEntitie.get("yem_bizdate"));//业务日期
                debCredNote.set("yem_operator",dataEntitie.get("yem_operator"));//业务员
                debCredNote.set("yem_currencybase",dataEntitie.get("yem_currencybase"));//本位币
                debCredNote.set("yem_bd_products",dataEntitie.get("yem_bd_products"));//产品类型
                debCredNote.set("yem_quotation",dataEntitie.get("yem_quotation"));//换算方式
                debCredNote.set("yem_exratetable",dataEntitie.get("yem_exratetable"));//汇率表
                DynamicObject useDebCredNoteNo = (DynamicObject)accFundDetail.get("yem_usedebcrednoteno");
                debCredNote.set("yem_sourcecreditno",useDebCredNoteNo);
                debCredNote.set("yem_credittype",accFundDetail.get("yem_debcredtype"));//贷记类型
                DynamicObject debCredNoteCurr = accFundDetail.getDynamicObject("yem_debcrednotecurr");
                debCredNote.set("yem_currency",debCredNoteCurr);//结算币别
                if(YEM.isNotEmpty(useDebCredNoteNo)){
                    useDebCredNoteNo = BusinessDataServiceHelper.loadSingle(useDebCredNoteNo.getPkValue(),useDebCredNoteNo.getDynamicObjectType().getName());
                    useRate = useDebCredNoteNo.getBigDecimal("yem_exrate");
                    debCredNote.set("yem_exrate",useRate);//汇率
                }
                debCredNote.set("yem_debcredtype","B");//借贷类型
                debCredNote.set("yem_exratedate",new Date());//汇率日期
                debCredNote.set("yem_amount_sub",debCUseAmt);//配件资金池扣减金额
                debCredNote.set("yem_amountbase_sub",useRate.multiply(debCUseAmt));//配件资金池扣减金额本位币

                DynamicObjectCollection destinations = debCredNote.getDynamicObjectCollection("yem_creditnotedes");
                DynamicObject addNew = destinations.addNew();
                addNew.set("yem_contractno_d",dataEntitie);//合同号
                addNew.set("yem_amount_d",debCUseAmt);//金额
                addNew.set("yem_amountbase_d",useRate.multiply(debCUseAmt));//金额本位币
                addNew.set("yem_remarke_d",accFundDetail.get("yem_remark"));//备注

                debCredNote.set("yem_sourcebilltype",dataEntitie.getDynamicObjectType().getName());//源单类型
                debCredNote.set("yem_sourcebillid",dataEntitie.getPkValue());//来源单据ID
                debCredNote.set("yem_sourcebillno",dataEntitie.getString("billno"));//来源单据编码
                debCredNote.set("yem_corebilltype",dataEntitie.getDynamicObjectType().getName());//核心单类型
                debCredNote.set("yem_corebillno",dataEntitie.getString("billno"));//核心单据编码
                debCredNote.set("yem_corebillid",dataEntitie.getPkValue());//核心单据ID
                debCredNote.set("yem_accfunddetailid",accFundDetail.getPkValue());//配件资金使用分录行id
                if (accFundDetail.get("yem_debcredtype") != null && debCredNoteCurr != null && useDebCredNoteNo != null && useDebCredNoteNo.getBigDecimal("yem_exrate") != null) {
                    OperationResult saveResult = OperationServiceHelper.executeOperate("save", "yem_debcrednote", new DynamicObject[]{debCredNote}, OperateOption.create());
                    if(saveResult.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()){
                                accFundDetail.set("yem_debcrednoteno",debCredNote.getString("billno"));
                                SaveServiceHelper.update(dataEntitie);
                            }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 = saveResult.getAllErrorOrValidateInfo();
                        String message = saveResult.getMessage();
                        throw new KDBizException("所生成贷记单保存失败，" + message + "，" + allErrorOrValidateInfo);
                    }
                }
            }
        }
    }

    public DynamicObject getCreditNoteBillType(){
        return BusinessDataServiceHelper.loadSingle("bos_billtype","id",
                new QFilter[]{new QFilter("number", QCP.equals,"yem_debcrednote_d")});
    }

    public void setBaseInfo(DynamicObject targetObj){
        targetObj.set("billstatus","A");
        targetObj.set("changestatus","A");
        targetObj.set("creator", RequestContext.get().getCurrUserId());
        targetObj.set("createtime",new Date());

    }
}