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

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.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.FormShowParameter;
import kd.bos.form.control.AttachmentPanel;
import kd.bos.form.control.events.BeforeAttachmentRemoveEvent;
import kd.bos.form.control.events.BeforeAttachmentRemoveListener;
import kd.bos.form.control.events.UploadEvent;
import kd.bos.form.control.events.UploadListener;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.bos.url.UrlService;

import java.util.*;

/**
 * @author zhouc
 * @date 2023/11/13 21:01
 * @className AssMaterialpicupEdit
 * @description 总成图片批量上传表单插件
 */
public class AssMaterialpicupEdit extends AbstractBillPlugIn implements UploadListener, BeforeAttachmentRemoveListener {

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        AbstractOperate operate = (AbstractOperate) args.getSource();
        String key = operate.getOperateKey();
        if (key.equals("match")) {
            if (this.getView().getModel().getDataChanged()) {
                this.getView().showErrorNotification(ResManager.loadKDString("请先保存单据！", "EtcmanualImportEdit_0", "bfcl_equipment"));
                args.cancel = true;
            }
        }
        if (key.equals("synremarks")) {
            if (this.getView().getModel().getDataChanged()) {
                this.getView().showErrorNotification(ResManager.loadKDString("请先保存单据！", "EtcmanualImportEdit_0", "bfcl_equipment"));
                args.cancel = true;
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        if ("match".equals(operateKey)) {
            this.getView().invokeOperation("refresh");
        }
        if ("synremarks".equals(operateKey)) {
            this.getView().invokeOperation("refresh");
        }
        if ("getfj".equals(operateKey)) {
            String RealPath = FileServiceFactory.getAttachmentFileService().getFileServiceExt().getRealPath("0774abebf57042d7a0dd97dfa21037fb");// 传你拿到的url，其实是ffileid

            String FullUrl = UrlService.getAttachmentFullUrl("0774abebf57042d7a0dd97dfa21037fb");
            String s1 = UrlService.getCheckAuthImageUrl("/sample/1716218006532523008/202307/yem_equipment/yem_em_materialpicupload/1737180187134550016/attachments/5e08f5da83654143a6d42ee20a737288/115900069.png");
            AttachmentPanel attachmentPanel = getControl("attachmentpanel");
            List<Map<String, Object>> attachmentData2 = attachmentPanel.getAttachmentData();
            if (attachmentData2.size() > 0) {
            }

//            AttachmentEdit attEdit2 = this.getView().getControl("kded_attachment");


        }

        if ("save".equals(operateKey)) {
            IDataModel model = this.getModel();
            List<String> attids = new ArrayList<>();
            int attdetail = model.getEntryRowCount("yem_attachmentpanel");
            for (int i = 0; i < attdetail; i++) {
                String attaddress = (String) model.getValue("yem_ffileid", i);
                if (YEM.isNotEmpty(attaddress)) {
                    continue;
                }
                String attid = (String) model.getValue("yem_attachmentid", i);
                attids.add(attid);
            }

            DynamicObject[] load = BusinessDataServiceHelper.load("bos_attachment", "fnumber, ffileid", new QFilter[]{new QFilter("fnumber", "in", attids)});
            for (DynamicObject attObj : load) {
                String url = attObj.getString("ffileid");
                String id = attObj.getString("fnumber");
                for (int i = 0; i < attdetail; i++) {
                    String attid = (String) model.getValue("yem_attachmentid", i);
                    if (attid.equals(id)) {
                        String ffileid = FileServiceFactory.getAttachmentFileService().getFileServiceExt().getRealPath(url);
                        model.setValue("yem_ffileid", ffileid, i);
                    }
                }
            }
            DynamicObject dataEntity = model.getDataEntity(true);
            SaveServiceHelper.update(new DynamicObject[]{dataEntity});
            this.getView().invokeOperation("refresh");
        }
    }

    /**
     * 附件表格
     */
    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        AttachmentPanel attachmentPanel = this.getView().getControl("attachmentpanel");
        attachmentPanel.addUploadListener(this);
        attachmentPanel.addBeforeRemoveListener(this);
    }

    @Override
    public void afterUpload(UploadEvent evt) {
        Object[] Urls = evt.getUrls();
        IDataModel model = this.getModel();
        for (Object Url : Urls) {
            Map<String, Object> urlmap = (Map) Url;
            String name = urlmap.get("name").toString();
            int rowinx = model.createNewEntryRow("yem_attachmentpanel");
            model.setValue("yem_attachmentname", name, rowinx);
            model.setValue("yem_syncstatus", "A", rowinx);
            model.setValue("yem_attachmentid", urlmap.get("uid"), rowinx);
            model.setValue("yem_breakpointime", new Date(), rowinx);
        }
    }

    @Override
    public void afterRemove(UploadEvent evt) {
        DynamicObjectCollection attachmentpanelCol = this.getModel().getEntryEntity("yem_attachmentpanel");
        Object[] Urls = evt.getUrls();
        for (Object Url : Urls) {
            Map<String, Object> urlmap = (Map) Url;
            String name = urlmap.get("name").toString();
            for (int i = attachmentpanelCol.size() - 1; i >= 0; i--) {
                DynamicObject attachmentpanel = attachmentpanelCol.get(i);
                String yem_attachmentname = attachmentpanel.getString("yem_attachmentname");
                if (yem_attachmentname.equals(name)) {
                    this.getModel().deleteEntryRow("yem_attachmentpanel", i);
                }
            }
        }
    }

    @Override
    public void beforeAttachmentRemove(BeforeAttachmentRemoveEvent e) {
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        String status = showParameter.getStatus().toString();
        if (!status.equals("ADDNEW")) {
            long userId = UserServiceHelper.getCurrentUserId();
            DynamicObject bos_user = BusinessDataServiceHelper.loadSingleFromCache(userId, "bos_user");
            Map<String, Object> map = e.getAttachemnt();
            AttachmentPanel attachmentPanel = (AttachmentPanel) e.getSource();
            String uid = (String) map.get("uid");
            List<Map<String, Object>> attachmentData = attachmentPanel.getAttachmentData();
            for (Map<String, Object> data : attachmentData) {
                String uidAttachment = (String) data.get("uid");
                if (!StringUtils.isEmpty(uidAttachment)) {
                    if (uidAttachment.equals(uid)) {
                        String creator = data.get("creator").toString();
                        if (!creator.contains(bos_user.getString("name"))) {
                            e.setMsg("不能删除别人上传的附件!!!");
                            e.setCancel(true);
                        }
                    }
                }
            }
        }
    }
}
