package com.yem.wm.im.csrCreditLine.dynamic;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.clr.DataEntityPropertyCollection;
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.UploadEvent;
import kd.bos.form.control.events.UploadListener;

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

/**
 * @author ljw
 * @date 2024/5/28 14:12
 * @description InsuranceBackfillEdit
 */
public class InsuranceBackfillEdit extends AbstractBillPlugIn implements UploadListener {
    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        IFormView parentView = this.getView().getParentView();
        IDataModel parentModel = parentView.getModel();
        IDataModel model = this.getModel();
        DataEntityPropertyCollection properties = model.getDataEntityType().getProperties();
        for (IDataEntityProperty property : properties) {
            String propName = property.getName();
            if (parentModel.getProperty(propName) != null) {
                Object propValue = parentModel.getValue(propName);
                if (propValue instanceof DynamicObject) {
                    DynamicObject obj = (DynamicObject) propValue;
                    model.setValue(propName, obj.getPkValue());
                } else {
                    model.setValue(propName, propValue);
                }
            }
        }

        this.creadteAttach(this.getView(), this.getModel(), e);
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners("btnok");

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


    @Override
    public void click(EventObject evt) {
        super.click(evt);
        Control source = (Control) evt.getSource();
        String name = source.getKey();
        if (name.equals("btnok")) {
            Map<String, Object> hashMap = new HashMap<>();
            String project = (String) this.getModel().getValue("yem_creditperiod");
            if (project != null) {
                hashMap.put("yem_creditperiod",(String) this.getModel().getValue("yem_creditperiod"));
                hashMap.put("yem_customersinosure",(String)this.getModel().getValue("yem_customersinosure"));
                hashMap.put("yem_insurancebuyercode",(String)this.getModel().getValue("yem_insurancebuyercode"));
                hashMap.put("yem_currency",(DynamicObject)this.getModel().getValue("yem_currency"));
                hashMap.put("yem_replylimit",(BigDecimal)this.getModel().getValue("yem_replylimit"));
                hashMap.put("yem_effectday",(Date)this.getModel().getValue("yem_effectday"));
                hashMap.put("yem_recentlapse",(Date)this.getModel().getValue("yem_recentlapse"));
                hashMap.put("yem_inactivityperiod",(Integer)this.getModel().getValue("yem_inactivityperiod"));
                hashMap.put("yem_unused",(Date)this.getModel().getValue("yem_unused"));
                hashMap.put("yem_countdown",(Integer)this.getModel().getValue("yem_countdown"));
                hashMap.put("yem_appointlapse",(Date)this.getModel().getValue("yem_appointlapse"));
                hashMap.put("yem_tardypercent",(BigDecimal)this.getModel().getValue("yem_tardypercent"));
                hashMap.put("yem_politicspercent",(BigDecimal)this.getModel().getValue("yem_politicspercent"));
                hashMap.put("yem_rejectionrisk",(BigDecimal)this.getModel().getValue("yem_rejectionrisk"));
                hashMap.put("yem_bankruptcyrisk",(BigDecimal)this.getModel().getValue("yem_bankruptcyrisk"));
                hashMap.put("yem_bankrisk",(BigDecimal)this.getModel().getValue("yem_bankrisk"));
                hashMap.put("yem_specialconditions",(String)this.getModel().getValue("yem_specialconditions"));
                hashMap.put("yem_initoccupancy",(BigDecimal)this.getModel().getValue("yem_initoccupancy"));
                hashMap.put("yem_initcollectionamt",(BigDecimal)this.getModel().getValue("yem_initcollectionamt"));
                hashMap.put("yem_otherbankrate", this.getModel().getValue("yem_otherbankrate"));
                hashMap.put("yem_confirmedrisk", this.getModel().getValue("yem_confirmedrisk"));
                DynamicObject bankcountry = (DynamicObject) this.getModel().getValue("yem_bankcountry");
                if (YEM.isNotEmpty(bankcountry)) {
                    hashMap.put("yem_bankcountry", bankcountry.getPkValue());
                } else {
                    hashMap.put("yem_bankcountry", 0L);
                }
                hashMap.put("yem_swiftcode", this.getModel().getValue("yem_swiftcode"));
                //返回数据
                this.getView().returnDataToParent(hashMap);
                this.getView().close();
            }

//            HashMap<String, Object> retMap = new HashMap<>();
            IPageCache cache = this.getPageCache();
            List<Map<String, Object>> addAttachmentData = getCache(cache);
            hashMap.put("attach", addAttachmentData);
            this.getView().returnDataToParent(hashMap);
            this.getView().close();
            addAttachmentData.clear();//关闭界面清空上传附件
        }
    }

    @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);
        }
        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("attachmentpanel");
        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));
        evt.setCancel(true);
        List<Map<String, Object>> attachmentData = panel.getAttachmentData();
        attachmentData.addAll(addAttachmentData);
        source.bindData(attachmentData);
        parentView.invokeOperation("refresh");
        view.sendFormAction(parentView);
    }

    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;
    }
}