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.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.bos.url.UrlService;
import org.apache.commons.lang.StringUtils;

import java.util.*;

import static com.yem.em.ass.assmaterialpicup.op.AssMaterialPicSynRemarksOp.updateAttachmentDetailEntry;

/**
 * @author zhouc
 * @date 2023/11/13 21:44
 * @className AssMaterialPicMatchOp
 * @description 总成图片批量上传同步系统服务插件
 */
public class AssMaterialPicMatchOp 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();
                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",
//                DynamicObject[] yem_em_asscomponent = BusinessDataServiceHelper.load("yem_em_asscomponent", "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});
        }
    }

    /**
     * 根据附件面板赋值图片URL
     *
     * @param Object    动态对象
     * @param Fieldname URL字段名曾
     */
    public void setattachmentpanelap(DynamicObject Object, String Fieldname) {
        List list = new ArrayList<>();
        List urllist = new ArrayList<>();
        List<Map<String, Object>> yemAttachmentpanelap =
                AttachmentServiceHelper.getAttachments(Object.getDynamicObjectType().getName(), Object.getPkValue(), "yem_attachmentpanelap");
        for (int i = 0; i < yemAttachmentpanelap.size(); i++) {
            Map<String, Object> stringObjectMap = yemAttachmentpanelap.get(i);
            list.add(stringObjectMap.get("uid"));
        }
        if (list.size() > 0) {
            QFilter qFilter = new QFilter("fnumber", QCP.in, list);
            DynamicObjectCollection collection = QueryServiceHelper.query("bos_attachment",
                    "id,ffileid", new QFilter[]{qFilter}, null);
            if (collection.size() > 0) {
                for (int i = 0; i < collection.size(); i++) {
                    urllist.add(collection.get(i).getString("ffileid"));
                }
            }
            Object.set(Fieldname, String.join(";", urllist) + ";");
        } else {
            Object.set(Fieldname, null);
        }
        SaveServiceHelper.save(new DynamicObject[]{Object});
    }
}
