package yem.wm.cm.htqs.form;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;


import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.IClientViewProxy;
import kd.bos.form.IFormView;
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.ClientCallBackEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import oadd.org.apache.commons.lang.math.NumberUtils;
import yem.base.common.utils.YEM;

/**
 * 附件表格-通用插件
 *
 * @author longh
 * @description 附件类型分录<->附件面板-同步
 * 添加附件回填的逻辑
 * @date 2023年8月25日
 */
public class AttachmentEntryFormPlugin extends AbstractBillPlugIn
        implements UploadListener, BeforeF7SelectListener, BeforeAttachmentRemoveListener {
    private static final String KEY_ATT_ENTRY = "yem_attachmentdetail";
    private static final String KEY_ATT_TAG = "yem_attachmentcon_tag";
    private static final String KEY_ATT_PANEL = "attachmentpanel";

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit attachmenttype = this.getView().getControl("yem_attachmenttype");
        attachmenttype.addBeforeF7SelectListener(this);
        AttachmentPanel attachmentPanel = this.getView().getControl("attachmentpanel");
        attachmentPanel.addUploadListener(this);
        attachmentPanel.addBeforeRemoveListener(this);
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        setAttachmentEntry();
        this.getModel().setDataChanged(false);
        setAttFileVisble();
    }

    private void setAttFileVisble() {
        AttachmentPanel panel = getControl(KEY_ATT_PANEL);
        List<Map<String, Object>> attachmentData = panel.getAttachmentData();
        if (attachmentData == null && attachmentData.isEmpty()) {
            return;
        }
        for (Map<String, Object> attachmentMap : attachmentData) {
            String visiablePreview = "1";//是否显示预览按钮
            String visiableDownload = "1";//是否显示下载按钮
            String visiableDelete = "0";//是否显示删除按钮
            String visiableRename = "1";//是否显示重命名按钮
            //visible参数规则为01组成,0代表不可见,1代表可见
            attachmentMap.put("visible", visiablePreview + visiableDownload + visiableDelete + visiableRename);
        }
        IClientViewProxy clientViewProxy = getView().getService(IClientViewProxy.class);
        clientViewProxy.setEntryProperty(KEY_ATT_PANEL, "data", attachmentData);
    }

    @Override
    public void afterUpload(UploadEvent evt) {
        setAttachmentEntry();
//		DynamicObjectCollection entryRows = this.getModel().getEntryEntity("yem_attachmentdetail");
//		int entryCurrentRowIndex = this.getModel().getEntryCurrentRowIndex("yem_attachmentdetail");
//		if (entryRows.size() > 0) {
//			afterData(entryRows, entryCurrentRowIndex);
//		}
    }

    @Override
    public void afterRemove(UploadEvent evt) {
        setAttachmentEntry();
    }

    protected void setAttachmentEntry() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        List<JSONObject> attList = new ArrayList<>();
        String jsonStr = (String) model.getValue(KEY_ATT_TAG);
        JSONObject json = YEM.isEmpty(jsonStr) ? new JSONObject() : JSONObject.parseObject(jsonStr);
        model.deleteEntryData(KEY_ATT_ENTRY);
        AttachmentPanel attachmentpanel = view.getControl(KEY_ATT_PANEL);
        List<Map<String, Object>> attachmentDatas = attachmentpanel.getAttachmentData();
        for (Map<String, Object> attachmentData : attachmentDatas) {
            String uid = (String) attachmentData.get("uid");
            String name = (String) attachmentData.get("name");// 附件名称
            Map<?, ?> maps = (Map<?, ?>) attachmentData.get("creator");

            JSONObject attJson = json.containsKey(uid) ? json.getJSONObject(uid) : new JSONObject();
            attJson.put("name", name);
            long times = (long) attachmentData.get("createdate");
            Date date = new Date(times);
            attJson.put("createdate", date);
            String lang = YEM.requestContext().getLang().toString();

            attJson.put("uid", uid);
            if (maps != null && maps.containsKey(lang)) {
                attJson.put("creator", maps.get(lang));
            }
            json.put(uid, attJson);
            attList.add(attJson);
        }

        List<JSONObject> collect = attList.stream().sorted(new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                Date date1 = o1.getDate("createdate");
                Date date2 = o2.getDate("createdate");
                if (date1 == null || date2 == null) {
                    return 0;
                }
                return date1.compareTo(date2);
            }

        }).collect(Collectors.toList());
        for (JSONObject attJson : collect) {
            int index = model.createNewEntryRow(KEY_ATT_ENTRY);
            model.beginInit();
            model.setValue("yem_attachmentname", attJson.get("name"), index);
            model.setValue("yem_attachmenttype", attJson.get("yem_attachmenttype"), index);
            model.setValue("yem_attachnumber", attJson.get("uid"), index);
            model.setValue("yem_templateid", attJson.getString("tplId"), index);

            model.endInit();
            view.updateView("yem_attachmentname", index);
            view.updateView("yem_attachmenttype", index);
            view.updateView("yem_attachnumber", index);
            view.updateView("yem_templateid", index);

        }
        model.setValue(KEY_ATT_TAG, json.toJSONString());
        //setAttachmentEntry();
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        ChangeData[] changeSet = e.getChangeSet();
        int rowIndex = changeSet[0].getRowIndex();
        String name = e.getProperty().getName();
        switch (name) {
            case "yem_attachmenttype":
                setAttachmentType(rowIndex);
                break;
            case "yem_attachmentcount":
                //附件数的逻辑，先注
                //uploadAttachment(changeSet);
                break;
        }

    }

    private void uploadAttachment(ChangeData[] changeSet) {
        Integer oldCount = (Integer) changeSet[0].getOldValue();
        Integer newCount = (Integer) changeSet[0].getNewValue();
        if (oldCount.equals(newCount)) {
            this.getView().addClientCallBack("auto_save", 0);
        }
    }

    @Override
    public void clientCallBack(ClientCallBackEvent e) {
        super.clientCallBack(e);
        if (e.getName().equals("auto_save")) {
            AttachmentPanel attachmentPanel = getControl(KEY_ATT_PANEL);
            List<Map<String, Object>> data = attachmentPanel.getAttachmentData();
            if (data != null & !data.isEmpty()) {
//				String billstatus = (String) this.getView().getModel().getValue("billstatus");
//				if (!"A".equals(billstatus)) {
                OperationResult saveResult = this.getView().invokeOperation("save", YEM.getOptionNoMsg());
                //}
            }
        }
    }

    private void setAttachmentType(int rowIndex) {
        IDataModel model = this.getModel();
        String jsonStr = (String) model.getValue(KEY_ATT_TAG);
        JSONObject json = YEM.isEmpty(jsonStr) ? new JSONObject() : JSONObject.parseObject(jsonStr);
        String yem_attachnumber = (String) model.getValue("yem_attachnumber", rowIndex);
        DynamicObject yem_attachmenttype = (DynamicObject) model.getValue("yem_attachmenttype", rowIndex);
        if (json.containsKey(yem_attachnumber)) {
            JSONObject attJson = json.getJSONObject(yem_attachnumber);
            if (attJson == null) {
                attJson = new JSONObject();
            }

//			if (attJson.get("yem_attachmenttype") == null){
            attJson.put("yem_attachmenttype", yem_attachmenttype == null ? null : yem_attachmenttype.getPkValue());
//			}else {
//				model.setValue("yem_attachmenttype",attJson.get("yem_attachmenttype"),rowIndex);
//			}

            json.put(yem_attachnumber, attJson);
        }
        model.setValue(KEY_ATT_TAG, json.toJSONString());
        //this.getView().invokeOperation("save");
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        OperationResult operationResult = e.getOperationResult();
        if (operationResult != null && operationResult.isSuccess()) {
            setAttachmentEntry();
            this.getModel().setDataChanged(false);
        }
    }

    @Override
    public void beforeAttachmentRemove(BeforeAttachmentRemoveEvent e) {

    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String name = e.getProperty().getName();
        switch (name) {
            case "yem_attachmenttype":
                attachmentTypeF7(e);
                break;
            default:
                break;
        }
    }

    /**
     * 附件类型过滤
     *
     * @param e
     */
    private void attachmentTypeF7(BeforeF7SelectEvent e) {
        ListShowParameter showParameter = (ListShowParameter) e.getFormShowParameter();
        String billKey = this.getView().getEntityId();
//		NewVersionHelper vHelper = new NewVersionHelper(billKey);
//		if (vHelper.isChanged()) {
//			billKey = vHelper.getRequireKey();
//		}
        QFilter qFilter = new QFilter("yem_attachbillentry.yem_requiredbill.number", QCP.equals, billKey);
        showParameter.getListFilterParameter().getQFilters().add(qFilter);
    }

}
