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

import com.yem.wm.utils.StringUtils;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.BillShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.OpenStyle;
import kd.bos.form.ShowType;
import kd.bos.form.control.AttachmentPanel;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.ImageList;
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.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.form.plugin.IFormPlugin;
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.*;

/**
 * @author zhouc
 * @date 2023/11/25 15:26
 * @className AssAtlasdetFromEdit
 * @description 总成图册明细表单插件
 */
public class AssAtlasdetFromEdit extends AbstractBillPlugIn implements UploadListener, BeforeF7SelectListener {
    private final String IMAGE_LIST_NUM = "yem_imagelistap";
    private final String IMAGE_LIST_URLS = "yem_imageurl";

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        ImageList imageList = this.getView().getControl(IMAGE_LIST_NUM);
        String imageUrls = (String) this.getModel().getValue(IMAGE_LIST_URLS);
        if (StringUtils.isNotEmpty(imageUrls)) {
            String[] urls = imageUrls.split(";");
            imageList.setImageUrls(urls);
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        ImageList imageList = this.getView().getControl(IMAGE_LIST_NUM);
        imageList.addUploadListener(this);
        // 侦听附件面板控件的文件上传事件
        AttachmentPanel attachmentPanel = this.getView().getControl("yem_attachmentpanelap");
        attachmentPanel.addUploadListener(this);

        BasedataEdit partasspartlib = this.getView().getControl("yem_partasspartlib");
        if (partasspartlib != null) {
            partasspartlib.addBeforeF7SelectListener(this);
        }
    }

    @Override
    public void upload(UploadEvent evt) {
        UploadListener.super.upload(evt);
        String key = evt.getCallbackKey();
        IDataModel model = this.getModel();
        Object[] imageLists = evt.getUrls();
        if (key.equals(IMAGE_LIST_NUM)) {
            for (int i = 0; i < imageLists.length; i++) {
                String url = imageLists[i].toString() + ";";
                String urls = model.getValue(IMAGE_LIST_URLS).toString();
                model.setValue(IMAGE_LIST_URLS, urls + url);
            }
            this.getView().updateView(IMAGE_LIST_URLS);
        }

        if (key.equals("yem_attachmentpanelap")) {
            for (Object image : imageLists) {
                Map<String, Object> map = (Map<String, Object>) image;
                int idx = model.createNewEntryRow("yem_attdetail");
                model.setValue("yem_attname", map.get("name"), idx);
                model.setValue("yem_attid", map.get("uid"), idx);
                model.setValue("yem_breakpointime", new Date(), idx);
            }
        }
    }


    @Override
    public void remove(UploadEvent e) {
        UploadListener.super.remove(e);
        Object[] urls = e.getUrls();
        IDataModel model = this.getModel();
        for (Object url : urls) {
            Map<String, Object> map = (Map<String, Object>) url;
            String uid = (String) map.get("uid");
            int attdetail = model.getEntryRowCount("yem_attdetail");
            for (int i = attdetail - 1; i >= 0; i--) {
                String attid = (String) model.getValue("yem_attid", i);
                if (uid.equals(attid)) {
                    model.deleteEntryRow("yem_attdetail", i);
                }
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        IDataModel model = this.getModel();
        String operateKey = e.getOperateKey();
        DynamicObject bill = model.getDataEntity(true);
        if ("save".equals(operateKey)) {
            ImageList imageList = this.getView().getControl(IMAGE_LIST_NUM);
            List<Map<String, Object>> yemAttachmentpanelap =
                    AttachmentServiceHelper.getAttachments(bill.getDynamicObjectType().getName(), bill.getPkValue(), "yem_attachmentpanelap");
            if (yemAttachmentpanelap.size() > 0) {
                String imageUrls = (String) model.getValue(IMAGE_LIST_URLS);
                if (StringUtils.isNotEmpty(imageUrls)) {
                    String[] urls = imageUrls.split(";");
                    imageList.setImageUrls(urls);
                }
            } else {
                String[] urls = new String[]{""};
                imageList.setImageUrls(urls);
            }

            List<String> attids = new ArrayList<>();
            int attdetail = model.getEntryRowCount("yem_attdetail");
            for (int i = 0; i < attdetail; i++) {
                String attaddress = (String) model.getValue("yem_attaddress", i);
                if (YEM.isNotEmpty(attaddress)) {
                    continue;
                }
                String attid = (String) model.getValue("yem_attid", 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_attid", i);
                    if (attid.equals(id)) {
                        String ffileid = FileServiceFactory.getAttachmentFileService().getFileServiceExt().getRealPath(url);
                        model.setValue("yem_attaddress", ffileid, i);
                    }
                }
            }
            DynamicObject dataEntity = model.getDataEntity(true);
            SaveServiceHelper.update(new DynamicObject[]{dataEntity});
            this.getView().invokeOperation("refresh");
        }
        if ("viewatlas".equals(operateKey)) {
            DynamicObject dataEntity = model.getDataEntity(true);
            //电子目录编码
            String number = dataEntity.getString("number");
            if (StringUtils.isNotEmpty(number)) {
                FormShowParameter showParameter = new FormShowParameter();
//                BillShowParameter showParameter = new BillShowParameter();
                showParameter.setFormId("yem_em_assepcdynamic");
                showParameter.setCloseCallBack(new CloseCallBack((IFormPlugin) this, "bug"));
                Map<String, Object> entryInfo = new HashMap<String, Object>();
                showParameter.setStatus(OperationStatus.ADDNEW);
                entryInfo.put("etcId", dataEntity.getString("id"));
                entryInfo.put("number", number);
                entryInfo.put("name", dataEntity.getString("name"));
                entryInfo.put("orgId", RequestContext.get().getOrgId());
                entryInfo.put("type", "atlas");
                showParameter.setCustomParams(entryInfo);
                showParameter.setCaption("总成图册");
                showParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                this.getView().showForm(showParameter);
            }
        }

        if ("isdisable".equals(operateKey)) {
            DynamicObject dataEntity = model.getDataEntity(true);
            EntryGrid entryGrid = this.getControl("yem_entryentity");
            int selectRows[] = entryGrid.getSelectRows();
            if (selectRows.length > 0) {
                for (int row : selectRows) {
                    this.getView().getModel().setValue("yem_disablestat", "B", row);
                    this.getView().getModel().setValue("yem_disableuser", YEM.getCurrentUserId(), row);
                    this.getView().getModel().setValue("yem_disabledate", new Date(), row);
                }
                this.getView().invokeOperation("save");
                this.getView().showSuccessNotification("操作完成");
            } else {
                this.getView().showErrorNotification("请至少选择一行进行操作！");
            }
        }
        if ("notisdisable".equals(operateKey)) {
            EntryGrid entryGrid = this.getControl("yem_entryentity");
            int selectRows[] = entryGrid.getSelectRows();
            if (selectRows.length > 0) {
                for (int row : selectRows) {
                    this.getView().getModel().setValue("yem_disablestat", "A", row);
                    this.getView().getModel().setValue("yem_disableuser", null, row);
                    this.getView().getModel().setValue("yem_disabledate", null, row);
                }
                this.getView().invokeOperation("save");
                this.getView().showSuccessNotification("操作完成");
            } else {
                this.getView().showErrorNotification("请至少选择一行进行操作！");
            }
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        AbstractOperate operate = (AbstractOperate) args.getSource();
        String key = operate.getOperateKey();
        if (key.equals("deleteentry")) {
            int row = this.getView().getModel().getEntryCurrentRowIndex("yem_entryentity");
            String yem_partnumber = (String) this.getView().getModel().getValue("yem_partnumber", row);
            Boolean yem_isadd = (Boolean) this.getView().getModel().getValue("yem_isadd", row);
            Boolean yem_isdelete = (Boolean) this.getView().getModel().getValue("yem_isdelete", row);
            Boolean yem_partisreplace = (Boolean) this.getView().getModel().getValue("yem_partisreplace", row);
            if (yem_isadd || yem_isdelete || yem_partisreplace) {
                this.getView().showErrorNotification("编码【" + yem_partnumber + "】存在替换关系，禁止删除！！");
                args.cancel = true;
            }
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String key = e.getProperty().getName();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObject createorg = dataEntity.getDynamicObject("createorg");
        if ("yem_partasspartlib".equals(key)) {
            if (createorg != null) {
                Long orgId = createorg.getLong("id");
                e.addCustomQFilter(new QFilter("createorg.id", QCP.equals, orgId));
            }
        }
    }
}
