package com.yem.em.ass.dynamic;

import com.alibaba.fastjson.JSONObject;
import com.yem.em.utils.AtlasUtils;
import com.yem.em.utils.SubRelationUtils;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.StringUtils;
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.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.report.CellStyle;
import kd.bos.entity.tree.TreeNode;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IPageCache;
import kd.bos.form.ShowType;
import kd.bos.form.cardentry.CardEntry;
import kd.bos.form.control.Label;
import kd.bos.form.control.TreeView;
import kd.bos.form.control.events.CellClickEvent;
import kd.bos.form.control.events.CellClickListener;
import kd.bos.form.control.events.TreeNodeClickListener;
import kd.bos.form.control.events.TreeNodeEvent;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeBindDataEvent;
import kd.bos.form.events.BeforeBindDataListener;
import kd.bos.form.events.BeforeCreateListDataProviderArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.BillList;
import kd.bos.list.IListColumn;
import kd.bos.list.events.CreateListDataProviderListener;
import kd.bos.mvc.form.FormDataModel;
import kd.bos.mvc.list.ListDataProvider;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhouc
 * @date 2023/10/31 18:19
 * @className AssepcDynamicEdut
 * @description 总成设备电子目录新_动态表单
 */
public class AssepcNewDynamicEdut extends AbstractFormPlugin implements BeforeBindDataListener, TreeNodeClickListener, CellClickListener {
    private String selectid = "1";
    private String ParentNodeId = "1";
    private String atlasid = "";
    private String complete = "";
    private String type = StringUtils.getEmpty();
    private boolean isComplete = false;
    private String yem_replacement = StringUtils.getEmpty();
    private Date yem_completetime = null;

    /**
     * 监听事件
     *
     * @param e 上下文
     */
    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        TreeView treeView = this.getView().getControl("yem_treeviewap");
        treeView.addTreeNodeClickListener(this);
        CardEntry yem_entryentity1 = this.getView().getControl("yem_entryentity1");
        yem_entryentity1.addCellClickListener(this);
        CardEntry yem_entryentity = this.getView().getControl("yem_entryentity");
        yem_entryentity.addCellClickListener(this);
        BillList billList = this.getControl("yem_billlistap");
        // 注册监听
        billList.addBeforeBindDataListener(this);
    }

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        IPageCache cache = this.getPageCache();
        EmptData();
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> customParas = showParameter.getCustomParams();
        TreeNode Cliknode = null;
        if (customParas.containsKey("parentpageid")) {
            if (customParas.get("parentpageid") != null) {
                cache.put("parentpageid", customParas.get("parentpageid").toString());
            } else {
                BillList list = this.getControl("yem_billlistap");
                list.getView().setVisible(false, "yem_listoperationcolumnap");
            }
        }
        if (customParas.containsKey("treeMap")) {
            if (customParas.get("treeMap") != null) {
                JSONObject treeMap = (JSONObject) customParas.get("treeMap");
                Cliknode = new TreeNode(treeMap.get("parentid").toString(), treeMap.get("id").toString(), treeMap.get("text").toString(), treeMap.get("isParent"));
            }
        }
        if (customParas.containsKey("complete")) {
            if (customParas.get("complete") != null) {
                cache.put("complete", customParas.get("complete").toString());
                cache.put("isComplete", String.valueOf(true));
                isComplete = true;
            }
        }
        if (customParas.containsKey("yem_analysistdate")) {
            if (customParas.get("yem_analysistdate") != null) {
                cache.put("yem_analysistdate", customParas.get("yem_analysistdate").toString());
            }
        }

        GetTreeView(customParas);
        BillList billList = this.getControl("yem_billlistap");
        billList.addCreateListDataProviderListener(new CreateListDataProviderListener() {
            @Override
            public void createListDataProvider(BeforeCreateListDataProviderArgs args) {
                args.setListDataProvider(new BillListDataProvider());
            }
        });

    }

    /**
     * 构建树结构
     *
     * @param customParas 入参
     */
    public void GetTreeView(Map<String, Object> customParas) {
        TreeNode Cliknode = null;
        IPageCache cache = this.getPageCache();
        String number = StringUtils.getEmpty(), name = StringUtils.getEmpty(), orgId = StringUtils.getEmpty(), etcId = StringUtils.getEmpty();
        if (customParas.containsKey("number")) {
            number = customParas.get("number").toString();
            ParentNodeId = number;
        }
        if (customParas.containsKey("name")) {
            name = customParas.get("name").toString();
        }
        if (customParas.containsKey("orgId")) {
            orgId = customParas.get("orgId").toString();
        }
        if (customParas.containsKey("etcId")) {
            etcId = customParas.get("etcId").toString();
        }
        if (cache.get("complete") != null) {
            complete = cache.get("complete").toString();
        }
        if (cache.get("isComplete") != null) {
            isComplete = Boolean.valueOf(cache.get("isComplete"));
        }
        Date yem_completetime = null;
        if (cache.get("yem_analysistdate") != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
                yem_completetime = sdf.parse(cache.get("yem_analysistdate").toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (customParas.get("type") != null) {
            type = customParas.get("type").toString();
            if (customParas.get("type") != null) {
                if (type.equals("assets")) {
                    cache.put("yem_replacement", "Par");
                }
                if (type.equals("atlas")) {
                    cache.put("yem_replacement", "Sub");
                }
            }
        }
        if (StringUtils.isNotEmpty(etcId)) {
            List<Map> fromCmmp = null;
            List<TreeNode> list = new ArrayList<TreeNode>();
            String accountId = RequestContext.get().getAccountId();
            if (StringUtils.isEmpty(type)) {
                return;
            } else {
                if (type.equals("assets")) {
                    yem_replacement = "Par";
                    list.add(new TreeNode(null, number, number + " " + name, true));
                    //根据CMMP明细表构建
                    QFilter Filter = new QFilter("number", QFilter.equals, number);
                    Filter.and(new QFilter("status", QFilter.equals, "C"));
                    Filter.and(new QFilter("yem_entryentity.yem_partisreplace", QFilter.equals, false));
                    Filter.and(new QFilter("yem_entryentity.yem_assatlasdet.number", QFilter.not_equals, null));
//                    Filter.and(new QFilter("yem_entryentity.yem_completetime", QCP.less_equals, yem_completetime));
                    DynamicObjectCollection yem_em_cmmptable = QueryServiceHelper.query("yem_em_cmmptable",
                            "yem_entryentity.yem_assatlasdet.number,yem_entryentity.yem_assatlasdet.name,yem_entryentity.yem_assatlasdet.yem_enname",
                            new QFilter[]{Filter}, "yem_entryentity.yem_assatlasdet.number");
                    if (yem_em_cmmptable.size() > 0) {
                        for (int i = 0; i < yem_em_cmmptable.size(); i++) {
                            DynamicObject dynamicObject = yem_em_cmmptable.get(i);
                            String ccode = dynamicObject.getString("yem_entryentity.yem_assatlasdet.number");
                            String ccodename = dynamicObject.getString("yem_entryentity.yem_assatlasdet.name");
                            String yem_nameen = dynamicObject.getString("yem_entryentity.yem_assatlasdet.yem_enname");
                            //查询部件替换关系
                            DynamicObject yem_em_substitution = SubRelationUtils.queryAssemblyrep(number, ccode, "Par", isComplete, yem_completetime);
                            if (yem_em_substitution != null) {
                                String yemTnumber = yem_em_substitution.getString("yem_entryentity.yem_repnumber");
                                String yemTname = yem_em_substitution.getString("yem_entryentity.yem_repname");
                                if (isassat(yemTnumber)) {
                                    list.add(new TreeNode(number, yemTnumber, yemTnumber + " " + yemTname, true));
                                } else {
                                    list.add(new TreeNode(number, yemTnumber, yemTnumber + " " + yemTname));
                                }
                            } else {
                                //是否替换《总成间零件替换关系》
                                DynamicObject pra = SubRelationUtils.queryassemtopart(number, ccode, "", "pra", yem_replacement, isComplete, yem_completetime);
                                if (pra != null) {
                                    String yem_repno = pra.getString("yem_entryentity.yem_repno");
                                    String yem_repnoname = pra.getString("yem_entryentity.yem_repnoname");
                                    if (isassat(yem_repno)) {
                                        list.add(new TreeNode(number, yem_repno, yem_repno + " " + yem_repnoname, true));
                                    } else {
                                        list.add(new TreeNode(number, yem_repno, yem_repno + " " + yem_repnoname));
                                    }
                                } else {
                                    if (isassat(ccode)) {
                                        list.add(new TreeNode(number, ccode, ccode + " " + ccodename, true));
                                    } else {
                                        list.add(new TreeNode(number, ccode, ccode + " " + ccodename));
                                    }
                                }
                            }
                        }
                    } else {
                        list.add(new TreeNode(number, "0", "无数据"));
                    }
                    if (StringUtils.isNotEmpty(complete)) {
                        QFilter qFilterdev = new QFilter("yem_framenumber", QCP.equals, complete);
                        DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_em_devicefiles",
                                "id,yem_retrofitting,yem_albumassemblyno", qFilterdev.toArray());
                        if (billType != null) {
                            Map<String, DynamicObject> jzlist = new HashMap<>();
                            DynamicObjectCollection yem_retrofitting = billType.getDynamicObjectCollection("yem_retrofitting");
                            if (yem_retrofitting.size() > 0) {
                                for (int i = 0; i < yem_retrofitting.size(); i++) {
                                    DynamicObject dynamicObject = yem_retrofitting.get(i);
                                    DynamicObject yem_albumassemblyno = dynamicObject.getDynamicObject("yem_albumassemblyno");
                                    if (yem_albumassemblyno != null) {
                                        String number1 = yem_albumassemblyno.getString("number");
                                        if (!jzlist.containsKey(number1)) {
                                            jzlist.put(number1, yem_albumassemblyno);
                                        }
                                    }
                                }
                                if (jzlist.size() > 0) {
                                    for (String key : jzlist.keySet()) {
                                        DynamicObject dynamicObject = jzlist.get(key);
                                        list.add(new TreeNode(number, key + "_123245678910", key + " " + dynamicObject.getString("name")));
                                    }
                                }
                                if (yem_retrofitting.size() > 0 && jzlist.size() != yem_retrofitting.size()) {
                                    list.add(new TreeNode(number, "_123245678910", "加装明细"));
                                }
                            }
                        }
                    }
                }
                //总成
                if (type.equals("atlas")) {
                    yem_replacement = "Sub";
                    if (isassat(number)) {
                        list.add(new TreeNode(null, number, number + " " + name, true));
                    } else {
                        list.add(new TreeNode(null, number, number + " " + name));
                    }
                    DynamicObject yem_em_assatlasdet = BusinessDataServiceHelper.loadSingle(etcId, "yem_em_assatlasdet");
                    if (yem_em_assatlasdet != null) {
                        DynamicObjectCollection dynamicObjectCollection = yem_em_assatlasdet.getDynamicObjectCollection("yem_entryentity");
                        for (int i = 0; i < dynamicObjectCollection.size(); i++) {
                            DynamicObject dynamicObject = dynamicObjectCollection.get(i);
                            //是否部件
                            boolean yemIscomp = dynamicObject.getBoolean("yem_iscomp");
                            if (yemIscomp) {
                                String yemPartnumber = dynamicObject.getString("yem_partnumber");
                                String yemPartname = dynamicObject.getString("yem_partname");
                                //是否替换 查询《替换关系》
                                boolean yemPartisreplace = dynamicObject.getBoolean("yem_partisreplace");
                                if (yemPartisreplace) {
                                    //查询部件替换关系
                                    DynamicObject yem_em_substitution = SubRelationUtils.queryAssemblyrep(yem_em_assatlasdet.getString("number"), yemPartnumber, "Par", isComplete, yem_completetime);
                                    if (yem_em_substitution != null) {
                                        String yemTnumber = yem_em_substitution.getString("yem_entryentity.yem_repnumber");
                                        String yemTname = yem_em_substitution.getString("yem_entryentity.yem_repname");
                                        if (isassat(yemTnumber)) {
                                            list.add(new TreeNode(number, yemTnumber, yemTnumber + " " + yemTname, true));
                                        } else {
                                            list.add(new TreeNode(number, yemTnumber, yemTnumber + " " + yemTname));
                                        }
                                    }
                                } else {
                                    //是否替换《总成间零件替换关系》
                                    DynamicObject pra = SubRelationUtils.queryassemtopart(number, yemPartnumber, "", "pra", yem_replacement, isComplete, yem_completetime);
                                    if (pra != null) {
                                        String yem_repno = pra.getString("yem_entryentity.yem_repno");
                                        String yem_repnoname = pra.getString("yem_entryentity.yem_repnoname");
                                        if (isassat(yem_repno)) {
                                            list.add(new TreeNode(number, yem_repno, yem_repno + " " + yem_repnoname, true));
                                        } else {
                                            list.add(new TreeNode(number, yem_repno, yem_repno + " " + yem_repnoname));
                                        }
                                    } else {
                                        if (isassat(yemPartnumber)) {
                                            list.add(new TreeNode(number, yemPartnumber, yemPartnumber + " " + yemPartname, true));
                                        } else {
                                            list.add(new TreeNode(number, yemPartnumber, yemPartnumber + " " + yemPartname));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            TreeView treeView = getControl("yem_treeviewap");
            treeView.addNodes(list);
            if (Cliknode == null) {
                Cliknode = GetLastNode(list, etcId);
            }
            if (Cliknode != null) {
                treeView.focusNode(Cliknode);
                treeView.checkNode(Cliknode);
                String nodeid = Cliknode.getId();
                treeView.expand(nodeid);
                treeView.showNode(nodeid);
                treeView.treeNodeClick(Cliknode.getParentid(), Cliknode.getId());
                selectid = nodeid;
                Getgroupdata(nodeid, "1", etcId, name);
            }
        }
    }

    /**
     * 获取树一级节点
     *
     * @param list
     * @param etcId
     * @return
     */
    private TreeNode GetLastNode(List<TreeNode> list, String etcId) {
        TreeNode node = null;
        if (type.equals("atlas")) {
            if (list.size() > 0) {
                node = list.get(0);
            }
        }
        if (type.equals("assets")) {
            if (list.size() > 1) {
                node = list.get(1);
            }
        }
        return node;
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        IPageCache cache = this.getPageCache();
        if (cache.get("yem_replacement") != null) {
            yem_replacement = cache.get("yem_replacement").toString();
        }
        if (cache.get("complete") != null) {
            complete = cache.get("complete").toString();
        }
        if (cache.get("isComplete") != null) {
            isComplete = Boolean.valueOf(cache.get("isComplete"));
        }
        Date yem_completetime = null;
        if (cache.get("yem_analysistdate") != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
                yem_completetime = sdf.parse(cache.get("yem_analysistdate").toString());
            } catch (ParseException em) {
                em.printStackTrace();
            }
        }
        IDataModel model = this.getModel();
        String key = e.getOperateKey();
        FormDataModel billModel = (FormDataModel) this.getModel();
        IPageCache pageCache = this.getPageCache();
        if ("repgroup".equals(key)) {
            TreeView treeView = this.getControl("yem_treeviewap");
            Map<String, Object> focusNode = treeView.getTreeState().getFocusNode();
            String id = focusNode.get("id").toString();
            BillList billList = this.getControl("yem_billlistap");
            if (billList != null) {
                ListSelectedRowCollection coll = billList.getSelectedRows();
                if (coll.size() > 0) {
                    ListSelectedRow rowlist = coll.get(0);
                    if (rowlist != null) {
                        String KeyValue = rowlist.getPrimaryKeyValue().toString();
                        DynamicObject yem_em_assatlaspartdet = BusinessDataServiceHelper.loadSingle(KeyValue, "yem_em_assatlaspartdet");
                        if (yem_em_assatlaspartdet != null) {
                            String number = yem_em_assatlaspartdet.getString("number");
                            long ReplaceGroupid = SubRelationUtils.queryReplaceGroup(id, number, isComplete, yem_completetime);
                            if (ReplaceGroupid > 0) {
                                BillShowParameter parameter = new BillShowParameter();
                                parameter.setPkId(ReplaceGroupid);
                                parameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                                parameter.setFormId("yem_em_replacementgroup");
                                parameter.setStatus(OperationStatus.VIEW);
//                                Map<String, Object> entryInfo = new HashMap<String, Object>();
////                                entryInfo.put("key", "value");
//                                parameter.setCustomParams(entryInfo);
                                this.getView().showForm(parameter);
                            } else {
                                this.getView().showErrorNotification("未获取到对应的替换组信息！");
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据设备部件ID
     * 1.获取设备部件图片
     *
     * @param nodeid 设备部件编码
     */
    private void Getgroupdata(String nodeid, String type, String etcId, String name) {
        if (!nodeid.equals("123245678910")) {
            QFilter qFilter = new QFilter("number", QCP.equals, nodeid);
            String selectfields = DynamicObjectUtil.getSelectfields("yem_em_assatlasdet");
            selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_em_assatlasdet", "yem_attdetail");
            DynamicObject component = BusinessDataServiceHelper.loadSingle("yem_em_assatlasdet", selectfields, qFilter.toArray());
            if (component != null) {
                this.getView().getModel().setValue("yem_ecataloggroup", component);
//                String imageUrls = component.getString("yem_imageurl");
                String imageUrls = initLatestImage(component);
                Setpicturefield(imageUrls);//构建图片
                if (StringUtils.isNotEmpty(imageUrls)) {
                    String[] urls = imageUrls.split(";");
                    if (urls.length > 0) {
                        this.getView().getModel().setValue("yem_picture1", urls[0]);
                    }
                } else {
                    this.getView().getModel().setValue("yem_picture1", null);
                }
                this.getView().updateView("yem_flexpanelap6");
            }
        }
    }

    /**
     * 4.图册查询显示最新断点时间的图片
     * @param component
     * @return
     */
    private String initLatestImage(DynamicObject component) {
        DynamicObjectCollection collection = component.getDynamicObjectCollection("yem_attdetail");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, List<DynamicObject>> map = new HashMap<>();
        if (isComplete) {
            DynamicObject devicefiles = BusinessDataServiceHelper.loadSingle("yem_em_devicefiles", new QFilter[]{new QFilter("number", "=", complete)});
            if (devicefiles == null) return "";
            Date analysistdate = devicefiles.getDate("yem_analysistdate");
            for (DynamicObject dynamicObject : collection) {
                Date breakpointime = dynamicObject.getDate("yem_breakpointime");
                if (breakpointime.after(analysistdate)) {
                    String key = sdf.format(breakpointime);
                    List<DynamicObject> list;
                    if (map.containsKey(key)) {
                        list = map.get(key);
                    } else {
                        list = new ArrayList<>();
                    }
                    list.add(dynamicObject);
                    map.put(key, list);
                }
            }
        } else {
            for (DynamicObject dynamicObject : collection) {
                Date breakpointime = dynamicObject.getDate("yem_breakpointime");
                String key = sdf.format(breakpointime);
                List<DynamicObject> list;
                if (map.containsKey(key)) {
                    list = map.get(key);
                } else {
                    list = new ArrayList<>();
                }
                list.add(dynamicObject);
                map.put(key, list);
            }
        }

        List<String> keys = new ArrayList<>(map.keySet());
        keys.sort(Comparator.comparing(key -> {
            try {
                return sdf.parse(key);
            } catch (ParseException e) {
                return null;
            }
        }, Comparator.reverseOrder()));

        StringBuilder sb = new StringBuilder();

        if (!keys.isEmpty()) {
            List<DynamicObject> list = map.get(keys.get(0));
            for (DynamicObject dynamicObject : list) {
                String attaddress = dynamicObject.getString("yem_attaddress");
                sb.append(attaddress).append(";");
            }
        }
        return sb.toString();
    }

    @Override
    public void cellClick(CellClickEvent e) {
        CardEntry cardEntry = (CardEntry) e.getSource();
        int row = e.getRow();
        String key = cardEntry.getKey();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if (cardEntry.getEntryKey().equals("yem_entryentity1")) {
            String yem_picturefield = "";
            DynamicObjectCollection yem_entryentity1 = dataEntity.getDynamicObjectCollection("yem_entryentity1");
            if (yem_entryentity1.size() > 0) {
                DynamicObject entryentity = yem_entryentity1.get(row);
                if (entryentity != null) {
                    yem_picturefield = entryentity.getString("yem_picturefield");
                }
            }
            this.getView().getModel().setValue("yem_picture1", yem_picturefield);
        }
        if (cardEntry.getEntryKey().equals("yem_entryentity")) {
            billlistap(dataEntity, row);
        }
    }

    /**
     * 分局点击图册号给单据体行赋值背景色
     *
     * @param dataEntity 整单动态对象
     * @param row        行号
     */
    public void billlistap(DynamicObject dataEntity, int row) {
        DynamicObjectCollection yem_entryentity = dataEntity.getDynamicObjectCollection("yem_entryentity");
        if (yem_entryentity.size() > 0) {
            DynamicObject entryentity = yem_entryentity.get(row);
            if (entryentity != null) {
                atlasid = entryentity.getString("yem_atlasid");
            }
        }
        BillList billList = this.getControl("yem_billlistap");
        List<IListColumn> columns = billList.getShowListColumns();//获取页面显示的字段列表
        List<CellStyle> cslist = new ArrayList();
        ListSelectedRowCollection rowList = billList.getCurrentListAllRowCollection();
        ListSelectedRow ss = billList.getCurrentSelectedRowInfo();
        for (int x = 0; x < rowList.size(); x++) {
            String rowListKey = rowList.get(x).getPrimaryKeyValue().toString();
            if (rowListKey.equals(atlasid)) {
                //给行添加背景色
                for (IListColumn lc : columns) {
                    CellStyle cs = new CellStyle();
                    cs.setFieldKey(lc.getListFieldKey());
                    cs.setBackColor("#45cdff");
                    cs.setRow(x);
                    cslist.add(cs);
                }
            } else {
                //给行添加背景色
                for (IListColumn lc : columns) {
                    CellStyle cs = new CellStyle();
                    cs.setFieldKey(lc.getListFieldKey());
                    cs.setBackColor("white");
                    cs.setRow(x);
                    cslist.add(cs);
                }
            }
        }
        billList.setCellStyle(cslist);
    }

    @Override
    public void cellDoubleClick(CellClickEvent cellClickEvent) {

    }

    /**
     * 构建图片单据体
     *
     * @param imageUrls 图片URL字符串
     */
    public void Setpicturefield(String imageUrls) {
        //获取卡片控件
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection yem_entryentity = dataEntity.getDynamicObjectCollection("yem_entryentity1");
        yem_entryentity.clear();
        String[] data = imageUrls.split(";");
        if (data.length > 0) {
            for (int i = 0; i < data.length; i++) {
                DynamicObject entryentity = yem_entryentity.addNew();
                entryentity.set("yem_picturefield", data[i]);
            }
        }
        this.getView().updateView("yem_entryentity1");
    }


    /**
     * 树点击事件
     *
     * @param evt 上下文
     */
    @Override
    public void treeNodeClick(TreeNodeEvent evt) {
        TreeNodeClickListener.super.treeNodeClick(evt);
        TreeView treeView = (TreeView) evt.getSource();
        IPageCache cache = this.getPageCache();
        if (treeView.getKey().equals("yem_treeviewap")) {
            String selectNodeId = evt.getNodeId().toString();
            ParentNodeId = evt.getParentNodeId().toString();
            if (StringUtils.isNotEmpty(selectNodeId)) {
                if (cache.get("complete") != null) {
                    complete = cache.get("complete").toString();
                }
                if (cache.get("isComplete") != null) {
                    isComplete = Boolean.valueOf(cache.get("isComplete"));
                }
                if (cache.get("yem_analysistdate") != null) {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
                        yem_completetime = sdf.parse(cache.get("yem_analysistdate").toString());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                selectid = selectNodeId;
                Getgroupdata(selectNodeId, "0", "", "");
                this.getView().updateView("yem_billlistap");
                Getsub(treeView, selectNodeId);
            }
        }
    }

    /**
     * 根据编码查询是否有下级
     *
     * @param treeView     树模型00
     * @param selectNodeId 点击节点编码
     */
    public void Getsub(TreeView treeView, String selectNodeId) {
        IPageCache cache = this.getPageCache();
        if (cache.get("yem_replacement") != null) {
            yem_replacement = cache.get("yem_replacement").toString();
        }
        if (cache.get("complete") != null) {
            complete = cache.get("complete").toString();
        }
        if (cache.get("isComplete") != null) {
            isComplete = Boolean.valueOf(cache.get("isComplete"));
        }

        if (cache.get("yem_analysistdate") != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
                yem_completetime = sdf.parse(cache.get("yem_analysistdate").toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
//        if (type.equals("assets")) {
        QFilter qFilter = new QFilter("number", QCP.equals, selectNodeId);
        qFilter.and(new QFilter("enable", QCP.equals, "1"));
        qFilter.and(new QFilter("yem_entryentity.yem_iscomp", QCP.equals, true));
        qFilter.and(new QFilter("yem_entryentity.yem_partisreplace", QCP.equals, false));
        DynamicObjectCollection yem_em_assatlasdet = QueryServiceHelper.query("yem_em_assatlasdet",
                "id,yem_entryentity.yem_partnumber,yem_entryentity.yem_partname", new QFilter[]{qFilter});
        if (yem_em_assatlasdet.size() > 0) {
            for (int i = 0; i < yem_em_assatlasdet.size(); i++) {
                DynamicObject dynamicObject = yem_em_assatlasdet.get(i);
                String yem_partnumber = dynamicObject.getString("yem_entryentity.yem_partnumber");
                String yem_partname = dynamicObject.getString("yem_entryentity.yem_partname");
                TreeNode node = null;
                //查询部件替换关系
                DynamicObject yem_em_substitution = SubRelationUtils.queryAssemblyrep(selectNodeId, yem_partnumber, "Par", isComplete, yem_completetime);
                if (yem_em_substitution != null) {
                    String yemTnumber = yem_em_substitution.getString("yem_entryentity.yem_repnumber");
                    String yemTname = yem_em_substitution.getString("yem_entryentity.yem_repname");
                    if (isassat(yemTnumber)) {
                        node = new TreeNode(selectNodeId, yemTnumber, yemTnumber + " " + yemTname, true);
                    } else {
                        node = new TreeNode(selectNodeId, yemTnumber, yemTnumber + " " + yemTname);
                    }
                } else {
                    //是否替换《总成间零件替换关系》
                    DynamicObject pra = SubRelationUtils.queryassemtopart(selectNodeId, yem_partnumber, "", "pra", yem_replacement, isComplete, yem_completetime);
                    if (pra != null) {
                        String yem_repno = pra.getString("yem_entryentity.yem_repno");
                        String yem_repnoname = pra.getString("yem_entryentity.yem_repnoname");
                        if (isassat(yem_repno)) {
                            node = new TreeNode(selectNodeId, yem_repno, yem_repno + " " + yem_repnoname, true);
                        } else {
                            node = new TreeNode(selectNodeId, yem_repno, yem_repno + " " + yem_repnoname);
                        }
                    } else {
                        if (isassat(yem_partnumber)) {
                            node = new TreeNode(selectNodeId, yem_partnumber, yem_partnumber + " " + yem_partname, true);
                        } else {
                            node = new TreeNode(selectNodeId, yem_partnumber, yem_partnumber + " " + yem_partname);
                        }
                    }
                }
                treeView.addNode(node);
            }
            treeView.showNode(selectNodeId);
            this.getView().updateView("yem_treeviewap");
        }
//        }
    }

    @Override
    public void beforeBindData(BeforeBindDataEvent beforeBindDataEvent) {
        BillList billList = this.getControl("yem_billlistap");
        billList.addCreateListDataProviderListener(new CreateListDataProviderListener() {
            @Override
            public void createListDataProvider(BeforeCreateListDataProviderArgs args) {
                args.setListDataProvider(new BillListDataProvider());
            }
        });
    }

    // 内部类，为单据列表控件添加值
    public class BillListDataProvider extends ListDataProvider {
        @Override
        public DynamicObjectCollection getData(int start, int limit) {
            if (selectid.contains("_123245678910")) {
                String[] selec = selectid.split("_");
                String selectfield = DynamicObjectUtil.getSelectfields("yem_em_devicefiles", false);
                String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, "yem_em_devicefiles", "yem_retrofitting", false);
                QFilter qFilterdev = new QFilter("yem_framenumber", QCP.equals, complete);
                if (selec[0].length() > 0) {
                    qFilterdev.and(new QFilter("yem_retrofitting.yem_albumassemblyno.number", QCP.equals, selec[0]));
                } else {
                    qFilterdev.and(new QFilter("yem_retrofitting.yem_albumassemblyno.number", QCP.equals, null));
                }
                DynamicObjectCollection yem_retrofitting = QueryServiceHelper.query("yem_em_devicefiles", selectfields, new QFilter[]{qFilterdev}, null);
                if (yem_retrofitting.size() > 0) {
                    //重新构建Data
                    DynamicObjectCollection data = reconData(yem_retrofitting);
                    getQueryResult().setCollection(data);
                    getQueryResult().setDataCount(data.size());
                    Setistcardviewap(data);
                    return data;
                }

            } else {
                String selectFieids = "id,number,name,yem_atlasno,yem_partenname,yem_partqty,yem_partisreplace,yem_partremark,yem_partweight," +
                        "yem_price,yem_qtytext,yem_pricetext,yem_weighttext,yem_isrepgroup";
                List getassatlaspartdetlist = getassatlaspartdet();
                QFilter qFilter = new QFilter("id", QCP.in, getassatlaspartdetlist);
                DynamicObjectCollection data = QueryServiceHelper.query("yem_em_assatlaspartdet", selectFieids, new QFilter[]{qFilter}, "length(yem_atlasno),yem_atlasno");
                getQueryResult().setCollection(data);
                getQueryResult().setDataCount(data.size());
                // 把列数据返回
                DynamicObjectCollection datas = DealData(data);
                Setistcardviewap(datas);
                return datas;
            }
            return EmptData();
        }
    }

    /**
     * 给图号单据体赋值
     *
     * @param data
     */
    public void Setistcardviewap(DynamicObjectCollection data) {
        //获取卡片控件
        ((Label) this.getControl("yem_labelap2")).setText("共" + data.size() + "条");
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection yem_entryentity = dataEntity.getDynamicObjectCollection("yem_entryentity");
        yem_entryentity.clear();
        if (data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                DynamicObject dataObject = data.get(i);
                DynamicObject entryentity = yem_entryentity.addNew();
                String yem_atlasno = dataObject.getString("yem_atlasno");
                if (yem_atlasno.length() > 0) {
                    entryentity.set("yem_atlasnumber", dataObject.get("yem_atlasno"));
                    entryentity.set("yem_atlasid", dataObject.get("id"));
                }
            }
        }
        this.getView().updateView("yem_entryentity");
    }

    public DynamicObjectCollection EmptData() {
        DynamicObjectCollection NewdataCollection = new DynamicObjectCollection();
        DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject("yem_em_asspart");
        DynamicObject newDynObject = new DynamicObject(dynamicObject.getDynamicObjectType());
        NewdataCollection.add(newDynObject);
        return NewdataCollection;
    }

    /**
     * 重新构建Data
     *
     * @param data 待处理数据包
     * @return 返回数据包
     */
    public DynamicObjectCollection reconData(DynamicObjectCollection data) {
        DynamicObjectCollection NewdataCollection = new DynamicObjectCollection();
        DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject("yem_em_assatlaspartdet");
        for (int i = 0; i < data.size(); i++) {
            DynamicObject dynamicObject1 = data.get(i);
            long aLong = dynamicObject1.getLong("yem_retrofitting.yem_materiel");
            DynamicObject dynamicObject2 = BusinessDataServiceHelper.loadSingle(aLong, "bd_material");
            DynamicObject newDynObject = new DynamicObject(dynamicObject.getDynamicObjectType());
            newDynObject.set("yem_atlasno", i + 1);//图册编号
            newDynObject.set("number", dynamicObject2.getString("number"));//零件编号
            newDynObject.set("name", dynamicObject2.getString("name"));//零件名称
            newDynObject.set("yem_partenname", dynamicObject1.getString("yem_retrofitting.yem_enname"));//英文名称
            BigDecimal yem_qty1 = dynamicObject1.getBigDecimal("yem_retrofitting.yem_qty1");
            newDynObject.set("yem_qtytext", yem_qty1.setScale(4, BigDecimal.ROUND_HALF_UP).toString());//数量
            newDynObject.set("yem_partremark", dynamicObject1.getString("yem_retrofitting.yem_desc"));//备注
            NewdataCollection.add(newDynObject);
        }
        return NewdataCollection;
    }

    /**
     * 处理特殊逻辑
     * 1. 数量
     * 2. 替换件
     *
     * @param data 查询的数据集合
     * @return 返回数据包
     */
    public DynamicObjectCollection DealData(DynamicObjectCollection data) {
        IPageCache cache = this.getPageCache();
        if (cache.get("yem_replacement") != null) {
            yem_replacement = cache.get("yem_replacement").toString();
        }
        if (cache.get("complete") != null) {
            complete = cache.get("complete").toString();
        }
        if (cache.get("isComplete") != null) {
            isComplete = Boolean.valueOf(cache.get("isComplete"));
        }
        Date yem_completetime = null;
        if (cache.get("yem_analysistdate") != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
                yem_completetime = sdf.parse(cache.get("yem_analysistdate").toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        for (int i = 0; i < data.size(); i++) {
            DynamicObject newDynObject = data.get(i);
            //通过零件编码过滤出替换零件编码
            String yem_pnumber = newDynObject.getString("number");
            //是否替换
//            DynamicObject yem_em_substitution = SubRelationUtils.queryAssemblyrep(selectid, yem_pnumber, yem_replacement, isComplete, yem_completetime);
            DynamicObject yem_em_substitution = SubRelationUtils.queryAssemblyrep(selectid, yem_pnumber, "Sub", isComplete, yem_completetime);
            if (yem_em_substitution != null) {
                String yem_replace = yem_em_substitution.getString("yem_entryentity.yem_replace");
                if (yem_replace.equals("E")) {
                    newDynObject.set("number", yem_em_substitution.getString("yem_entryentity.yem_onumber"));
                    newDynObject.set("name", yem_em_substitution.getString("yem_entryentity.yem_oname"));
                    newDynObject.set("yem_partenname", yem_em_substitution.getString("yem_entryentity.yem_oenname"));
                    newDynObject.set("yem_qtytext", yem_em_substitution.getString("yem_entryentity.yem_oqty"));
                } else {
                    newDynObject.set("number", yem_em_substitution.getString("yem_entryentity.yem_repnumber"));
                    newDynObject.set("name", yem_em_substitution.getString("yem_entryentity.yem_repname"));
                    newDynObject.set("yem_partenname", yem_em_substitution.getString("yem_entryentity.yem_repenname"));
                    newDynObject.set("yem_qtytext", yem_em_substitution.getString("yem_entryentity.yem_repenqty"));
                }

                newDynObject.set("yem_partisreplace", true);
            } else {
                //总成间零件替换关系
//                DynamicObject pra = SubRelationUtils.queryassemtopart(ParentNodeId, selectid, yem_pnumber, "rep", "Sub", isComplete, yem_completetime);
                DynamicObjectCollection pra = SubRelationUtils.queryassemtopartAll(ParentNodeId, selectid, yem_pnumber, "rep", yem_replacement, isComplete, yem_completetime);
                if (pra.size() > 0) {
                    newDynObject.set("yem_partisreplace", true);
                } else {
                    newDynObject.set("yem_partisreplace", false);
                }
            }

            if (isComplete) {
//                DynamicObject object = SubRelationUtils.querynoAssemblyrep(selectid, yem_pnumber, "Sub", isComplete, yem_completetime);
//                if (object != null) {
//                    newDynObject.set("number", object.getString("yem_entryentity.yem_onumber"));
//                    newDynObject.set("name", object.getString("yem_entryentity.yem_oname"));
//                    newDynObject.set("yem_partenname", object.getString("yem_entryentity.yem_oenname"));
//                    newDynObject.set("yem_qtytext", object.getString("yem_entryentity.yem_oqty"));
//                    newDynObject.set("yem_partisreplace", false);
//                }
            }
            //替换组
            long ReplaceGroupid = SubRelationUtils.queryReplaceGroup(selectid, yem_pnumber, isComplete, yem_completetime);
            if (ReplaceGroupid > 0) {
                newDynObject.set("yem_isrepgroup", true);
            } else {
                newDynObject.set("yem_isrepgroup", false);
            }
            BigDecimal yem_qty = newDynObject.getBigDecimal("yem_partqty");
            newDynObject.set("yem_qtytext", yem_qty.setScale(4, RoundingMode.HALF_UP));
            newDynObject.set("yem_weighttext", newDynObject.getBigDecimal("yem_partweight").setScale(4, RoundingMode.HALF_UP));
            newDynObject.set("yem_pricetext", newDynObject.getBigDecimal("yem_price").setScale(4, RoundingMode.HALF_UP));
        }
        return data;
    }

    public boolean isassat(String etcId) {
        QFilter qFilter = new QFilter("number", QCP.equals, etcId);
        qFilter.and(new QFilter("yem_entryentity.yem_iscomp", QCP.equals, true));
        DynamicObjectCollection query = QueryServiceHelper.query("yem_em_assatlasdet", "id", qFilter.toArray(), null);
        if (query.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 总成查询图册部件明细分录
     *
     * @return
     */
    public List getassatlaspartdet() {
        List list = new ArrayList<>();
        List listreplace = new ArrayList<>();
        listreplace.add("A");
        listreplace.add("B");
        IPageCache cache = this.getPageCache();
        if (cache.get("yem_replacement") != null) {
            yem_replacement = cache.get("yem_replacement").toString();
        }
        if (cache.get("complete") != null) {
            complete = cache.get("complete").toString();
        }
        if (cache.get("isComplete") != null) {
            isComplete = Boolean.valueOf(cache.get("isComplete"));
        }
        if (cache.get("yem_analysistdate") != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
                yem_completetime = sdf.parse(cache.get("yem_analysistdate").toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        QFilter qFilters = new QFilter("number", QCP.equals, selectid);
        if (isComplete) {
//            qFilters.and(new QFilter("yem_entryentity.yem_replace", QCP.not_in, listreplace));
            List getassatlasdet = AtlasUtils.getassatlasdet(selectid, yem_completetime);
            if (getassatlasdet.size() > 0) {
                qFilters.and(new QFilter("yem_entryentity.yem_partnumber", QCP.not_in, getassatlasdet));
            }
        } else {
            qFilters.and(new QFilter("yem_entryentity.yem_partisreplace", QCP.equals, false));
        }
        DynamicObjectCollection yem_em_assatlasdet = QueryServiceHelper.query("yem_em_assatlasdet",
                "yem_entryentity.id,yem_entryentity.yem_replace,yem_entryentity.yem_completetime,yem_entryentity.yem_partnumber"
                , new QFilter[]{qFilters});
        for (int i = 0; i < yem_em_assatlasdet.size(); i++) {
            DynamicObject object = yem_em_assatlasdet.get(i);
            long yem_entryentityid = object.getLong("yem_entryentity.id");
            if (isComplete) {
                String yem_replace = object.getString("yem_entryentity.yem_replace");
                Date completetime = object.getDate("yem_entryentity.yem_completetime");
                if (yem_replace.length() > 0) {
                    //新增
                    if (yem_replace.equals("D")) {
//                    if(yem_completetime.after(completetime)){
                        list.add(yem_entryentityid);
//                    }
                    }
                    if (yem_replace.equals("C") || yem_replace.equals("E")) {
                        if (completetime == null) {
                            list.add(yem_entryentityid);
                        } else {
                            if (yem_completetime.before(completetime) && completetime.before(new Date())) {
                                list.add(yem_entryentityid);
                            }
                        }
                    }
                } else {
                    list.add(yem_entryentityid);
                }
            } else {
                list.add(yem_entryentityid);
            }
        }
        return list;
    }
}
