package com.yem.wm.es.specialapplica.form;

import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.IFormView;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.FormOperate;

import java.util.HashSet;
import java.util.Set;

/**
 * 发货特殊申请表单插件
 */
public class SpecialApplicaEdit extends AbstractBillPlugIn {
    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);

        FormOperate source = (FormOperate) e.getSource();
        String operateKey = source.getOperateKey();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        if ("save".equals(operateKey)) {
            Set<String> salesOrderSet = new HashSet<>();
            Set<String> shippingDetailSet = new HashSet<>();

            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_tradeapp");
            for (DynamicObject dynamicObject : collection) {
                salesOrderSet.add(dynamicObject.getString("yem_contractno"));
                shippingDetailSet.add(dynamicObject.getString("yem_shippingnumber"));
            }
            StringBuilder salesOrder = new StringBuilder();
            StringBuilder shippingDetail = new StringBuilder();

            for (String no : salesOrderSet) {
                salesOrder.append(no).append("\r\n");
            }
            for (String no : shippingDetailSet) {
                shippingDetail.append(no).append("\r\n");
            }

            dataEntity.set("yem_saleorderno", salesOrder.toString());
            dataEntity.set("yem_shippingdetailsno", shippingDetail.toString());

            StringBuilder title = new StringBuilder();
            DynamicObject client = dataEntity.getDynamicObject("yem_client");
            if (YEM.isNotEmpty(client)) {
                title.append(client.getString("name")).append(" ");
            }

            DynamicObject products = dataEntity.getDynamicObject("yem_bd_products");
            if (YEM.isNotEmpty(products)) {
                title.append(products.getString("name")).append(" ");
            }
            String billno = dataEntity.getString("billno");
            title.append("发货特殊申请").append(" ").append(billno);
            dataEntity.set("yem_title", title.toString());
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);

        IFormView view = this.getView();
        String operateKey = e.getOperateKey();
        if ("save".equals(operateKey)) {
            view.invokeOperation("refresh");
        }
    }
}
