package com.yem.em.dynamic;

import com.yem.em.utils.SubRelationUtils;
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.context.RequestContext;
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.Search;
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.field.TextEdit;
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.report.ReportList;
import kd.bos.servicehelper.QueryServiceHelper;

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

/**
 * @author zhouc
 * @date 2023/8/31 17:48
 * @className SelectsalenoDynamicoEdit
 * @description 订单号查询动态表单插件
 */
public class SelectsalenoDynamicoEdit 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").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_entryentity.yem_partnumber", QCP.equals, customParas.get("yem_salesorderno")));
//                DataSet dataSet = ORM.create().queryDataSet(algoKey, "yem_em_assatlasdet", "number ljnumber", qFilters.toArray(new QFilter[]{}));
//                DataSet dataSet2 = ORM.create().queryDataSet(algoKey, "yem_em_cmmptable", "yem_entryentity.yem_asscomponent.number yem_ccode,number ", null);
//                DataSet dataSet3 = dataSet.leftJoin(dataSet2).on("ljnumber", "yem_ccode").select(new String[]{"ljnumber"}, new String[]{"number"}).finish();
                DynamicObject object1 = SubRelationUtils.getfirstNumber(customParas.get("yem_salesorderno").toString());
                DynamicObject getfirstid = SubRelationUtils.getfirstid(customParas.get("yem_salesorderno").toString());
                if (getfirstid != null) {
                    qFilters.add(new QFilter("yem_entryentity.yem_asscomponent.number", QCP.equals, getfirstid.getString("number")));
                    DataSet dataSet3 = ORM.create().queryDataSet(algoKey, "yem_em_cmmptable", "number", 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 = dataSet3.leftJoin(dataSet1).on("number", "yem_modelno")
                            .select(new String[]{"number"},
                                    new String[]{"yem_modelno", "yem_products", "yem_productsgroup", "yem_dateofpurchase", "yem_salesorderno"})
                            .finish().where("yem_salesorderno is not null");
                    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 (object1 != null) {
                                    entryentity.set("yem_parentpartcode", object1.getString("number"));
                                }
                                entryentity.set("yem_partcode", customParas.get("yem_salesorderno"));
                                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"
                            , 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"));
                            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("未获取到整机编码对应的设备档案！");
                }
            }
        }
    }
}
