package com.yem.em.dynamic;

import com.yem.wm.utils.StringUtils;
import com.yem.wm.utils.YEM;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.algo.RowMeta;
import kd.bos.algo.input.CollectionInput;
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.dataentity.serialization.SerializationUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.tree.TreeNode;
import kd.bos.form.*;
import kd.bos.form.control.Control;
import kd.bos.form.control.Label;
import kd.bos.form.control.Search;
import kd.bos.form.control.events.SearchEnterEvent;
import kd.bos.form.control.events.SearchEnterListener;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.form.plugin.IFormPlugin;
import kd.bos.list.ListFilterParameter;
import kd.bos.list.ListShowParameter;
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.SimpleDateFormat;
import java.util.*;

/**
 * @author zhouc
 * @date 2023/8/31 15:17
 * @className AtlasinquiryDynamicoEdit
 * @description 图册查询动态表单插件
 */
public class AtlasinquiryDynamicoEdit extends AbstractFormPlugin implements SearchEnterListener {

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        QFilter qFilters = new QFilter("yem_shoppingstatus", QCP.equals, "N");
        qFilters.and(new QFilter("yem_user.id", QCP.equals, YEM.getCurrentUserId()));
        DynamicObjectCollection yem_em_shopcartbill = QueryServiceHelper.query("yem_em_shopcartbill", "id,number,name,yem_pnumber,yem_enname,yem_materielmodel,yem_qty", new QFilter[]{qFilters});
        if (yem_em_shopcartbill.size() > 0) {
            ((Label) this.getControl("yem_labelap2")).setText(String.valueOf(yem_em_shopcartbill.size()));
        }
    }


    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        Search search = getView().getControl("yem_searchap");//资源号搜索
        search.addEnterListener(this);
        Search search1 = getView().getControl("yem_searchap1");//整机编号
        search1.addEnterListener(this);
        Search search2 = getView().getControl("yem_searchap2");//资源号搜索
        search2.addEnterListener(this);
        Search search3 = getView().getControl("yem_searchap3");//资源号搜索
        search3.addEnterListener(this);
        Search searchap4 = getView().getControl("yem_searchap4");//资源号搜索
        searchap4.addEnterListener(this);
        this.addClickListeners("yem_flexpanelap7", "yem_flexpanelap6");
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        Control source = (Control) evt.getSource();
        String key = source.getKey();
        if (key.equals("yem_flexpanelap7")) {//购物清单
            showSrcFieldForm("yem_em_shoppinglist", "shoppinglist", new HashMap<>());
        }
        if (key.equals("yem_flexpanelap6")) {
            ShowSrcFieldList("yem_em_partsorder", "partsorder", new HashMap<>());
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        IDataModel model = this.getModel();
        Object returnData = e.getReturnData();
        if (actionId.equals("shoppinglist")) {
            QFilter qFilters = new QFilter("yem_shoppingstatus", QCP.equals, "N");
            qFilters.and(new QFilter("yem_user.id", QCP.equals, YEM.getCurrentUserId()));
            DynamicObjectCollection yem_em_shopcartbill = QueryServiceHelper.query("yem_em_shopcartbill", "id,number,name,yem_pnumber,yem_enname,yem_materielmodel,yem_qty", new QFilter[]{qFilters});
            ((Label) this.getControl("yem_labelap2")).setText(String.valueOf(yem_em_shopcartbill.size()));
        }
    }

    /**
     * 输入回车进入方法
     *
     * @param e
     */
    @Override
    public void search(SearchEnterEvent e) {
        Search search = (Search) e.getSource();
        String key = search.getKey();
        String searchText = e.getText();
        if (key.equals("yem_searchap")) {//资源号搜索
            if (StringUtils.isNotEmpty(searchText)) {
                searchapSearch(searchText);
            }
        }
        if (key.equals("yem_searchap1")) {//整机搜索
            if (StringUtils.isNotEmpty(searchText)) {
                searchap1Search(searchText);
            }
        }
        if (key.equals("yem_searchap2")) {//零件号搜索
            if (StringUtils.isNotEmpty(searchText)) {
                searchap2Search(searchText);
            }
        }
        if (key.equals("yem_searchap3")) {//订单号搜索
            if (StringUtils.isNotEmpty(searchText)) {
                searchap3Search(searchText);
            }
        }
        if (key.equals("yem_searchap4")) {//产品机型
            if (StringUtils.isNotEmpty(searchText)) {
                searchap4Search(searchText);
            }
        }
    }

    /**
     * 自动补全风格 输入搜索条件后 进入该方法组织数据返回前端显示*。
     *
     * @param evt 上下文
     * @return
     */
    @Override
    public List<String> getSearchList(SearchEnterEvent evt) {
        Search search = (Search) evt.getSource();
        String key = search.getKey();
        String searchText = evt.getText();
        if (key.equals("yem_searchap")) {//资源号搜索
            if (StringUtils.isNotEmpty(searchText)) {
                return SearchList(searchText);
            }
        }
        if (key.equals("yem_searchap1")) {//整机搜索
            if (StringUtils.isNotEmpty(searchText)) {
                return SearchList1(searchText);
            }
        }
        if (key.equals("yem_searchap2")) {//零件号搜索
            if (StringUtils.isNotEmpty(searchText)) {
                return SearchList2(searchText);
            }
        }
        if (key.equals("yem_searchap3")) {//订单号搜索
            if (StringUtils.isNotEmpty(searchText)) {
                return SearchList3(searchText);
            }
        }
        if (key.equals("yem_searchap4")) {
            if (StringUtils.isNotEmpty(searchText)) {
                return SearchList4(searchText);
            }
        }
        return null;
    }

    @Override
    public List<Object> getComPlexSearchList(SearchEnterEvent evt) {
//        return SearchEnterListener.super.getComPlexSearchList(evt);
        return null;
    }

    /**
     * 资源号搜索
     *
     * @param key 用户输入内容
     */
    public void searchapSearch(String key) {
        IFormView view = this.getView();
        //根据输入内容获取设备电子目录
        QFilter qFilters = new QFilter("number", QCP.equals, key);
        DynamicObjectCollection data = QueryServiceHelper.query("yem_em_assequipment",
                "id,number,name", new QFilter[]{qFilters});
        if (data.size() > 0) {
            Map<String, Object> entryInfo = new HashMap<String, Object>(); //传入动态表单Map
            entryInfo.put("etcId", data.get(0).getString("id"));
            entryInfo.put("number", data.get(0).getString("number"));
            entryInfo.put("name", data.get(0).getString("name"));
            entryInfo.put("orgId", RequestContext.get().getOrgId());
            entryInfo.put("parentpageid", this.getView().getPageId());
            Setnest(data.get(0).getString("id"), entryInfo, "A");
        } else {
            view.showErrorNotification("未找资源号对应的配件图册！");
        }
    }

    /**
     * 整机搜索
     *
     * @param key 用户输入内容
     */
    public void searchap1Search(String key) {
        IFormView view = this.getView();
        //通过《设备档案》整机编码获取《设备档案》中产品明细资源表编码
        QFilter qFilters = new QFilter("yem_framenumber", QCP.equals, key);
        DynamicObjectCollection yem_em_devicefiles = QueryServiceHelper.query("yem_em_devicefiles",
                "id,number,name,yem_model.number,yem_analysistdate", new QFilter[]{qFilters});
        if (yem_em_devicefiles.size() > 0) {
            String yem_model = yem_em_devicefiles.get(0).getString("yem_model.number");
            Date yem_analysistdate = yem_em_devicefiles.get(0).getDate("yem_analysistdate");
            if (yem_analysistdate == null) {
                this.getView().showErrorNotification("整机编号【" + key + "】领料分析时间为空，禁止查询图册！");
                return;
            }
            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) {
                    Map<String, Object> entryInfo = new HashMap<String, Object>(); //传入动态表单Map
                    entryInfo.put("etcId", data.get(0).getString("id"));
                    entryInfo.put("number", data.get(0).getString("number"));
                    entryInfo.put("name", data.get(0).getString("name"));
                    entryInfo.put("orgId", RequestContext.get().getOrgId());
                    entryInfo.put("parentpageid", this.getView().getPageId());
                    entryInfo.put("complete", key);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String formattedDate = sdf.format(yem_em_devicefiles.get(0).getDate("yem_analysistdate"));
                    entryInfo.put("yem_analysistdate", formattedDate);
                    Setnest(data.get(0).getString("id"), entryInfo, "A");
                } else {
                    view.showErrorNotification("未找整机编号对应的配件图册！");
                }
            }
        } else {
            view.showErrorNotification("未找到整机编号对应的资源号！");
        }
    }

    /**
     * 零件号搜索
     *
     * @param key 用户输入内容
     */
    public void searchap2Search(String key) {
        IFormView view = this.getView();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        Map<String, Object> entryInfo = new HashMap<String, Object>(); //传入动态表单Map
        entryInfo.put("yem_salesorderno", key);
        entryInfo.put("Tpye", "searchap2");
        entryInfo.put("parentpageid", this.getView().getPageId());
        Setnest("yem_em_selectsaleno", entryInfo, "B");
    }

    /**
     * 资源号模糊构建下拉
     *
     * @param searchText 输入内容
     * @return 查询结果集合
     */
    public List<String> SearchList(String searchText) {
        Map<String, String> searchList = new HashMap<String, String>();
        QFilter filter1 = new QFilter("number", QCP.like, "%" + searchText + "%");
        QFilter filter2 = new QFilter("name", QCP.like, "%" + searchText + "%");
        QFilter filters = filter1.or(filter2);
        DynamicObjectCollection collection = QueryServiceHelper.query("yem_em_assequipment",
                "id,number,name", new QFilter[]{filters});
        for (DynamicObject obj : collection) {
            searchList.put(obj.get("id").toString(), obj.get("number").toString());
        }
        return new ArrayList<>(searchList.values());
    }

    /**
     * 整机搜索
     *
     * @param searchText 输入内容
     * @return 查询结果集合
     */
    public List<String> SearchList1(String searchText) {
        Map<String, String> searchList = new HashMap<String, String>();
        QFilter filter = new QFilter("yem_framenumber", QCP.like, "%" + searchText + "%");
        DynamicObjectCollection collection = QueryServiceHelper.query("yem_em_devicefiles",
                "id,number,name,yem_framenumber", new QFilter[]{filter});
        for (DynamicObject obj : collection) {
            searchList.put(obj.get("id").toString(), obj.get("yem_framenumber").toString());
        }
        return new ArrayList<>(searchList.values());
    }

    /**
     * 零件号
     *
     * @param searchText
     * @return
     */
    public List<String> SearchList2(String searchText) {
        Map<String, String> searchList = new HashMap<String, String>();
        QFilter filter = new QFilter("yem_entryentity.yem_partnumber", QCP.like, "%" + searchText + "%");
        DynamicObjectCollection collection = QueryServiceHelper.query("yem_em_assatlasdet",
                "id,yem_entryentity.yem_partnumber,yem_entryentity.yem_partname", new QFilter[]{filter});
        for (DynamicObject obj : collection) {
            searchList.put(obj.get("id").toString(), obj.get("yem_entryentity.yem_partnumber").toString());
        }
        return new ArrayList<>(searchList.values());
    }

    /**
     * 订单号
     *
     * @param searchText
     * @return
     */
    public List<String> SearchList3(String searchText) {
        Map<String, String> searchList = new HashMap<String, String>();
        QFilter filter = new QFilter("billno", QCP.like, "%" + searchText + "%");
        filter.and(new QFilter("yem_billtype.number", QCP.equals, "yem_es_salesorder_ZJ"));
        DynamicObjectCollection collection = QueryServiceHelper.query("yem_es_salesorder",
                "id,billno,yem_bizdate", new QFilter[]{filter}, "yem_bizdate");
        if (collection.size() > 0) {
            if (collection.size() < 10) {
                for (DynamicObject obj : collection) {
                    searchList.put(obj.get("id").toString(), obj.get("billno").toString());
                }
            } else {
                for (int i = 0; i < 10; i++) {
                    DynamicObject obj = collection.get(i);
                    searchList.put(obj.get("id").toString(), obj.get("billno").toString());
                }
            }
        }
        return new ArrayList<>(searchList.values());
    }

    /**
     * 订单号搜索
     *
     * @param key 用户输入内容
     */
    public void searchap3Search(String key) {
        Map<String, Object> entryInfo = new HashMap<String, Object>(); //传入动态表单Map
        entryInfo.put("yem_salesorderno", key);
        entryInfo.put("Tpye", "searchap3");
        Setnest("yem_em_selectsaleno", entryInfo, "B");
    }

    /**
     * 构建模糊查询下拉
     *
     * @param searchText 输入内容
     * @return
     */
    public List<String> SearchList4(String searchText) {
        Map<String, String> searchList = new HashMap<String, String>();
        QFilter filter = new QFilter("number", QCP.like, "%" + searchText + "%");
        DynamicObjectCollection collection = QueryServiceHelper.query("yem_bd_productstree",
                "id,number,name", new QFilter[]{filter}, "number");
        if (collection.size() > 0) {
            if (collection.size() < 10) {
                for (DynamicObject obj : collection) {
                    if (!searchList.containsKey(obj.get("number").toString())) {
                        searchList.put(obj.get("number").toString(), obj.get("number").toString());
                    }
                }
            } else {
                for (int i = 0; i < 10; i++) {
                    DynamicObject obj = collection.get(i);
                    if (!searchList.containsKey(obj.get("number").toString())) {
                        searchList.put(obj.get("number").toString(), obj.get("number").toString());
                    }
                }
            }
        }
        return new ArrayList<>(searchList.values());
    }

    /**
     * 产品机型搜索
     *
     * @param key 用户输入内容
     */
    public void searchap4Search(String key) {
        Map<String, Object> entryInfo = new HashMap<String, Object>(); //传入动态表单Map
        entryInfo.put("yem_salesorderno", key);
        entryInfo.put("Tpye", "searchap4");
        Setnest("yem_em_productquery", entryInfo, "B");
    }

    /**
     * 弹出表单
     *
     * @param FormId    弹出表单id
     * @param actionId  回调方法key
     * @param entryInfo 入参
     */
    private void showSrcFieldForm(String FormId, String actionId, Map<String, Object> entryInfo) {
        FormShowParameter showParameter = new FormShowParameter();
        showParameter.setFormId(FormId);
        showParameter.setCloseCallBack(new CloseCallBack((IFormPlugin) this, actionId));
        showParameter.setCustomParams(entryInfo);
        showParameter.getOpenStyle().setShowType(ShowType.Modal);
        this.getView().showForm(showParameter);
    }

    /**
     * 弹出列表
     *
     * @param FormId    弹出表单id
     * @param actionId  回调方法key
     * @param entryInfo
     */
    public void ShowSrcFieldList(String FormId, String actionId, Map<String, Object> entryInfo) {
        ListShowParameter listpara = new ListShowParameter();
        listpara.setBillFormId(FormId);
        listpara.setParentPageId(this.getView().getPageId());
        listpara.setMultiSelect(false);
        listpara.setStatus(OperationStatus.VIEW);
        listpara.getOpenStyle().setShowType(ShowType.MainNewTabPage);
        CloseCallBack closeCallBack = new CloseCallBack(this.getClass().getName(), actionId);
        listpara.setCloseCallBack(closeCallBack);
        if (entryInfo.size() > 0) {
            ListFilterParameter listFilterParameter = new ListFilterParameter();
            QFilter qFilter = new QFilter("billstatus", QCP.equals, "C");
            listFilterParameter.setFilter(qFilter);
            listpara.setListFilterParameter(listFilterParameter);
        }
        this.getView().showForm(listpara);
    }

    /**
     * 嵌套单据
     *
     * @param Number
     * @param entryInfo
     */
    public void Setnest(String Number, Map<String, Object> entryInfo, String type) {
        if (type.equals("B")) {
            FormShowParameter bsp = new FormShowParameter();
            bsp.setFormId(Number);
            OpenStyle openStyle = new OpenStyle();
            openStyle.setShowType(ShowType.InContainer);
            openStyle.setTargetKey("yem_flexpanelap4");
            bsp.setCustomParams(entryInfo);
            bsp.setHasRight(true);
            bsp.setStatus(OperationStatus.VIEW);
            bsp.setOpenStyle(openStyle);
            this.getView().showForm(bsp);
        }
        if (type.equals("A")) {
            BillShowParameter parameter = new BillShowParameter();
            parameter.setPkId(Number);
            parameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
            OpenStyle openStyle = new OpenStyle();
            openStyle.setShowType(ShowType.InContainer);
            openStyle.setTargetKey("yem_flexpanelap4");
            parameter.setFormId("yem_em_assequipment");
            parameter.setStatus(OperationStatus.VIEW);
            parameter.setOpenStyle(openStyle);
            parameter.setCustomParams(entryInfo);
            parameter.setHasRight(true);
            this.getView().showForm(parameter);
        }
    }
}
