package com.yem.em.ass.assmaterialpicup.op;

import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.fileservice.FileServiceFactory;
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 kd.bos.servicehelper.user.UserServiceHelper;
import org.apache.commons.lang.StringUtils;

import java.util.*;

/**
 * @author zhouc
 * @date 2023/12/1 21:12
 * @className AssMaterialPicSynRemarksOp
 * @description 总成图片批量上传【同步系统（备注服务插件）】
 */
public class AssMaterialPicSynRemarksOp extends AbstractOperationServicePlugIn {

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        super.beginOperationTransaction(e);
        for (DynamicObject dataEntity : e.getDataEntities()) {
            List list = new ArrayList<>();
            List attachlist = new ArrayList<>();
            String pkValue = dataEntity.getPkValue().toString();
            dataEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), dataEntity.getDynamicObjectType().getName());
            DynamicObjectCollection attachmentpanelCol = dataEntity.getDynamicObjectCollection("yem_attachmentpanel");
            for (int i = 0; i < attachmentpanelCol.size(); i++) {
                DynamicObject dynamicObject = attachmentpanelCol.get(i);
                if (dynamicObject.getString("yem_syncstatus").equals("B")) {
                    list.add(dynamicObject.getString("yem_attachmentid"));
                }
            }
            QFilter qFilter1 = new QFilter("fbilltype", QCP.equals, dataEntity.getDynamicObjectType().getName());
            qFilter1.and(new QFilter("finterid", QCP.equals, pkValue));
            if (list.size() > 0) {
                qFilter1.and(new QFilter("fnumber", QCP.not_in, list));
            }
            DynamicObject[] atts = BusinessDataServiceHelper.load("bos_attachment",
                    "id,ffileid,fattachmentname,fattachmentsize",
                    new QFilter[]{qFilter1});
            for (DynamicObject att : atts) {
                String number = "";
                String fileName = att.getString("fattachmentname");
                String ffileid = FileServiceFactory.getAttachmentFileService().getFileServiceExt().getRealPath(att.getString("ffileid"));
                //先根据备注匹配
                String materialNum = StringUtils.substringBeforeLast(fileName, ".").trim();
                QFilter qFilterremark = new QFilter("yem_remark", QCP.equals, materialNum);
                DynamicObject[] yem_em_asscomponentremark = BusinessDataServiceHelper.load("yem_em_assatlasdet", "id,number,yem_imageurl",
                        new QFilter[]{qFilterremark});
                if (yem_em_asscomponentremark.length > 0) {
                    for (DynamicObject etcmanual : yem_em_asscomponentremark) {
                        etcmanual = BusinessDataServiceHelper.loadSingle(etcmanual.getPkValue(), etcmanual.getDynamicObjectType().getName());
                        Map uploadFileMap = new HashMap();
                        uploadFileMap.put("entityNum", etcmanual.getDynamicObjectType().getName());
                        uploadFileMap.put("billPkId", etcmanual.getPkValue().toString());
                        uploadFileMap.put("lastModified", new Date().getTime());
                        uploadFileMap.put("name", fileName);
                        long time = new Date().getTime();
                        StringBuffer uid = new StringBuffer();
                        uid.append("rc-upload-");
                        uid.append(time);
                        uid.append("-");
                        uid.append("1");
                        uploadFileMap.put("uid", uid.toString());
                        uploadFileMap.put("url", att.getString("ffileid"));
                        uploadFileMap.put("size", att.getString("fattachmentsize"));
                        uploadFileMap.put("status", "success");
                        uploadFileMap.put("creator", UserServiceHelper.getCurrentUserId());

                        List<Map<String, Object>> attachments = new ArrayList<>();
                        attachments.add(uploadFileMap);
                        AttachmentServiceHelper.upload(etcmanual.getDynamicObjectType().getName(), etcmanual.getPkValue().toString(), "yem_attachmentpanelap", attachments);
                        String yem_imageurl = etcmanual.getString("yem_imageurl");
                        if (YEM.isEmpty(yem_imageurl)) {
                            etcmanual.set("yem_imageurl", ffileid + ";");
                        } else {
                            etcmanual.set("yem_imageurl", yem_imageurl + ffileid + ";");
                        }
                        Object[] save = SaveServiceHelper.save(new DynamicObject[]{etcmanual});
                        for (DynamicObject attachmentpanel : attachmentpanelCol) {
                            String yem_attachmentname = attachmentpanel.getString("yem_attachmentname");
                            if (yem_attachmentname.equals(fileName)) {
                                attachmentpanel.set("yem_syncstatus", "B");
                            }
                        }
                    }
                } else {
                    String[] split = materialNum.split("-");
                    if (split.length > 0) {
                        number = split[0];
                    } else {
                        number = materialNum;
                    }
                    //总成图册部件
                    QFilter qFilter = new QFilter("number", QCP.equals, number);
                    DynamicObject[] yem_em_asscomponent = BusinessDataServiceHelper.load("yem_em_assatlasdet", "id,number,yem_imageurl",
                            new QFilter[]{qFilter});
                    for (DynamicObject etcmanual : yem_em_asscomponent) {
                        etcmanual = BusinessDataServiceHelper.loadSingle(etcmanual.getPkValue(), etcmanual.getDynamicObjectType().getName());
                        Map uploadFileMap = new HashMap();
                        uploadFileMap.put("entityNum", etcmanual.getDynamicObjectType().getName());
                        uploadFileMap.put("billPkId", etcmanual.getPkValue().toString());
                        uploadFileMap.put("lastModified", new Date().getTime());
                        uploadFileMap.put("name", fileName);
                        uploadFileMap.put("url", att.getString("ffileid"));
                        uploadFileMap.put("size", att.getString("fattachmentsize"));
                        uploadFileMap.put("status", "success");
                        long time = new Date().getTime();
                        StringBuffer uid = new StringBuffer();
                        uid.append("rc-upload-");
                        uid.append(time);
                        uid.append("-");
                        uid.append("1");
                        uploadFileMap.put("uid", uid.toString());
                        uploadFileMap.put("url", att.getString("ffileid"));
                        uploadFileMap.put("size", att.getString("fattachmentsize"));
                        uploadFileMap.put("status", "success");
                        uploadFileMap.put("creator", UserServiceHelper.getCurrentUserId());

                        List<Map<String, Object>> attachments = new ArrayList<>();
                        attachments.add(uploadFileMap);
                        AttachmentServiceHelper.upload(etcmanual.getDynamicObjectType().getName(), etcmanual.getPkValue().toString(), "yem_attachmentpanelap", attachments);
                        String yem_imageurl = etcmanual.getString("yem_imageurl");
                        if (YEM.isEmpty(yem_imageurl)) {
                            etcmanual.set("yem_imageurl", ffileid + ";");
                        } else {
                            etcmanual.set("yem_imageurl", yem_imageurl + ffileid + ";");
                        }
                        updateAttachmentDetailEntry(etcmanual);
                        Object[] save = SaveServiceHelper.save(new DynamicObject[]{etcmanual});

                        for (DynamicObject attachmentpanel : attachmentpanelCol) {
                            String yem_attachmentname = attachmentpanel.getString("yem_attachmentname");
                            if (yem_attachmentname.equals(fileName)) {
                                attachmentpanel.set("yem_syncstatus", "B");
                            }
                        }
                    }
                }
            }
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
        }
    }

    public static DynamicObject updateAttachmentDetailEntry(DynamicObject dynamicObject) {
        String formId = dynamicObject.getDynamicObjectType().getName();
        String pkId = String.valueOf(dynamicObject.getLong("id"));
        DynamicObject[] attachments = BusinessDataServiceHelper.load("bos_attachment", "fattachmentname, fnumber, ffileid, fcreatetime",
                new QFilter[]{new QFilter("fattachmentpanel", "=", "yem_attachmentpanelap"),
                        new QFilter("fbilltype", "=", formId),
                        new QFilter("finterid", "=", pkId)});
        DynamicObjectCollection collection = dynamicObject.getDynamicObjectCollection("yem_attdetail");
        collection.clear();
        for (DynamicObject attObj : attachments) {
            String url = attObj.getString("ffileid");
            String id = attObj.getString("fnumber");
            String name = attObj.getString("fattachmentname");
            Date fcreatetime = attObj.getDate("fcreatetime");
            DynamicObject addNew = collection.addNew();
            addNew.set("yem_attname", name);
            addNew.set("yem_attid", id);
            String realPath = FileServiceFactory.getAttachmentFileService().getFileServiceExt().getRealPath(url);
            addNew.set("yem_attaddress", realPath);
            addNew.set("yem_breakpointime", fcreatetime);
        }
        return dynamicObject;
    }
}
