package com.yem.wm.es.storagetrans.dynamic;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.es.salesorder.dynamic.ContractResignEdit;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.IPageCache;
import kd.bos.form.control.AttachmentPanel;
import kd.bos.form.control.Control;
import kd.bos.form.control.events.BeforeUploadEvent;
import kd.bos.form.control.events.UploadEvent;
import kd.bos.form.control.events.UploadListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;

import java.util.*;

/**
 * @Description: TODO
 * @Date: 2024/6/3 14:46
 * @Created: by ZZSLL
 */

public class UploadSingleFileEdit extends AbstractFormPlugin implements UploadListener {
    private static final Log log = LogFactory.getLog(ContractResignEdit.class);


    @Override
    public void registerListener(EventObject e)
    {
        super.registerListener(e);

        AttachmentPanel attachmentPanel = this.getView().getControl("yem_attachmentpanelap");
        attachmentPanel.addUploadListener(this);

        this.addClickListeners("btncancel", "btnok");
    }

    @Override
    public void beforeUpload(BeforeUploadEvent evt) {
        UploadListener.super.beforeUpload(evt);
        IPageCache pageCache = this.getView().getPageCache();
        pageCache.put("falg", null);
    }

    @Override
    public void afterUpload(UploadEvent evt) {
        this.addAttachmentContext(this.getModel(), this.getView());
        IPageCache pageCache = this.getView().getPageCache();
        pageCache.put("falg", null);
    }

    private void addAttachmentContext(IDataModel model, IFormView view) {
        IPageCache cache = this.getPageCache();
        List<Map<String, Object>> addAttachmentData = getCache(cache);

        cache.put("attach", addAttachmentData.toString());
        log.error("上传附件之后：" + addAttachmentData);
    }

    @Override
    public void upload(UploadEvent evt) {
        Object[] urls = evt.getUrls();
        IPageCache cache = this.getPageCache();
        List<Map<String, Object>> addAttachmentData = getCache(cache);
        for (Object url : urls) {
            @SuppressWarnings("unchecked")
            Map<String, Object> att = (Map<String, Object>) url;
            addAttachmentData.add(att);
            log.error("上传附件：" + addAttachmentData);
        }
        cache.put("attach", JSONObject.toJSONString(addAttachmentData));
    }

    @Override
    public void remove(UploadEvent evt) {
        this.removeAttachmentContext(this.getView(), this.getModel(), evt);
    }

    private void removeAttachmentContext(IFormView view, IDataModel model, UploadEvent evt) {
        IFormView parentView = view.getParentView();
        AttachmentPanel panel = parentView.getControl("yem_attachmentpanelap1");
        AttachmentPanel source = (AttachmentPanel) evt.getSource();

        IPageCache cache = this.getPageCache();
        List<Map<String, Object>> addAttachmentData = getCache(cache);

        Object[] urls = evt.getUrls();
        for (Object url : urls) {
            @SuppressWarnings("unchecked")
            Map<String, Object> att = (Map<String, Object>) url;
            panel.remove(att);

            for (int i = 0; i < addAttachmentData.size(); i++) {
                Map<String, Object> map = addAttachmentData.get(i);
                if (map.get("name").equals(att.get("name"))) {
                    addAttachmentData.remove(i);
                }
            }
        }
        cache.put("attach", JSONObject.toJSONString(addAttachmentData));
        log.error("删除附件：" + addAttachmentData);
        evt.setCancel(true);
        List<Map<String, Object>> attachmentData = panel.getAttachmentData();
        attachmentData.addAll(addAttachmentData);
        source.bindData(attachmentData);
        parentView.invokeOperation("refresh");
        view.sendFormAction(parentView);
    }

    @Override
    public void click(EventObject e)
    {
        super.click(e);
        Control source = (Control) e.getSource();
        String key = source.getKey();
        if ("btncancel".equals(key)) {
            this.getView().returnDataToParent(null);
            this.getView().close();
        }
        if ("btnok".equals(key)) {
            btnOk();
        }
    }

    private void btnOk() {
        DynamicObject dataEntity = this.getModel().getDataEntity();
        HashMap<String, Object> hashMap = new HashMap<>();
        IPageCache cache = this.getPageCache();
        List<Map<String, Object>> addAttachmentData = getCache(cache);
        hashMap.put("attach", addAttachmentData);
        long user = YEM.getCurrentUserId();
        Date date = new Date();
        hashMap.put("user", user);
        hashMap.put("date", date);
        log.error("关闭界面之前：" + addAttachmentData);
        this.getView().returnDataToParent(hashMap);
        this.getView().close();
        addAttachmentData.clear();//关闭界面清空上传附件
        log.error("关闭界面：" + addAttachmentData);
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        this.creadteAttach(this.getView(), this.getModel(), e);
        IPageCache cache = this.getPageCache();
        List<Map<String, Object>> addAttachmentData = getCache(cache);
        log.error("刷新界面" + addAttachmentData);
    }

    private void creadteAttach(IFormView view, IDataModel model, EventObject e) {
        FormShowParameter showParameter = view.getFormShowParameter();
        List<String> filtername = new ArrayList<>();
        List<Map<String, Object>> attach = showParameter.getCustomParam("attach");
        if (attach != null && attach.size() > 0) {
            AttachmentPanel panel = view.getControl("yem_attachmentpanelap");
            for (Map<String, Object> map : attach) {
                map.put("lastModified", new Date().getTime());
                filtername.add((String)map.get("name"));
            }
            panel.upload(attach);
            view.updateView("yem_attachmentpanelap");

        }
    }

    /**
     * 从缓存中获取附件
     * @param cache
     * @return
     */
    private List<Map<String, Object>> getCache(IPageCache cache) {
        String attach = cache.get("attach");
        List<Map<String, Object>> addAttachmentData = null;
        if (attach != null) {
            addAttachmentData = getJson(attach) == null ? new ArrayList<>() : getJson(attach);
        }else {
            addAttachmentData = new ArrayList<>();
        }
        return addAttachmentData;
    }

    /**
     * 将从缓存中取到的附件转换成List<Map<String,Object>>
     * @param attach
     * @return
     */
    @SuppressWarnings("unchecked")
    private List<Map<String, Object>> getJson(String attach) {
        List<Object> parseArray = (List<Object>) JSONArray.parseObject(attach, List.class);
        List<Map<String, Object>> List = new ArrayList<>();
        for (Object parse : parseArray) {
            Map<String, Object> map = (Map<String, Object>) parse;
            List.add(map);
        }
        return List;
    }
}
