package yem.wmc.ydn.formplugin.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.form.plugin.IFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import yem.wmc.ydn.formplugin.dynamic.Viewshipping;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lipan
 * @date 2024/4/26 17:23
 * @className YdnBseClass  提单
 * @description
 */
public class YdnBseClass extends AbstractFormPlugin {
    public static final String YEM_YDN_DATAREGISTRATION1 = "yem_ydn_dataregistration";
    private final String YEM_YDN_DATAREGISTRATION = YEM_YDN_DATAREGISTRATION1;//数据注册表

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String key = e.getOperateKey();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        String billName = dataEntity.getDataEntityType().getName();
        if ("viewshipping".equals(key)) {
            if(!dataEntity.containsProperty("yem_mmsi")){
                this.getView().showErrorNotification("此单据不包含MMSI号字段或者MMSI号标识不正确");
                return;
            }
            String yemMmsi = dataEntity.getString("yem_mmsi");
            if (!yemMmsi.isEmpty()){
                // 查询数据注册表，根据数据注册表，给实体赋值
                QFilter qFilter = new QFilter("yem_buttonname", QCP.equals, key);
                qFilter.and(new QFilter("yem_requirebill", QCP.equals, billName));
                qFilter.and(new QFilter("yem_targetbill", QCP.equals, "yem_ydn_viewshipping"));//航运跟踪
                DynamicObject registerBill = BusinessDataServiceHelper
                        .loadSingle(YEM_YDN_DATAREGISTRATION, "yem_colsmap.yem_billcol,yem_colsmap.yem_billcolno,yem_colsmap.yem_targebillcol,yem_colsmap.yem_targebillcolno", new QFilter[]{qFilter});
                if (registerBill == null) {
                    this.getView().showErrorNotification("没有找到符合条件的数据注册表");
                    return;
                }
                //获取到数据注册表上要替换的标识
                DynamicObjectCollection yemColsmap = registerBill.getDynamicObjectCollection("yem_colsmap");
                HashMap<String, String> map = new HashMap<>();
                for (DynamicObject rowDO : yemColsmap) {
                    String yemBillcolno = rowDO.getString("yem_billcolno");//来源字段标识
                    String yemTargebillcolno = rowDO.getString("yem_targebillcolno");//目标字段标识
                    if (!dataEntity.containsProperty(yemBillcolno) || yemTargebillcolno.isEmpty() || yemBillcolno.isEmpty()) {
                        continue;
                    }
                    map.put(yemBillcolno, yemTargebillcolno);
                }
                HashMap<String, String> differenceMap = new HashMap<>();
                for (String str : map.keySet()) {
                    if (!str.equals(map.get(str))) {
                        differenceMap.put(str, map.get(str));
                    }
                }
                DynamicObject bill = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), billName);//存储相同标识字段
                HashMap<String, Object> vaueMap = new HashMap<>();//存储值的map
                for (String str : map.keySet()) {
                    vaueMap.put(str, bill.get(str));
                }
                for (String str : differenceMap.keySet()) {//存储目标单和源单表不一致字段值
                    Object value = bill.get(str);
                    vaueMap.put(differenceMap.get(str), value);
                }

                //使用反射根据类属性自动赋值
                String path = "yem.wmc.ydn.formplugin.dynamic.Viewshipping";
                Viewshipping data = null;
                Class clazz = null;
                try {
                    clazz = Class.forName(path);
                    Field[] declaredFields = clazz.getDeclaredFields();// 获取所有的属性
                    data = (Viewshipping) clazz.newInstance();
                    for (Field declaredField : declaredFields) {
                        declaredField.setAccessible(true);//设置可以直接访问
                        String name = declaredField.getName();
                        name = "yem_"+ name;
                        if (vaueMap.containsKey(name)) {
                            Object Valuename = vaueMap.get(name);
                            if (Valuename instanceof String) {
                                declaredField.set(data, Valuename);
                            } else if (Valuename instanceof DynamicObject) {
                                DynamicObject dy = (DynamicObject) Valuename;
                                declaredField.set(data, dy.getString("name"));
                            } else if (Valuename instanceof Date) {
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                String format = simpleDateFormat.format(Valuename);
                                declaredField.set(data, format);
                            }
                        }
                    }
                } catch (IllegalAccessException ex) {
                    throw new RuntimeException(ex);
                } catch (InstantiationException | ClassNotFoundException ex) {
                    throw new RuntimeException(ex);
                }
                FormShowParameter showParameter = new FormShowParameter();
                showParameter.setFormId("yem_ydn_viewshipping");
                Map<String, Object> entryInfo = new HashMap<String, Object>();
                entryInfo.put("data", data);
                showParameter.setCustomParams(entryInfo);

                showParameter.setCloseCallBack(new CloseCallBack((IFormPlugin) this, "baritemap"));
                showParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                this.getView().showForm(showParameter);
            }else { //MMSI号 为空
                String yemShipname = dataEntity.getString("yem_shipname");
                if (yemShipname.isEmpty()){
                    this.getView().showTipNotification("船名为空,无法搜索MMSI号");
                    return;
                }
                FormShowParameter showParameter = new FormShowParameter();
                showParameter.setFormId("yem_ydn_queryshipdy");
                showParameter.setCustomParam("shipname",yemShipname);
                showParameter.setCloseCallBack(new CloseCallBack((IFormPlugin) this, "queryshipdy"));
                showParameter.getOpenStyle().setShowType(ShowType.Modal);
                this.getView().showForm(showParameter);
            }
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String key = e.getActionId();
        Object returnData = e.getReturnData();
        if (key.equals("queryshipdy") && returnData != null){
            this.getModel().setValue("yem_mmsi",returnData);
            DynamicObject dataEntity = this.getModel().getDataEntity(true);
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            this.getView().invokeOperation("viewshipping");
        }
    }
}
