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

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.cache.CacheFactory;
import kd.bos.cache.TempFileCache;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.AttachmentPanel;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.bos.util.FileNameUtils;

import java.io.InputStream;
import java.util.*;

public class CsrCreditLineEdit extends AbstractBillPlugIn {


    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addItemClickListeners("insurancebackfill");
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        IDataModel model = this.getModel();
        switch (name) {
            case "yem_customer":
                Showquery();
                break;
            case "yem_ladingdate":
                updateRecentLapse(model);
                break;
            default:
                break;
        }
    }

    /**
     * 更新最新责任生效日
     */
    public static void updateRecentLapse(IDataModel model) {
        int rowCount = model.getEntryRowCount("yem_im_info");
        List<Date> list = new ArrayList<>();
        for (int i = 0; i < rowCount; i++) {
            Date ladingdate = (Date) model.getValue("yem_ladingdate", i);
            if (ladingdate != null) {
                list.add(ladingdate);
            }
        }
        if (!list.isEmpty()) {
            list.sort(Comparator.reverseOrder());
            Date date = list.get(0);
            model.setValue("yem_recentlapse", date);
        }
    }

    public static void updateRecentLapseUseDataEntity(DynamicObject dynamicObject) {
        DynamicObjectCollection collection = dynamicObject.getDynamicObjectCollection("yem_im_info");
        List<Date> list = new ArrayList<>();
        for (DynamicObject object : collection) {
            Date ladingdate = object.getDate("yem_ladingdate");
            list.add(ladingdate);
        }
        if (!list.isEmpty()) {
            list.sort(Comparator.reverseOrder());
            Date date = list.get(0);
            dynamicObject.set("yem_recentlapse", date);
        }
    }


    private void Showquery() {
        DynamicObject value = (DynamicObject) this.getModel().getValue("yem_customer");
        if (value != null) {
            String yemCreditinsurance = value.getString("yem_creditinsurance");
            String yem_customer = value.getString("yem_customer");
            this.getModel().setValue("yem_customersinosure", yemCreditinsurance);
            this.getModel().setValue("yem_insurancebuyercode", yem_customer);
//            if (!"".equals(yemCreditinsurance) && !"".equals(yem_customer)) {
            this.getView().setEnable(true, "yem_customersinosure");
            this.getView().setEnable(true, "yem_insurancebuyercode");
//            } else {
//                this.getView().setEnable(false, "yem_customersinosure");
//                this.getView().setEnable(false, "yem_insurancebuyercode");
//            }
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        String value = (String) this.getModel().getValue("billstatus");
        if ("C".equals(value)) {
            this.getView().setEnable(true, "yem_customersinosure");
            this.getView().setEnable(true, "yem_insurancebuyercode");
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);

        String operateKey = e.getOperateKey();
        if ("insurancebackfill".equals(operateKey)) {
            AttachmentPanel control = this.getControl("attachmentpanel");
            List<Map<String, Object>> attachmentData = control.getAttachmentData();
            FormShowParameter ShowParameter = new FormShowParameter();
            ShowParameter.setFormId("yem_insurancebackfill");
            ShowParameter.setCustomParam("attach", attachmentData);
            ShowParameter.setCloseCallBack(new CloseCallBack(this, "yem_baritemap"));
            ShowParameter.getOpenStyle().setShowType(ShowType.Modal);
            this.getView().showForm(ShowParameter);
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        super.closedCallBack(closedCallBackEvent);
        Object returnData = closedCallBackEvent.getReturnData();
        //子页面数据回调
        Map hashMap = (HashMap) returnData;
        if (hashMap != null) {
            this.getModel().setValue("yem_creditperiod", hashMap.get("yem_creditperiod"));
            this.getModel().setValue("yem_customersinosure", hashMap.get("yem_customersinosure"));
            this.getModel().setValue("yem_insurancebuyercode", hashMap.get("yem_insurancebuyercode"));
            this.getModel().setValue("yem_currency", hashMap.get("yem_currency"));
            this.getModel().setValue("yem_replylimit", hashMap.get("yem_replylimit"));
            this.getModel().setValue("yem_effectday", hashMap.get("yem_effectday"));
            this.getModel().setValue("yem_recentlapse", hashMap.get("yem_recentlapse"));
            this.getModel().setValue("yem_inactivityperiod", hashMap.get("yem_inactivityperiod"));
            this.getModel().setValue("yem_unused", hashMap.get("yem_unused"));
            this.getModel().setValue("yem_countdown", hashMap.get("yem_countdown"));
            this.getModel().setValue("yem_appointlapse", hashMap.get("yem_appointlapse"));
            this.getModel().setValue("yem_tardypercent", hashMap.get("yem_tardypercent"));
            this.getModel().setValue("yem_politicspercent", hashMap.get("yem_politicspercent"));
            this.getModel().setValue("yem_rejectionrisk", hashMap.get("yem_rejectionrisk"));
            this.getModel().setValue("yem_bankruptcyrisk", hashMap.get("yem_bankruptcyrisk"));
            this.getModel().setValue("yem_bankrisk", hashMap.get("yem_bankrisk"));
            this.getModel().setValue("yem_specialconditions", hashMap.get("yem_specialconditions"));
            this.getModel().setValue("yem_initoccupancy", hashMap.get("yem_initoccupancy"));
            this.getModel().setValue("yem_initcollectionamt", hashMap.get("yem_initcollectionamt"));
            this.getModel().setValue("yem_otherbankrate", hashMap.get("yem_otherbankrate"));
            this.getModel().setValue("yem_confirmedrisk", hashMap.get("yem_confirmedrisk"));
            this.getModel().setValue("yem_bankcountry", hashMap.get("yem_bankcountry"));
            this.getModel().setValue("yem_swiftcode", hashMap.get("yem_swiftcode"));

            putAttachmentData((Map < String, Object > ) returnData, this.getModel(), this.getView());

            this.getView().invokeOperation("save");
            this.getView().invokeOperation("refresh");

        }
    }

    public void putAttachmentData(Map < String, Object > attachInfor, IDataModel modal, IFormView view)
    {
        String entityId = view.getEntityId();
        if(attachInfor != null)
        {
            List< Map < String, Object >> retData = (List < Map < String, Object >> ) attachInfor.get("attach");
            DynamicObject dataEntity = modal.getDataEntity(true);
            // ...
            if(retData != null && !retData.isEmpty())
            {
                for(Map < String, Object > map: retData)
                {
                    String url = (String) map.get("url");
                    String name = (String) map.get("name");
                    // 持久化附件到服务器
                    url = uploadTempfile(url, name);
                    map.put("url", url);
                    map.put("creator", UserServiceHelper.getCurrentUserId());
                    map.put("modifytime", new Date().getTime());
                }
                AttachmentServiceHelper.upload(entityId, dataEntity.getPkValue(), "attachmentpanel", retData);
            }
            SaveServiceHelper.save(new DynamicObject[]
                    {
                            dataEntity
                    });
        }
    }

    // 附件持久化
    public static String uploadTempfile(String url, String name)
    {
        TempFileCache cache = CacheFactory.getCommonCacheFactory().getTempFileCache();
        InputStream in = cache.getInputStream(url);
        FileService service = FileServiceFactory.getAttachmentFileService();
        RequestContext requestContext = RequestContext.get();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 生成文件路径-上传附件时远程服务器需要存储文件的位置
        String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(), requestContext.getAccountId(), uuid, name);
        FileItem fileItem = new FileItem(name, pathParam, in );
        // 上传附件到文件服务器
        return service.upload(fileItem);
    }
}
