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

import com.yem.ensign.common.CommonUtils;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.IFormView;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.control.AttachmentPanel;
import kd.bos.form.control.Control;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
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.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;

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

/**
 * @author zhouc
 * @date 2023/12/30 22:14
 * @className BackFillbillEdit
 * @description 提单回填动态表单插件
 */
public class BackFillbillEdit extends AbstractFormPlugin {
    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        IFormView parentView = view.getParentView();
        IDataModel parentModel = parentView.getModel();
        DynamicObject parentdataEntity = parentModel.getDataEntity(true);
        model.setValue("yem_id", parentModel.getValue("id"));//
        model.setValue("yem_billno", parentModel.getValue("yem_billno"));//

        model.setValue("yem_encasemedate", parentModel.getValue("yem_encasemedate"));//预计装箱时间
        model.setValue("yem_cfscompnay", parentModel.getValue("yem_cfscompnay"));//货代公司
        model.setValue("yem_custombrokers", parentModel.getValue("yem_custombrokers"));//报关行
        model.setValue("yem_bhd_combo", parentModel.getValue("yem_bhd_combo"));//运费承付
        model.setValue("yem_boxtext", parentModel.getValue("yem_boxvolume1"));//箱型箱量
//        model.setValue("yem_sumpieces", parentModel.getValue("yem_sumpieces"));//总件数
//        model.setValue("yem_boxgwsum", parentModel.getValue("yem_boxgwsum"));//总毛重
//        model.setValue("yem_boxnwsum", parentModel.getValue("yem_boxnwsum"));//总净重
//        model.setValue("yem_boxvolsum", parentModel.getValue("yem_boxvolsum"));//总体积

        model.setValue("yem_sumunits", parentModel.getValue("yem_sumunits"));//总件数
        model.setValue("yem_sumweight", parentModel.getValue("yem_sumweight"));//总重量
        model.setValue("yem_sumcube", parentModel.getValue("yem_sumcube"));//总立方

        model.setValue("yem_shipdate", parentModel.getValue("yem_shipdate"));//发运日期
        model.setValue("yem_actualtdeclaredate", parentModel.getValue("yem_actualtdeclaredate"));//实际报关日期
        model.setValue("yem_expdelaration", parentModel.getValue("yem_expdelaration"));//出口报关单号

        model.setValue("yem_initforecdate", parentModel.getValue("yem_initforecdate"));//预计船期
        model.setValue("yem_etddate", parentModel.getValue("yem_etddate"));//ETD(预计离港日期
        model.setValue("yem_etadate", parentModel.getValue("yem_etadate"));//ETA(预计到达日期)
        model.setValue("yem_cutdate", parentModel.getValue("yem_cutdate"));//截单日期
        model.setValue("yem_portinterception", parentModel.getValue("yem_portinterception"));//截港日期
        model.setValue("yem_creditbackfill", parentModel.getValue("yem_containerfreedays"));//免箱天数
        model.setValue("yem_tremark", parentModel.getValue("yem_tremark"));//备注

        model.setValue("yem_sctcompnayname", parentModel.getValue("yem_sctcompnayname"));//船公司
        model.setValue("yem_stationtext", parentModel.getValue("yem_stationtext"));//场站
        model.setValue("yem_shipname", parentModel.getValue("yem_shipname"));//船名
        model.setValue("yem_voyageno", parentModel.getValue("yem_voyageno"));//航次
        model.setValue("yem_noticeno", parentModel.getValue("yem_noticeno"));//主提单号
        model.setValue("yem_housebillofladnum", parentModel.getValue("yem_housebillofladnum"));//分提单号
        model.setValue("yem_billqtys", parentModel.getValue("yem_billqtys"));//提单份数
        model.setValue("yem_linkman", parentModel.getValue("yem_linkman"));//联系人
        model.setValue("yem_linkmantel", parentModel.getValue("yem_linkmantel"));//联系电话
        model.setValue("yem_tddate", parentModel.getValue("yem_tddate"));//提单日期
        model.setValue("yem_saildate", parentModel.getValue("yem_saildate"));//实际开船日期
        model.setValue("yem_arrivaldate", parentModel.getValue("yem_arrivaldate"));//实际到港日

        model.setValue("yem_priceitem", parentModel.getValue("yem_priceitem"));//价格条款
        model.setValue("yem_currencyfreight", parentModel.getValue("yem_currencyfreight"));//海运费币别
        model.setValue("yem_freightrate", parentModel.getValue("yem_freightrate"));//海运费汇率
        model.setValue("yem_freightamt1", parentModel.getValue("yem_freightamt1"));//海运费（原币）
        model.setValue("yem_freightamtbase", parentModel.getValue("yem_freightamtbase"));//海运费（本位币）
        model.setValue("yem_freightamtend", parentModel.getValue("yem_freightamtend"));//海运费（结算币别）

        model.setValue("yem_currencybase", parentModel.getValue("yem_currencybase"));//本位币
        model.setValue("yem_currency", parentModel.getValue("yem_currency"));//结算币别

        model.setValue("yem_exrate", parentModel.getValue("yem_exrate"));//财务信息 汇率
        List<Map<String, Object>> atts = AttachmentServiceHelper.getAttachments("yem_es_storagetrans_wl", parentModel.getValue("id"), "yem_attachmentpanel");
        if (atts.size() > 0) {
            AttachmentPanel attachmentPanel = this.getView().getControl("yem_attachmentpanelap");
            attachmentPanel.upload(atts);
        }

    }

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


    @Override
    public void confirmCallBack(MessageBoxClosedEvent e) {
        super.confirmCallBack(e);
        String callBackId = e.getCallBackId();
        if ("btnok".equals(callBackId)) {
            if (MessageBoxResult.Yes.equals(e.getResult())) {
                btnOk();
            }
        }
    }

    @Override
    public void click(EventObject e) {
        super.click(e);
        Control control = (Control) e.getSource();
        String key = control.getKey();
        if ("btnok".equals(key)) {
            IDataModel model = this.getModel();
            BigDecimal yemCreditbackfill = (BigDecimal) model.getValue("yem_creditbackfill");
            if (BigDecimal.ZERO.compareTo(yemCreditbackfill) == 0) {
                this.getView().showTipNotification("免箱天数为空，请填写后提交   ！！！");
                return;
            }
            DynamicObject priceitem = (DynamicObject) model.getValue("yem_priceitem");
            String name = priceitem.getString("name");
            StringBuilder sb = new StringBuilder();
            if ("CIF".equals(name) || "CFR".equals(name)) {
                DynamicObject currencyfreight = (DynamicObject) model.getValue("yem_currencyfreight");
                BigDecimal freightrate = (BigDecimal) model.getValue("yem_freightrate");
                BigDecimal freightamt1 = (BigDecimal) model.getValue("yem_freightamt1");
                BigDecimal freightamtbase = (BigDecimal) model.getValue("yem_freightamtbase");
                BigDecimal freightamtend = (BigDecimal) model.getValue("yem_freightamtend");
                if (YEM.isEmpty(currencyfreight)) {
                    sb.append("海运费币别，");
                }
                if (YEM.isEmpty(freightrate)) {
                    sb.append("海运费汇率，");
                }
                if (YEM.isEmpty(freightamt1)) {
                    sb.append("海运费（原币），");
                }
                if (YEM.isEmpty(freightamtbase)) {
                    sb.append("海运费（本位币），");
                }
                if (YEM.isEmpty(freightamtend)) {
                    sb.append("海运费（结算币别），");
                }
                if (sb.length() > 0) {
                    sb.deleteCharAt(sb.length() - 1);
                    sb.append("未填写，请确认是否继续？");
                    ConfirmCallBackListener confirmCallBackListener = new ConfirmCallBackListener("btnok", this);
                    this.getView().showConfirm(sb.toString(), MessageBoxOptions.YesNo, confirmCallBackListener);
                } else {
                    btnOk();
                }
            } else {
                btnOk();
            }
        }
    }

    private void btnOk() {
        IDataModel model = this.getModel();
        Map map = new HashMap();
        map.put("yem_encasemedate", model.getValue("yem_encasemedate"));//预计装箱时间
        map.put("yem_cfscompnay", model.getValue("yem_cfscompnay"));//货代公司
        map.put("yem_custombrokers", model.getValue("yem_custombrokers"));//报关行
        map.put("yem_bhd_combo", model.getValue("yem_bhd_combo"));//运费承付
        map.put("yem_boxtext", model.getValue("yem_boxtext"));//箱型箱量
//        map.put("yem_sumpieces", model.getValue("yem_sumpieces"));//总件数
//        map.put("yem_boxgwsum", model.getValue("yem_boxgwsum"));//总毛重
//        map.put("yem_boxnwsum", model.getValue("yem_boxnwsum"));//总净重
//        map.put("yem_boxvolsum", model.getValue("yem_boxvolsum"));//总体积
        map.put("yem_sumunits", model.getValue("yem_sumunits"));//总件数
        map.put("yem_sumweight", model.getValue("yem_sumweight"));//总重量
        map.put("yem_sumcube", model.getValue("yem_sumcube"));//总立方


        map.put("yem_shipdate", model.getValue("yem_shipdate"));//发运日期
        map.put("yem_creditbackfill", model.getValue("yem_creditbackfill"));//免箱天数
        map.put("yem_tremark", model.getValue("yem_tremark"));//免箱天数

        map.put("yem_actualtdeclaredate", model.getValue("yem_actualtdeclaredate"));//实际报关日期
        map.put("yem_expdelaration", model.getValue("yem_expdelaration"));//出口报关单号

        map.put("yem_initforecdate", model.getValue("yem_initforecdate"));//预计船期
        map.put("yem_etddate", model.getValue("yem_etddate"));//ETD(预计离港日期
        map.put("yem_etadate", model.getValue("yem_etadate"));//ETA(预计到达日期)
        map.put("yem_cutdate", model.getValue("yem_cutdate"));//截单日期
        map.put("yem_portinterception", model.getValue("yem_portinterception"));//截港日期

        map.put("yem_sctcompnayname", model.getValue("yem_sctcompnayname"));//船公司
        map.put("yem_stationtext", model.getValue("yem_stationtext"));//场站
        map.put("yem_shipname", model.getValue("yem_shipname"));//船名
        map.put("yem_voyageno", model.getValue("yem_voyageno"));//航次
        map.put("yem_noticeno", model.getValue("yem_noticeno"));//主提单号
        map.put("yem_housebillofladnum", model.getValue("yem_housebillofladnum"));//分提单号
        map.put("yem_billqtys", model.getValue("yem_billqtys"));//提单份数
        map.put("yem_linkman", model.getValue("yem_linkman"));//联系人
        map.put("yem_linkmantel", model.getValue("yem_linkmantel"));//联系电话
        map.put("yem_tddate", model.getValue("yem_tddate"));//提单日期
        map.put("yem_saildate", model.getValue("yem_saildate"));//实际开船日期
        map.put("yem_arrivaldate", model.getValue("yem_arrivaldate"));//实际到港日

        map.put("yem_priceitem", model.getValue("yem_priceitem"));//价格条款
        map.put("yem_currencyfreight", model.getValue("yem_currencyfreight"));//海运费币别
        map.put("yem_freightrate", model.getValue("yem_freightrate"));//海运费汇率
        map.put("yem_freightamt1", model.getValue("yem_freightamt1"));//海运费（原币）
        map.put("yem_freightamtbase", model.getValue("yem_freightamtbase"));//海运费（本位币）
        map.put("yem_freightamtend", model.getValue("yem_freightamtend"));//海运费（结算币别）
        this.getView().returnDataToParent(map);
        AttachmentPanel attachmentPanel = this.getView().getControl("yem_attachmentpanelap");
        List<Map<String, Object>> attachmentData = attachmentPanel.getAttachmentData();
        deletefile("yem_es_storagetrans", "attachmentpanel");
        deletefile("yem_es_storagetrans_wl", "yem_attachmentpanel");
        effectVersion("yem_es_storagetrans", "attachmentpanel");
        effectVersion("yem_es_storagetrans_wl", "yem_attachmentpanel");
        this.getView().close();
    }


    public void deletefile(String formId, String attachkey) {
        IDataModel model = this.getModel();
        String yem_masterid = (String) model.getValue("yem_id");
        QFilter qFilter1 = new QFilter("finterid", QCP.equals, yem_masterid);
        qFilter1.and("fattachmentpanel", "=", attachkey);
        qFilter1.and("fbilltype", "=", formId);
        DynamicObject[] atts = BusinessDataServiceHelper.load("bos_attachment",
                "id,ffileid,fattachmentname,fattachmentsize",
                new QFilter[]{qFilter1});
        for (int i = 0; i < atts.length; i++) {
            DynamicObject att = atts[i];
            OperationResult delete = OperationServiceHelper.executeOperate("delete", "bos_attachment",
                    new Object[]{att.getLong("id")}, OperateOption.create());
            if (delete.isSuccess()) {

            }


        }
    }

    /**
     * 反写附件
     *
     * @param
     * @param
     */
    private void effectVersion(String formId, String attachkey) {
        IDataModel model = this.getModel();
        String yem_masterid = (String) model.getValue("yem_id");

        AttachmentPanel attachmentPanel = this.getView().getControl("yem_attachmentpanelap");
        List<Map<String, Object>> attachmentData = attachmentPanel.getAttachmentData();
        if (attachmentData.size() > 0) {
            if (yem_masterid.length() > 0) {
                DynamicObject yem_es_salesorder = BusinessDataServiceHelper.loadSingle(yem_masterid, formId);
                for (int i = 0; i < attachmentData.size(); i++) {
                    Map<String, Object> map = attachmentData.get(i);
                    Map uploadFileMap = new HashMap();
                    String name = (String) map.get("name");
                    uploadFileMap.put("entityNum", yem_es_salesorder.getDynamicObjectType().getName());
                    uploadFileMap.put("billPkId", yem_es_salesorder.getPkValue().toString());
                    uploadFileMap.put("lastModified", new Date().getTime());
                    uploadFileMap.put("name", name);
                    if (map.containsKey("relativeUrl")) {
                        uploadFileMap.put("url", map.get("relativeUrl"));
                    } else {
                        // 持久化附件到服务器
                        String url = (String) map.get("url");
                        if (url.contains("configKey=redis.serversForCache&id=tempfile")) {
                            url = CommonUtils.uploadTempFile(url, name);
                            uploadFileMap.put("url", url);
                        }
                    }
                    uploadFileMap.put("status", "success");
                    long time = new Date().getTime();
                    StringBuffer uid = new StringBuffer();
                    uid.append("rc-upload-");
                    uid.append(time);
                    uid.append("-");
                    uid.append("1");
                    uploadFileMap.put("uid", uid.toString());
                    uploadFileMap.put("size", map.get("size"));
                    uploadFileMap.put("creator", UserServiceHelper.getCurrentUserId());
                    List<Map<String, Object>> attachments = new ArrayList<>();
                    attachments.add(uploadFileMap);
                    AttachmentServiceHelper.upload(formId, yem_masterid, attachkey, attachments);
                    Object[] save = SaveServiceHelper.save(new DynamicObject[]{yem_es_salesorder});
                    if (save.length > 0) {

                    }
                }
            }
        }
    }

//    @Override
//    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
//        super.closedCallBack(closedCallBackEvent);
////        if ("kded_attachfileds".equals(closedCallBackEvent.getActionId())) {
//        if (closedCallBackEvent.getReturnData() != null) {
//            HashMap<String, List<Map<String, Object>>> hashMap = (HashMap<String, List<Map<String, Object>>>) closedCallBackEvent.getReturnData();
//            List<Map<String, Object>> retData = hashMap.get("attach");
//            if (retData != null && retData.size() > 0) {
//                AttachmentPanel panel = this.getControl("yem_attachmentpanel");
//                panel.upload(retData);
//                //刷新页面
////                this.getView().updateView("kdec_attachmentpanelap");
//            }
////            }
//        }
//    }

}
