package yem.wmc.ydn.formplugin.dynamic;

import com.alibaba.fastjson.JSONObject;
import kd.bos.algo.DataSet;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.Control;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.sdk.plugin.Plugin;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static yem.base.common.utils.DateUtil.formatDateHms;

/**
 * 航运跟踪
 *
 * @description:
 * @date: 2024/4/17
 * @auther: longh
 */
public class ViewShippingEdit extends AbstractFormPlugin implements Plugin {

    private String mmsi=null;
    private Viewshipping viewshipping=new Viewshipping();


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

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        String key = ((Control) evt.getSource()).getKey();
        switch (key) {
            case "yem_buttonap":
                String pageId = (String) this.getModel().getValue("yem_textfield");
                IFormView view = this.getView();
                IFormView childView = view.getView(pageId);
                childView.close();
                view.sendFormAction(childView);
                break;
            default:
                break;
        }
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        header();
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> cusMapone = showParameter.getCustomParams();
        Map<String, Object> cusMaptwo=showParameter.getCustomParams();
        showForm("yem_ydn_viewmap", "yem_flexpanelap31",cusMapone);//地图
        showForm("yem_ydn_trackinform", "yem_flexpanelap4",cusMaptwo);//航运跟踪
        updateentryentity();
    }
    private void updateentryentity() {
        QFilter bugfilter = new QFilter("yem_mmsi", QCP.equals, mmsi);
        DataSet dataSet = QueryServiceHelper.queryDataSet(ViewShippingEdit.class.getName(), "yem_ydn_shipdocking", "yem_ydn_shipdocking_gk.yem_portnamecn as yem_portnamecn,yem_ydn_shipdocking_gk.yem_ata as yem_ata," +
                        "yem_ydn_shipdocking_gk.yem_atd as yem_atd,yem_ydn_shipdocking_gk.yem_stayinport as yem_stayinport" +
                        ",yem_ydn_shipdocking_gk.yem_countrycn as yem_countrycn",
                new QFilter[]{bugfilter},"").distinct().orderBy(new String[]{"yem_ata desc"});

        DynamicObjectCollection objects = ORM.create().toPlainDynamicObjectCollection(dataSet);
        this.getModel().deleteEntryData("yem_entryentity");
        for (DynamicObject shipdockings: objects) { //单据遍历
            int newEntryRow = this.getModel().createNewEntryRow("yem_entryentity");
            this.getModel().setValue("yem_portname_cn",shipdockings.getString("yem_portnamecn"),newEntryRow);
            this.getModel().setValue("yem_ata",shipdockings.getString("yem_ata"),newEntryRow);//到达时间
            this.getModel().setValue("yem_atd",shipdockings.getString("yem_atd"),newEntryRow);//离泊时间
            String apartTime = getApartTime(shipdockings.getString("yem_ata"), shipdockings.getString("yem_atd"));
            this.getModel().setValue("yem_stayinport",apartTime,newEntryRow);
            this.getModel().setValue("yem_countrycn",shipdockings.getString("yem_countrycn"),newEntryRow);
        }
    }

    /**
     * 获取 到达和离岗之间的时间
     * @param ata //到达时间
     * @param atd //离泊时间
     * @return
     */
    public String getApartTime(String ata,String atd) {
        if (ata ==null|| atd ==null || ata.isEmpty() || atd.isEmpty()){
            return "";
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long ataTime = sdf.parse(ata).getTime();
            long atdTime = sdf.parse(atd).getTime();
            String hour = (atdTime - ataTime) / (60 * 60 * 1000) + "h";//小时
            String minute =  ((atdTime - ataTime)/(1000*60)%60)+ "m";//分
            return hour +minute;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    private void header() {
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> cusMap = showParameter.getCustomParams();
        JSONObject data = (JSONObject) cusMap.get("data");
        viewshipping = JSONObject.toJavaObject(data, Viewshipping.class);
        this.getModel().setValue("yem_contractnumber",viewshipping.getcontractnumber());
        this.getModel().setValue("yem_custorsup",viewshipping.getcustorsup());
        this.getModel().setValue("yem_shipmentarrival",viewshipping.getshipmentarrival());
        this.getModel().setValue("yem_blno",viewshipping.getblno());
        this.getModel().setValue("yem_blnos",viewshipping.getblno());
        this.getModel().setValue("yem_shipname",viewshipping.getshipname());
        this.getModel().setValue("yem_dataupdatetime",viewshipping.getdataupdatetime());
        this.getModel().setValue("yem_pol",viewshipping.getpol());
        this.getModel().setValue("yem_poldate",viewshipping.getpoldate());//启运时间
        this.getModel().setValue("yem_dtp",viewshipping.getdtp()); //到港时间
        this.getModel().setValue("yem_dtpdate",viewshipping.getdtpdate());
        this.getModel().setValue("yem_mmsi",viewshipping.getMMSI());
        mmsi=viewshipping.getMMSI();
    }

    private void showForm(String formkey, String targetKey,Map<String, Object> cusMap) {
        IFormView view = this.getView();
        FormShowParameter showParameter = new FormShowParameter();
        showParameter.setStatus(OperationStatus.EDIT);
        showParameter.getOpenStyle().setShowType(ShowType.InContainer);
        showParameter.getOpenStyle().setTargetKey(targetKey);
        showParameter.setSendToClient(true);
        showParameter.setCustomParams(cusMap);
        showParameter.setFormId(formkey);
        view.showForm(showParameter);
    }

}