package com.yem.wm.es.salesorder.op;/*
 *
 * @auther: xwudd
 * @Description
 * @Date: 2023/7/24
 */

import com.yem.wm.es.salesorder.utils.SalesOrderUtils;
import com.yem.wm.es.salesorder.validator.NewSalesOrderSubmitValidator;
import com.yem.wm.es.salesorder.validator.SalesOrderSubmitValidator;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
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.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

/**
 * @Description
 **/
public class SalesOrderSubmitOp extends AbstractOperationServicePlugIn {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_billtype");
        fieldKeys.add("yem_materialclass");
        fieldKeys.add("yem_fundusetype");
        fieldKeys.add("yem_fundpoolamt");
        fieldKeys.add("yem_accfunddetail");
        fieldKeys.add("yem_usedebcrednoteno");
        fieldKeys.add("yem_orderuseamt");
        fieldKeys.add("yem_onecarcom");
        fieldKeys.add("yem_es_materialinfo");
        fieldKeys.add("yem_intauditbusano");
        fieldKeys.add("yem_commissionamt");
        e.getFieldKeys().add("yem_materiel");
        fieldKeys.add("yem_issinosurecon");
        fieldKeys.add("yem_intauditbusaid");
        fieldKeys.add("yem_giftamountsum");
        fieldKeys.add("yem_isgiftgiveparts");
        fieldKeys.add("yem_issinosure");
        fieldKeys.add("yem_offeramount");
        fieldKeys.add("yem_rapamt");
        fieldKeys.add("yem_giftamountsum");
        fieldKeys.add("yem_newprice");
        fieldKeys.add("yem_newsalediffprice");
        fieldKeys.add("yem_safobprice");
        fieldKeys.add("yem_exrate");
        fieldKeys.add("org");
        fieldKeys.add("yem_customer");
        fieldKeys.add("yem_customer");
        fieldKeys.add("yem_bd_products");
        fieldKeys.add("yem_bd_products");
        fieldKeys.add("yem_debitamount");
        fieldKeys.add("yem_contremark");
        fieldKeys.add("yem_exrate");
        fieldKeys.add("yem_fundusetype");
        fieldKeys.add("yem_accfunddetail");
        fieldKeys.add("yem_debcredtype");
        fieldKeys.add("yem_usedebcrednoteno");
        fieldKeys.add("yem_disamt");
        fieldKeys.add("yem_color");
        fieldKeys.add("yem_marketraiseprice");
        fieldKeys.add("yem_currency");
        fieldKeys.add("yem_cnperson");
        fieldKeys.add("yem_suminsured");
        fieldKeys.add("yem_internationalrate");
        fieldKeys.add("yem_es_salescontrac_s");
        fieldKeys.add("yem_es_salescontrac_s.yem_issinosure");
        fieldKeys.add("yem_es_salescontrac_s.yem_rapstyle");
    }

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

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
//        for (DynamicObject dataEntitie : dataEntities) {
//            boolean isSinosureCon = dataEntitie.getBoolean("yem_issinosurecon");
//            if (isSinosureCon) {
//
//            }
//            setNewpPrice(dataEntitie);
//
//        }

        // 更新配件客商额度申请单据
        updatePartsmerchant(e);

        // 最新财务标准售价为空时，不允许提交
//        checkNewPrice(dataEntities);
    }

    /**
     * 更新配件客商额度申请单据
     *
     * @param e
     */
    public void updatePartsmerchant(EndOperationTransactionArgs e) {
        String operationKey = e.getOperationKey();
        DynamicObject[] entities = e.getDataEntities();
        for (DynamicObject entity : entities) {
            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");
            // 配件客商/借记额度
            BigDecimal debitamount = entity.getBigDecimal("yem_debitamount");
            // 预计发货时间
            Date acshipdate = entity.getDate("yem_acshipdate");
            // 业务组织 = 公司
            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));
            if ("submit".equals(operationKey)) {
                // 根据组织+客户+产品分类，查询 配件客商额度申请单
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("yem_im_partsmerchant", qFilters.toArray());

                if (dynamicObject == null) {
                    continue;
                }
                ;
                // 配件客商额度申请单 - 分录
                DynamicObjectCollection collection = dynamicObject.getDynamicObjectCollection("yem_im_entryentity_m");

                // 删除旧的数据，保证相同合同数据只有一条
                Iterator<DynamicObject> iterator = collection.iterator();
                while (iterator.hasNext()) {
                    DynamicObject next = iterator.next();
                    long constractId = next.getLong("yem_cn.id");
                    if (constractId == entity.getLong("id")) {
                        iterator.remove();
                    }
                }

                DynamicObject addNew = collection.addNew();
                // 合同号 - 基本信息-外销合同号
                addNew.set("yem_cn", entity.get("id"));
                // 合同币别 - 财务信息-结算币别
                addNew.set("yem_currencyfield", entity.get("yem_currency"));
                // 合同占用金额 - 基本信息-配件客商/借记额度
                addNew.set("yem_sum", debitamount);
                // 合同占用金额RMB - 配件客商/借记额度 * 财务信息-汇率
                addNew.set("yem_localsum", debitamount.multiply(entity.getBigDecimal("yem_exrate")));
                // 核销金额
                addNew.set("yem_writtenamt", null);
                // 核销金额RMB
                addNew.set("yem_locwrittenamt", null);
                // 发货时间 - 基本信息-预计发货时间
                addNew.set("yem_deliverytime", acshipdate);
                // 最晚还款时间 - 预计发货时间的下个月14号
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(acshipdate);
                calendar.add(Calendar.MONTH, 1);
                calendar.set(Calendar.DAY_OF_MONTH, 14);
                addNew.set("yem_optimaltime", calendar.getTime());
                // 实际还款时间
                addNew.set("yem_pennsylvania", null);
                // 备注
                addNew.set("yem_comment", entity.get("yem_contremark"));
                SaveServiceHelper.save(new DynamicObject[]{dynamicObject});
                SalesOrderUtils.calcCreditAmount(dynamicObject.getLong("id"));
            }
        }
    }
}
