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

import com.yem.wm.es.contactbook.validator.ContactBookSaveValidator;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Classname ContactBookSaveOp
 * @Description TODO
 * @Date 2023/12/21 15:05
 * @Created by ZZSLL
 */

public class ContactBookSaveOp extends AbstractOperationServicePlugIn
{
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e)
    {
        super.onPreparePropertys(e);
        List<String> keys = e.getFieldKeys();
        keys.add("yem_attachmentpanelap2");
        keys.add("yem_attachmentpanelap3");
        keys.add("yem_attachmentpanelap");
        keys.add("billno");
        keys.add("id");
    }

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

    }



    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e)
    {
        super.beforeExecuteOperationTransaction(e);

        DynamicObject[] dataEntities = e.getDataEntities();
        String operationKey = e.getOperationKey();
        if ("save".equals(operationKey)) {
            for (DynamicObject dataEntity : dataEntities) {
                String billno = dataEntity.getString("billno");

                QFilter qFilter = new QFilter("billno", QCP.equals, billno);
                DynamicObject[] load = BusinessDataServiceHelper.load("yem_es_storagetrans", "id, billno", qFilter.toArray());

                for (DynamicObject dynamicObject : load) {

                    AttachmentServiceHelper.remove("yem_es_storagetrans", dynamicObject.getLong("id"));

                    uploadAttachmentPanel(dataEntity, dynamicObject);
                }
            }

            // 反写关联发货联系数量
//            for (DynamicObject dataEntity : dataEntities) {
//
//                String billno = dataEntity.getString("yem_storagetransno");
//                DynamicObject yem_producttype = dataEntity.getDynamicObject("yem_producttype");
//                if (yem_producttype == null) throw new KDBizException("产品类型不能为空");
//                long producttype = yem_producttype.getLong("id");
//                DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
//                List<Long> book = new ArrayList<>();
//                for (DynamicObject dynamicObject : collection) {
//                    book.add(dynamicObject.getLong("yem_sourceentryid"));
//                }
//                DynamicObject single = BusinessDataServiceHelper.loadSingle("yem_es_storagetrans", new QFilter[]{new QFilter("billno", QCP.equals, billno)});
//                if (single == null) continue;
//                DynamicObjectCollection materialinfo = single.getDynamicObjectCollection("yem_es_materialinfo");
//                List<Long> origin = new ArrayList<>();
//                for (DynamicObject dynamicObject : materialinfo) {
//                    DynamicObject products = dynamicObject.getDynamicObject("yem_products");
//                    if (products == null) continue;
//                    if (producttype == products.getLong("id")) {
//                        origin.add((Long) dynamicObject.getPkValue());
//                    }
//                }
//                for (DynamicObject object : collection) {
//                    for (DynamicObject materialinfoEntry : materialinfo) {
//                        Long pkValue = (Long) materialinfoEntry.getPkValue();
//                        if (object.getLong("yem_sourceentryid") == pkValue) {
//                            materialinfoEntry.set("yem_contactbookqty", object.getBigDecimal("yem_qty"));
//                        }
//                    }
//                }
//                List<Long> result = new ArrayList<>(CollectionUtils.removeAll(origin, book));
//                for (DynamicObject dynamicObject : materialinfo) {
//                    for (Long longId : result) {
//                        if (longId.equals(dynamicObject.getPkValue())) {
//                            dynamicObject.set("yem_contactbookqty", 0);
//                        }
//                    }
//                }
//                single.set("yem_secdeliverytime", dataEntity.get("yem_secdeliverytime"));
//                SaveServiceHelper.update(single);
//            }
        }
    }

    public static void uploadAttachmentPanel(DynamicObject from, DynamicObject to) {
        List<Map<String, Object>> attachments = AttachmentServiceHelper
                .getAttachmentsByExport(from.getDataEntityType().getName(), from.getLong("id"));
        List<Map<String, Object>> toattachments = AttachmentServiceHelper
                .getAttachmentsByExport(to.getDynamicObjectType().getName(), to.getLong("id"));
        List<String> toname = toattachments.stream().map(x -> (String) x.get("name")).collect(Collectors.toList());
        for (Map<String, Object> map : attachments) {
            String fileName = (String) map.get("name");
            if (fileName != null && !toname.contains(fileName)) {// 判断源单的附件是否在目标单上存在
                DynamicObject newAtt = BusinessDataServiceHelper.newDynamicObject("bos_attachment");
                Long id = ORM.create().genLongId("bos_attachment");
                newAtt.set("id", id);
                newAtt.set("fnumber", "upload_" + id);
                newAtt.set("FBillType", to.getDataEntityType().getName());
                newAtt.set("FInterID", to.getString("id"));
                newAtt.set("FModifyTime", map.get("lastModified"));
                newAtt.set("fcreatetime", map.get("createdate"));
                newAtt.set("FaliasFileName", fileName);
                newAtt.set("FAttachmentName", fileName);
                newAtt.set("FFileId", map.get("url"));
                newAtt.set("FExtName", map.get("type"));
                newAtt.set("FATTACHMENTSIZE", map.get("size"));
                newAtt.set("FCREATEMEN", map.get("creator"));
                newAtt.set("fattachmentpanel", map.get("fattachmentpanel"));
                newAtt.set("fdescription", map.get("description"));
                SaveServiceHelper.save(new DynamicObject[] { newAtt });
            }
        }
    }
}
