package com.yem.em.dynamic;

import com.yem.wm.utils.StringUtils;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.bill.BillShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.events.RowClickEvent;
import kd.bos.form.control.events.RowClickEventListener;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.HyperLinkClickEvent;
import kd.bos.form.events.HyperLinkClickListener;
import kd.bos.form.operate.FormOperate;
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.QueryServiceHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhouc
 * @date 2023/10/23 15:49
 * @className ProductstreeDynamicEdit
 * @description 产品机型查询动态表单插件
 */
public class ProductstreeDynamicEdit extends AbstractFormPlugin implements RowClickEventListener, HyperLinkClickListener {
    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> customParas = showParameter.getCustomParams();
        DynamicObjectCollection yem_entryentity = dataEntity.getDynamicObjectCollection("yem_entryentity");
        yem_entryentity.clear();
        if(customParas.get("Tpye")==null){
            return;
        }
        if (customParas.get("Tpye").equals("searchap3")) {//订单号
            if (customParas.containsKey("yem_salesorderno")) {
                List<QFilter> qFilters = new ArrayList<>();
                String algoKey = this.getClass().getName();
                qFilters.add(new QFilter("yem_salesorderno", QCP.equals, customParas.get("yem_salesorderno")));
                String selectFields = "yem_model.number yem_modelno,yem_model.yem_products.number yem_products" +
                        ",yem_model.yem_productsgroup.name  yem_productsgroup,yem_dateofpurchase";
                DataSet dataSet = ORM.create().queryDataSet(algoKey, "yem_em_devicefiles", selectFields, qFilters.toArray(new QFilter[]{}));
                DataSet dataSetdis = dataSet.distinct();
                if (dataSetdis != null) {
                    for (Row data : dataSetdis) {
                        DynamicObject entryentity = yem_entryentity.addNew();
                        entryentity.set("yem_salesorderno", customParas.get("yem_salesorderno"));
                        entryentity.set("yem_resourceno", data.getString("yem_modelno"));
                        entryentity.set("yem_products", data.getString("yem_products"));
                        entryentity.set("yem_productsgroup", data.getString("yem_productsgroup"));
                        if (data.getString("yem_dateofpurchase") != null) {
                            Date yem_dateofpurchase = formatDate(data.getString("yem_dateofpurchase"), "yyyy-MM-dd");
                            entryentity.set("yem_dateofpurchase", yem_dateofpurchase);
                        }
                    }
                }
            }
        }
        if (customParas.get("Tpye").equals("searchap2")) {//零件
            if (customParas.containsKey("yem_salesorderno")) {
                List<QFilter> qFilters = new ArrayList<>();
                String algoKey = this.getClass().getName();
                //查询零件明细表 根据零件编码过滤
                qFilters.add(new QFilter("yem_pnumber", QCP.equals, customParas.get("yem_salesorderno")));
                qFilters.add(new QFilter("yem_basemodelib.number", QCP.is_notnull, null));
                String selectFields = "yem_basemodelib.number yem_basemodelib";
                DataSet dataSet = ORM.create().queryDataSet(algoKey, "yem_em_part", selectFields, qFilters.toArray(new QFilter[]{}));
                //查询设备档案  与 查询零件明细表DataSet通过资源号编码进行左关联
                String selectField1 = "yem_model.number yem_modelno,yem_model.yem_products.number yem_products" +
                        ",yem_model.yem_productsgroup.name  yem_productsgroup,yem_dateofpurchase,yem_salesorderno";
                DataSet dataSet1 = ORM.create().queryDataSet(algoKey, "yem_em_devicefiles", selectField1, null);
                DataSet dataSetdi11 = dataSet.leftJoin(dataSet1).on("yem_basemodelib", "yem_modelno")
                        .select(new String[]{"yem_basemodelib"},
                                new String[]{"yem_modelno", "yem_products", "yem_productsgroup", "yem_dateofpurchase", "yem_salesorderno"})
                        .finish();
                DataSet dataSetdis = dataSetdi11.distinct();
                if (dataSetdis != null) {
                    for (Row data : dataSetdis) {
                        if (data.get("yem_salesorderno") != null) {
                            DynamicObject entryentity = yem_entryentity.addNew();
                            entryentity.set("yem_salesorderno", data.get("yem_salesorderno"));
                            entryentity.set("yem_resourceno", data.getString("yem_modelno"));
                            entryentity.set("yem_products", data.getString("yem_products"));
                            entryentity.set("yem_productsgroup", data.getString("yem_productsgroup"));
                            if (data.getString("yem_dateofpurchase") != null) {
                                Date yem_dateofpurchase = formatDate(data.getString("yem_dateofpurchase"), "yyyy-MM-dd");
                                entryentity.set("yem_dateofpurchase", yem_dateofpurchase);
                            }
                        }
                    }
                }
            }
        }

        if(customParas.get("Tpye").equals("searchap4")){
            if (customParas.containsKey("yem_salesorderno")) {
                List<QFilter> qFilters = new ArrayList<>();
                String algoKey = this.getClass().getName();
                //查询零件明细表 根据零件编码过滤
                qFilters.add(new QFilter("yem_model.yem_products.number", QCP.equals, customParas.get("yem_salesorderno")));
                String selectField1 = "yem_model.number yem_modelno,yem_model.yem_products.number yem_products" +
                        ",yem_model.yem_productsgroup.name  yem_productsgroup,yem_dateofpurchase,yem_salesorderno";
                DataSet dataSetss = ORM.create().queryDataSet(algoKey, "yem_em_devicefiles", selectField1, qFilters.toArray(new QFilter[]{})).distinct();

                if (dataSetss != null) {
                    for (Row data : dataSetss) {
                        if (data.get("yem_salesorderno") != null) {
                            DynamicObject entryentity = yem_entryentity.addNew();
                            entryentity.set("yem_salesorderno", data.get("yem_salesorderno"));
                            entryentity.set("yem_resourceno", data.getString("yem_modelno"));
                            entryentity.set("yem_products", data.getString("yem_products"));
                            entryentity.set("yem_productsgroup", data.getString("yem_productsgroup"));
                            if (data.getString("yem_dateofpurchase") != null) {
                                Date yem_dateofpurchase = formatDate(data.getString("yem_dateofpurchase"), "yyyy-MM-dd");
                                entryentity.set("yem_dateofpurchase", yem_dateofpurchase);
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        EntryGrid entryGrid = this.getView().getControl("yem_entryentity");
        entryGrid.addRowClickListener(this);
        EntryGrid yem_entryentity1 = this.getView().getControl("yem_entryentity1");
        yem_entryentity1.addHyperClickListener(this);
    }

    @Override
    public void entryRowClick(RowClickEvent evt) {
        RowClickEventListener.super.entryRowClick(evt);
        EntryGrid entryGrid = (EntryGrid) evt.getSource();
        String key = entryGrid.getEntryKey();
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if (key.equals("yem_entryentity")) {
            int row = model.getEntryCurrentRowIndex("yem_entryentity");
            DynamicObjectCollection yem_entryentity = dataEntity.getDynamicObjectCollection("yem_entryentity");
            DynamicObjectCollection yem_entryentity1 = dataEntity.getDynamicObjectCollection("yem_entryentity1");
            yem_entryentity1.clear();
            if (yem_entryentity.size() > 0) {
                DynamicObject entryentity = yem_entryentity.get(row);
                if (entryentity != null) {
                    String yem_salesorderno = entryentity.getString("yem_salesorderno");
                    String yem_resourceno = entryentity.getString("yem_resourceno");
                    QFilter qFilters = new QFilter("yem_salesorderno", QCP.equals, yem_salesorderno);
                    qFilters.and(new QFilter("yem_model.number", QCP.equals, yem_resourceno));
                    DynamicObjectCollection yem_em_devicefiles = QueryServiceHelper.query("yem_em_devicefiles",
                            "id,number,name,yem_framenumber,yem_enginecode,yem_enginemodel,yem_dateofmanufacture,yem_machinedata"
                            , new QFilter[]{qFilters});
                    if (yem_em_devicefiles.size() > 0) {
                        for (int i = 0; i < yem_em_devicefiles.size(); i++) {
                            DynamicObject devicefiles = yem_em_devicefiles.get(i);
                            DynamicObject entryentity1 = yem_entryentity1.addNew();
                            entryentity1.set("yem_framenumber", devicefiles.getString("yem_framenumber"));
                            entryentity1.set("yem_enginecode", devicefiles.getString("yem_enginecode"));
                            entryentity1.set("yem_enginemodel", devicefiles.getString("yem_enginemodel"));
                            entryentity1.set("yem_machinedata", devicefiles.getDate("yem_machinedata"));
                            if (devicefiles.getString("yem_dateofmanufacture") != null) {
                                Date yem_dateofmanufacture = formatDate(devicefiles.getString("yem_dateofmanufacture"), "yyyy-MM-dd");
                                entryentity1.set("yem_dateofmanufacture", yem_dateofmanufacture);
                            }
                        }
                    }
                }
            }
            this.getView().updateView("yem_entryentity1");
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);
        FormOperate operate = (FormOperate) e.getSource();
        String key = operate.getOperateKey();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        if (key.equals("searchbook")) {
            int row = model.getEntryCurrentRowIndex("yem_entryentity");
            DynamicObjectCollection yem_entryentity = dataEntity.getDynamicObjectCollection("yem_entryentity");
            if (yem_entryentity.size() > 0) {
                DynamicObject entryentity = yem_entryentity.get(row);
                String yem_resourceno = entryentity.getString("yem_resourceno");
                QFilter qFilter = new QFilter("number", QCP.equals, yem_resourceno);
                DynamicObjectCollection data = QueryServiceHelper.query("yem_em_assequipment",
                        "id,number,name", new QFilter[]{qFilter});
                if (data.size() > 0) {
                    long id = data.get(0).getLong("id");
                    BillShowParameter parameter = new BillShowParameter();
                    parameter.setPkId(id);
                    parameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                    parameter.setFormId("yem_em_assequipment");
                    parameter.setStatus(OperationStatus.VIEW);
                    Map<String, Object> entryInfo = new HashMap<String, Object>();
                    entryInfo.put("key", "value");
                    parameter.setCustomParams(entryInfo);
                    this.getView().showForm(parameter);
                } else {
                    view.showErrorNotification("未获取到资源号对应的配件图册！");
                }
            }
        }
        if (key.equals("searchbookzj")) {
            int row = model.getEntryCurrentRowIndex("yem_entryentity1");
            DynamicObjectCollection yem_entryentity1 = dataEntity.getDynamicObjectCollection("yem_entryentity1");
            if (yem_entryentity1.size() > 0) {
                DynamicObject entryentity = yem_entryentity1.get(row);

                QFilter qFilters = new QFilter("yem_framenumber", QCP.equals, entryentity.getString("yem_framenumber"));
                DynamicObjectCollection yem_em_devicefiles = QueryServiceHelper.query("yem_em_devicefiles",
                        "id,number,name,yem_model.number", new QFilter[]{qFilters});
                if (yem_em_devicefiles.size() > 0) {
                    String yem_model = yem_em_devicefiles.get(0).getString("yem_model.number");
                    if (StringUtils.isNotEmpty(yem_model)) {
                        //根据输入内容获取设备电子目录
                        QFilter qFilter = new QFilter("number", QCP.equals, yem_model);
                        DynamicObjectCollection data = QueryServiceHelper.query("yem_em_assequipment",
                                "id,number,name", new QFilter[]{qFilter});
                        if (data.size() > 0) {
                            long id = data.get(0).getLong("id");
                            BillShowParameter parameter = new BillShowParameter();
                            parameter.setPkId(id);
                            parameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                            parameter.setFormId("yem_em_assequipment");
                            parameter.setStatus(OperationStatus.VIEW);
                            Map<String, Object> entryInfo = new HashMap<String, Object>();
                            entryInfo.put("key", "value");
                            parameter.setCustomParams(entryInfo);
                            this.getView().showForm(parameter);
                        } else {
                            view.showErrorNotification("未获取到整机编号对应的配件图册！");
                        }
                    }
                }
            }
        }
    }


    public Date formatDate(String date, String format) {
        SimpleDateFormat dt = new SimpleDateFormat(format);
        try {
            return dt.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void hyperLinkClick(HyperLinkClickEvent e) {
        String fieldName = e.getFieldName();
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if (fieldName.equals("yem_framenumber")) {
            int row = model.getEntryCurrentRowIndex("yem_entryentity1");
            DynamicObjectCollection yem_entryentity1 = dataEntity.getDynamicObjectCollection("yem_entryentity1");
            if (yem_entryentity1.size() > 0) {
                DynamicObject entryentity = yem_entryentity1.get(row);
                String yem_framenumber = entryentity.getString("yem_framenumber");
                QFilter qFilter = new QFilter("yem_framenumber", QCP.equals, yem_framenumber);
                DynamicObjectCollection data = QueryServiceHelper.query("yem_em_devicefiles",
                        "id,number,name", new QFilter[]{qFilter});
                if (data.size() > 0) {
                    long id = data.get(0).getLong("id");
                    BillShowParameter parameter = new BillShowParameter();
                    parameter.setPkId(id);
                    parameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                    parameter.setFormId("yem_em_devicefiles");
                    parameter.setStatus(OperationStatus.VIEW);
                    Map<String, Object> entryInfo = new HashMap<String, Object>();
                    entryInfo.put("key", "value");
                    parameter.setCustomParams(entryInfo);
                    this.getView().showForm(parameter);
                } else {
                    view.showErrorNotification("未获取到整机编码对应的设备档案！");
                }
            }
        }
    }
}
