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

import com.yem.wm.es.Util.TotalUtil;
import com.yem.wm.utils.CalendarUtils;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.operate.OperateOptionConst;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.plugin.IFormPlugin;
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.SaveServiceHelper;

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

/**
 * @author zhouc
 * @date 2023/12/30 22:10
 * @className StorageTransEdit_wl
 * @description 订舱通知单_订舱委托表单插件
 */
public class StorageTransEdit_wl extends AbstractBillPlugIn {
    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        String operateKey = e.getOperateKey();
        if ("backfillbill".equals(operateKey)) {
            DynamicObject dataEntity = this.getModel().getDataEntity();
            Set<String> set = new HashSet<>();
            dataEntity.getDynamicObjectCollection("yem_es_materialinfo").forEach(
                    dynamicObject ->
                    {
                        String contractnum = dynamicObject.getString("yem_contractnumbers_m");
                        set.add(contractnum);
                    }
            );
            Set<Boolean> isCreditContract = new HashSet<>();
            for (String salesOrderNum : set) {
                DynamicObject salesOrder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder"
                        , "id, billno, yem_issinosurecon"
                        , new QFilter[]{new QFilter("billno", QCP.equals, salesOrderNum)});
                isCreditContract.add(salesOrder.getBoolean("yem_issinosurecon"));
            }
            if (isCreditContract.contains(true)) {
                DynamicObject customer = dataEntity.getDynamicObject("yem_customer");
                DynamicObject method = TotalUtil.getSettlementMethod(dataEntity);
                DynamicObject company = dataEntity.getDynamicObject("yem_company.yem_erporg");
                String swiftCode = TotalUtil.getSwiftCode(dataEntity);
                DynamicObject csrCreditLine = TotalUtil.getCsrCreditLine(customer, method, company, swiftCode);
                if (csrCreditLine != null) {
                    boolean yem_changing = csrCreditLine.getBoolean("yem_changing");
                    boolean yem_effective = csrCreditLine.getBoolean("yem_effective");
                    String billno = csrCreditLine.getString("billno");
                    if (!yem_changing) {
                        FormShowParameter showParameter = new FormShowParameter();
                        showParameter.setFormId("yem_backfillbill");
                        String id = dataEntity.getString("id");
                        showParameter.getCustomParams().put("id", id);
                        showParameter.getCustomParams().put("billno", billno);
                        showParameter.setCloseCallBack(new CloseCallBack((IFormPlugin) this, "backfillbill"));
                        showParameter.getOpenStyle().setShowType(ShowType.Modal);
                        this.getView().showForm(showParameter);
                    } else {
                        this.getView().showErrorNotification("获取到客户信保额度申请【" + billno + "】正在变更中，请稍后重试！");
                    }
                } else {
                    this.getView().showErrorNotification("未获取到满足条件的信保额度申请单，请稍后重试！");
                }
            } else {
                FormShowParameter showParameter = new FormShowParameter();
                showParameter.setFormId("yem_backfillbill");
                showParameter.setCloseCallBack(new CloseCallBack((IFormPlugin) this, "backfillbill"));
                showParameter.getOpenStyle().setShowType(ShowType.Modal);
                this.getView().showForm(showParameter);
            }
        }
        if ("bookingspace".equals(operateKey)) {
//            this.operationResult.setSuccess(true);
//
            OperateOption option = OperateOption.create();
            option.setVariableValue(OperateOptionConst.ISSHOWMESSAGE, String.valueOf(false));
            this.getView().invokeOperation("save",option);
//            OperationResult saveOperate = OperationServiceHelper.executeOperate("save", this.getView().getEntityId(), new DynamicObject[]{this.getModel().getDataEntity(true)}, YEM.getOptionNoMsg());
//            if (saveOperate.isSuccess()) {
//                saveOperate.setSuccess(false);
//            }
//            SaveServiceHelper.save(new DynamicObject[]{this.getModel().getDataEntity(true)});
            SaveServiceHelper.update(this.getModel().getDataEntity(true));
            boolean boonle = true;
            int i = 1;
            String string = "";
            Date yemInitforecdate = (Date) this.getModel().getValue("yem_initforecdate");
            DynamicObject yemTransportstyle = (DynamicObject) this.getModel().getValue("yem_transportstyle");//运输方式
            String yemNoticeno = (String) this.getModel().getValue("yem_noticeno");//主题单号
            String yemHousebillofladnum = (String) this.getModel().getValue("yem_housebillofladnum");//分提单号
            String yemShipname = (String) this.getModel().getValue("yem_shipname");//船名
            String yemVoyageno = (String) this.getModel().getValue("yem_voyageno");//航次
            Date yemCutdate = (Date) this.getModel().getValue("yem_cutdate");//截单日期
            Date yemPortinterception = (Date) this.getModel().getValue("yem_portinterception");//截港日期
            DynamicObject yemCfscompnay = (DynamicObject) this.getModel().getValue("yem_cfscompnay");//货代公司
            Date yemEtddate = (Date) this.getModel().getValue("yem_etddate");//ETD(离港日期）
            DynamicObject yemSctcompnayname = (DynamicObject) this.getModel().getValue("yem_sctcompnayname");//船公司
            String yemStation = (String) this.getModel().getValue("yem_stationtext");//场站
            List<Map<String, Object>> atts = AttachmentServiceHelper.getAttachments("yem_es_storagetrans_wl",
                    this.getModel().getValue("id"), "yem_attachmentpanel");
            if (yemTransportstyle != null) {
                String number = yemTransportstyle.getString("number");
                if ("YSFS-0004".equals(number) || "YSFS-0006".equals(number) || "YSFS-0008".equals(number) ||
                        "YSFS-0010".equals(number) || "YSFS-1003".equals(number) || "YSFS-1004".equals(number)) {
                    if ("".equals(yemNoticeno) && "".equals(yemHousebillofladnum)) {
                        string = string + i + ". 主,分提单号为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemInitforecdate == null) {
                        string = string + i + ". 预计船期为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (atts.isEmpty()) {
                        string = string + i + ". 物流附件面板为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if ("".equals(yemShipname)) {
                        string = string + i + ". 船名为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if ("".equals(yemVoyageno)) {
                        string = string + i + ". 航次为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemCutdate == null) {
                        string = string + i + ". 截单日期为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemPortinterception == null) {
                        string = string + i + ". 截港日期为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (null == yemCfscompnay) {
                        string = string + i + ". 货代公司为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemEtddate == null) {
                        string = string + i + ". ETD(离港日期）为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemSctcompnayname == null) {
                        string = string + i + ". 船公司为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemStation == null) {
                        string = string + i + ". 场站为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                }
                if ("YSFS-0005".equals(number) || "YSFS-0011".equals(number)) {
                    if (yemEtddate == null) {
                        string = string + i + ". ETD(离港日期）为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (atts.isEmpty()) {
                        string = string + i + ". 物流附件面板为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemInitforecdate == null) {
                        string = string + i + ". 预计船期为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (null == yemCfscompnay) {
                        string = string + i + ". 货代公司为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                }
                if ("YSFS-1001".equals(number) || "YSFS-1002".equals(number)) {
                    if (null == yemCfscompnay) {
                        string = string + i + ". 货代公司为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemInitforecdate == null) {
                        string = string + i + ". 预计船期为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                }
                if ("YSFS-1002".equals(number)){
                    if (atts.isEmpty()) {
                        string = string + i + ". 物流附件面板为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                }
                if ("YSFS-0007".equals(number)) {
                    if ("".equals(yemNoticeno) && "".equals(yemHousebillofladnum)) {
                        string = string + i + ". 主,分提单号为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (atts.isEmpty()) {
                        string = string + i + ". 物流附件面板为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemInitforecdate == null) {
                        string = string + i + ". 预计船期为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if ("".equals(yemShipname)) {
                        string = string + i + ". 船名为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if ("".equals(yemVoyageno)) {
                        string = string + i + ". 航次为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemCutdate == null) {
                        string = string + i + ". 截单日期为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemPortinterception == null) {
                        string = string + i + ". 截港日期为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (null == yemCfscompnay) {
                        string = string + i + ". 货代公司为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemEtddate == null) {
                        string = string + i + ". ETD(离港日期）为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemSctcompnayname == null) {
                        string = string + i + ". 船公司为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemStation == null) {
                        string = string + i + ". 场站为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                }
                if ("YSFS002_SYS".equals(number)) {
                    if ("".equals(yemNoticeno) && "".equals(yemHousebillofladnum)) {
                        string = string + i + ". 主,分提单号为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (atts.isEmpty()) {
                        string = string + i + ". 物流附件面板为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemInitforecdate == null) {
                        string = string + i + ". 预计船期为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemCutdate == null) {
                        string = string + i + ". 截单日期为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemPortinterception == null) {
                        string = string + i + ". 截港日期为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (null == yemCfscompnay) {
                        string = string + i + ". 货代公司为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                    if (yemEtddate == null) {
                        string = string + i + ". ETD(离港日期）为空，请稍后重试！\n";
                        boonle = false;
                        i++;
                    }
                }
            }
            if (boonle) {
                this.getModel().setValue("yem_bookingspacestatus", "B");
                IDataModel model = this.getModel();
                DynamicObject dataEntity = model.getDataEntity(true);
                SaveServiceHelper.save(new DynamicObject[]{dataEntity});
                this.getView().invokeOperation("refresh");
                this.getView().showSuccessNotification("订舱完成成功");
            } else {
                this.getView().showErrorNotification(string);
            }
        }
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        DynamicObject dataEntity = model.getDataEntity(true);
        if ("custom_save".equals(operateKey)) {
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            view.invokeOperation("refresh");
        }
        if ("cancel_finish_status".equals(operateKey)) {
            dataEntity.set("yem_bookingspacestatus", "A");
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            view.invokeOperation("refresh");
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        IDataModel model = this.getModel();
        Object returnData = e.getReturnData();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if (actionId.equals("backfillbill")) {
            if (returnData != null) {
                Map<String, Object> map = (Map) returnData;
                String yem_billno = dataEntity.getString("yem_billno");
                DynamicObject yem_customer = dataEntity.getDynamicObject("yem_customer");
                model.setValue("yem_encasemedate", map.get("yem_encasemedate"));//预计装箱时间
                model.setValue("yem_cfscompnay", map.get("yem_cfscompnay"));//货代公司
                model.setValue("yem_custombrokers", map.get("yem_custombrokers"));//报关行
                model.setValue("yem_bhd_combo", map.get("yem_bhd_combo"));//运费承付
//                model.setValue("yem_boxtext", map.get("yem_boxtext"));//箱型箱量
//                model.setValue("yem_sumpieces", map.get("yem_sumpieces"));//总件数
//                model.setValue("yem_boxgwsum", map.get("yem_boxgwsum"));//总毛重
//                model.setValue("yem_boxnwsum", map.get("yem_boxnwsum"));//总净重
//                model.setValue("yem_boxvolsum", map.get("yem_boxvolsum"));//总体积

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

                model.setValue("yem_shipdate", map.get("yem_shipdate"));//发运日期
                model.setValue("yem_actualtdeclaredate", map.get("yem_actualtdeclaredate"));//实际报关日期
                model.setValue("yem_expdelaration", map.get("yem_expdelaration"));//出口报关单号
                model.setValue("yem_initforecdate", map.get("yem_initforecdate"));//预计船期
                model.setValue("yem_etddate", map.get("yem_etddate"));//ETD(预计离港日期
                model.setValue("yem_etadate", map.get("yem_etadate"));//ETA(预计到达日期)
                model.setValue("yem_cutdate", map.get("yem_cutdate"));//截单日期
                model.setValue("yem_portinterception", map.get("yem_portinterception"));//截港日期
                model.setValue("yem_containerfreedays", map.get("yem_creditbackfill"));//免箱天数
                model.setValue("yem_tremark", map.get("yem_tremark"));//备注

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


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


                uptddate(yem_billno, map);
                SaveServiceHelper.save(new DynamicObject[]{dataEntity});

                updatePackingForm();

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

            QFilter qFilter = new QFilter("billno", QCP.equals, dataEntity.getString("yem_billno"));
            DynamicObject single = BusinessDataServiceHelper.loadSingle("yem_es_storagetrans", qFilter.toArray());
            if (single != null) {
                DynamicObjectCollection collection = single.getDynamicObjectCollection("yem_creditdetail");
                for (DynamicObject dynamicObject : collection) {
                    Date receivableDate = dynamicObject.getDate("yem_paydate1");
                    if (receivableDate != null) {
                        dynamicObject.set("yem_countpayback", CalendarUtils.calcPayBackCount(receivableDate));
                    }
                    // 投保回款金额美元（实际收汇金额）
                    BigDecimal actualsinkamt_cd = dynamicObject.getBigDecimal("yem_actualsinkamt_cd");
                    // 应收款金额1
                    BigDecimal paymentamt1Cd = dynamicObject.getBigDecimal("yem_paymentamt1_cd");
                    BigDecimal amountowed = actualsinkamt_cd.subtract(paymentamt1Cd);
                    dynamicObject.set("yem_amountowed", amountowed);
                }
                SaveServiceHelper.save(new DynamicObject[]{single});
                this.getView().invokeOperation("refresh");
            }
        }
    }

    /**
     * 将主提单号 分提单号更新到下游装箱单
     */
    private void updatePackingForm() {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity();
        Long pkValue = (Long) dataEntity.getPkValue();
        if (YEM.isEmpty(pkValue)) return;
        String noticeno = (String) model.getValue("yem_noticeno"); // 主提单号
        String housebillofladnum = (String) model.getValue("yem_housebillofladnum"); // 分提单号
        QFilter qFilter = new QFilter("yem_sourcebillid", QCP.equals, pkValue);
        DynamicObject[] load = BusinessDataServiceHelper.load("yem_im_encasement", "id, billno" +
                ", yem_mainladingno, yem_divladingno", qFilter.toArray());
        for (DynamicObject dynamicObject : load) {
            dynamicObject.set("yem_mainladingno", noticeno);
            dynamicObject.set("yem_divladingno", housebillofladnum);
            SaveServiceHelper.save(new DynamicObject[]{dynamicObject});
        }
    }

    public void uptddate(String yem_billno, Map<String, Object> map) {
        /**
         * 订舱通知书
         */
        DynamicObject yem_es_storagetrans = BusinessDataServiceHelper.loadSingle("yem_es_storagetrans", "id",
                new QFilter[]{new QFilter("billno", QCP.equals, yem_billno)});
        if (yem_es_storagetrans != null) {
            long id = yem_es_storagetrans.getLong("id");
            DynamicObject storagetrans = BusinessDataServiceHelper.loadSingle(id, "yem_es_storagetrans");
            if (storagetrans != null) {
                storagetrans.set("yem_encasemedate", map.get("yem_encasemedate"));//预计装箱时间
                storagetrans.set("yem_cfscompnay", map.get("yem_cfscompnay"));//货代公司
                storagetrans.set("yem_custombrokers", map.get("yem_custombrokers"));//报关行
                storagetrans.set("yem_bhd_combo", map.get("yem_bhd_combo"));//运费承付
                storagetrans.set("yem_boxtexts", map.get("yem_boxtext"));//箱型箱量
                storagetrans.set("yem_sumpiece", map.get("yem_sumpieces"));//总件数
                storagetrans.set("yem_boxgwsum", map.get("yem_boxgwsum"));//总毛重
                storagetrans.set("yem_boxnwsum", map.get("yem_boxnwsum"));//总净重
                storagetrans.set("yem_boxvolsum", map.get("yem_boxvolsum"));//总体积
                storagetrans.set("yem_shipdate", map.get("yem_shipdate"));//发运日期
                storagetrans.set("yem_actualtdeclaredate", map.get("yem_actualtdeclaredate"));//实际报关日期
                storagetrans.set("yem_expdelaration", map.get("yem_expdelaration"));//出口报关单号

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

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

                SaveServiceHelper.save(new DynamicObject[]{storagetrans});
            }
        }
    }
}
