package com.yem.em.dynamic;

import com.alibaba.fastjson.JSONObject;
import com.yem.wm.utils.StringUtils;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.report.CellStyle;
import kd.bos.entity.tree.TreeNode;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.IPageCache;
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.field.TextEdit;
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 kd.bos.servicehelper.operation.OperationServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author zhouc
 * @date 2023/8/29 15:23
 * @className NewEpcdynamicEdit
 * @description 设备电子目录_动态表单插件
 * 废弃原【EpcdynamicEdit】方法
 */
public class NewEpcdynamicEdit extends AbstractFormPlugin implements TreeNodeClickListener, CellClickListener, BeforeBindDataListener {
    private String selectid = "1";
    private String atlasid = "";
    private String complete = "";

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        EmptData();
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> customParas = showParameter.getCustomParams();
        TreeNode Cliknode = null;
        if (customParas.containsKey("parentpageid")) {
            IPageCache cache = this.getPageCache();
            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")) {
            IPageCache cache = this.getPageCache();
            if (customParas.get("complete") != null) {
                cache.put("complete", customParas.get("complete").toString());
            }
        }

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

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        IDataModel model = this.getModel();
        String key = e.getOperateKey();
        FormDataModel billModel = (FormDataModel) this.getModel();
        IPageCache pageCache = this.getPageCache();
        if ("insertcarshop".equals(key)) {
            int row = model.getEntryCurrentRowIndex("yem_billlistap");
            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();
                        int Success = UpdateShopcartbill(KeyValue);
                        if (Success > 0) {
                            String parentpageid = pageCache.get("parentpageid");
                            if (parentpageid != null) {
                                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});

                                IFormView childView = this.getView().getView(parentpageid);
                                Label lab = childView.getControl("yem_labelap2");
                                TextEdit yem_textfield = childView.getControl("yem_textfield");
                                String textfield = yem_textfield.getView().getModel().getValue("yem_textfield").toString();
                                if (StringUtils.isEmpty(textfield)) {
                                    lab.setText(yem_em_shopcartbill.size() + "");
                                    yem_textfield.getView().getModel().setValue("yem_textfield", "1");
                                } else {
                                    int labelap2 = Integer.valueOf(textfield) + 1;
                                    lab.setText(yem_em_shopcartbill.size() + "");
                                    yem_textfield.getView().getModel().setValue("yem_textfield", labelap2);
                                }
                                this.getView().sendFormAction(childView);
                                this.getView().showSuccessNotification(ResManager.loadKDString("加入购物车成功！", "EtcmanualEdit_10", "yem_em_equipment"));
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 更新我的购物车
     *
     * @param KeyValue 设备零件明细(新)内码
     */
    public int UpdateShopcartbill(String KeyValue) {
        long currentUserId = YEM.getCurrentUserId();
        //1.根据设备零件内码获取设备零件信息
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(KeyValue, "yem_em_part");
        if (dynamicObject != null) {
            String yem_pnumber = dynamicObject.getString("yem_pnumber");
            //2.根据设备零件编码和当前用户获取时候新增单据
            QFilter qFilter = new QFilter("yem_pnumber", QCP.equals, yem_pnumber);
            qFilter.and(new QFilter("yem_user.id", QCP.equals, currentUserId));
            qFilter.and(new QFilter("yem_shoppingstatus", QCP.equals, "N"));
            DynamicObject shopcartbill = BusinessDataServiceHelper.loadSingle("yem_em_shopcartbill", "id,number,yem_qty,yem_partid", new QFilter[]{qFilter});
            if (shopcartbill != null) {
                //更新 数量 零件内码
                DynamicObject yem_em_shopcartbill = BusinessDataServiceHelper.loadSingle(shopcartbill.getString("id"), "yem_em_shopcartbill");
                if (yem_em_shopcartbill != null) {
                    BigDecimal yem_qty = yem_em_shopcartbill.getBigDecimal("yem_qty");
                    yem_em_shopcartbill.set("yem_qty", yem_qty.add(new BigDecimal(1)));
                    OperationResult Operate = OperationServiceHelper.executeOperate("save", yem_em_shopcartbill.getDynamicObjectType().getName(), new DynamicObject[]{yem_em_shopcartbill}, OperateOption.create());
                    if (Operate.isSuccess()) {
                        return 1;
                    }
                }
            } else {
                //新增购物车底表
                return AddShopcartbill(dynamicObject, currentUserId);
            }
        }
        return 0;
    }

    /**
     * 新增我的购物车
     *
     * @param dynamicObject 设备零件明细(新)内码
     * @param currentUserId 当前用户
     */
    public int AddShopcartbill(DynamicObject dynamicObject, long currentUserId) {
        MainEntityType type = EntityMetadataCache.getDataEntityType("yem_em_shopcartbill");
        DynamicObject carShop = new DynamicObject(type);
        carShop.set("enable", "1");
        carShop.set("status", "A");
        carShop.set("number", dynamicObject.getString("number"));
        carShop.set("name", dynamicObject.getString("name"));
        carShop.set("yem_pnumber", dynamicObject.getString("yem_pnumber"));
        carShop.set("yem_enname", dynamicObject.getString("yem_enname"));
        carShop.set("yem_materielmodel", dynamicObject.getString("yem_materielmodel"));
        carShop.set("yem_qty", new BigDecimal(1));
        carShop.set("yem_user", currentUserId);
        carShop.set("yem_date", new Date());
        carShop.set("yem_partid", dynamicObject.getLong("id"));
        carShop.set("yem_shoppingstatus", "N");
        OperationResult Operate = OperationServiceHelper.executeOperate("save", carShop.getDynamicObjectType().getName(), new DynamicObject[]{carShop}, OperateOption.create());
        if (Operate.isSuccess()) {
            return 1;
        }
        return 0;
    }

    /**
     * 监听事件
     *
     * @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 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);
        }
    }

    @Override
    public void cellDoubleClick(CellClickEvent cellClickEvent) {

    }

    /**
     * 树点击事件
     *
     * @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();
            if (StringUtils.isNotEmpty(selectNodeId)) {
                if (cache.get("complete") != null) {
                    complete = cache.get("complete").toString();
                }
                selectid = selectNodeId;
                Getgroupdata(selectNodeId, "0", "", "");
                this.getView().updateView("yem_billlistap");
            }
        }
    }

    /**
     * 构建树结构
     *
     * @param customParas 入参
     */
    public void GetTreeView(Map<String, Object> customParas,TreeNode node) {
        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();
        }
        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 (StringUtils.isNotEmpty(etcId)) {
            List<TreeNode> list = new ArrayList<TreeNode>();
            QFilter qFilter = new QFilter("yem_equipmentlistid", QCP.equals, Long.valueOf(etcId));
            QFilter qFilter1 = new QFilter("enable", QCP.equals, "1");
            QFilter qFilter3 = new QFilter("status", QCP.equals, "C");
            //查询设备部件（新）
            String componentid = "";
            String ordreby="";
            if(etcId.equals("1766722784202875904")){
                ordreby="longnumber desc";
            }
            else{
                ordreby="longnumber";
            }
            DynamicObject[] etcmanualsub = BusinessDataServiceHelper.load("yem_em_component", "id,number,name,parent,level,longnumber",
                    new QFilter[]{qFilter, qFilter1, qFilter3}, ordreby);//,qFilter2
//            DynamicObjectCollection etcmanualsub = QueryServiceHelper.query("yem_em_component", "id,number,name,parent,level,longnumber", new QFilter[]{qFilter, qFilter1, qFilter3}, "longnumber");
            if (etcmanualsub.length > 0) {
                for (int i = 0; i < etcmanualsub.length; i++) {
                    DynamicObject component = etcmanualsub[i];
                    DynamicObject parent = component.getDynamicObject("parent");
                    if (parent == null) {
                        componentid = component.getString("id");
                        list.add(new TreeNode(null, component.getString("id"), component.getString("name"), true));
//                        list.add(new TreeNode(etcId, component.getString("id"), component.getString("name"), true));
                    } else {
                        list.add(new TreeNode(parent.getString("id"), component.getString("id"), component.getString("name")));
                    }
                }
                //根据整机编号获取设备电子目录看是否存在加装
                if (StringUtils.isNotEmpty(complete)) {
                    QFilter qFilterdev = new QFilter("yem_framenumber", QCP.equals, complete);
                    DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_em_devicefiles", "id,yem_retrofitting", qFilterdev.toArray());
                    if (billType != null) {
                        DynamicObjectCollection yem_retrofitting = billType.getDynamicObjectCollection("yem_retrofitting");
                        if(yem_retrofitting.size()>0){
                            list.add(new TreeNode(componentid, "123245678910", "加装明细"));
                        }
                    }
                }

                TreeView treeView = getControl("yem_treeviewap");
                treeView.addNodes(list);
//                TreeNode node = GetLastNode(list, etcId);
                if (node == null) {
                    node = GetLastNode(list, etcId);
                }
                if (node != null) {
                    treeView.focusNode(node);
                    treeView.checkNode(node);
                    String nodeid = node.getId();
                    treeView.expand(nodeid);
                    treeView.showNode(nodeid);
                    treeView.treeNodeClick(node.getParentid(),node.getId());
                    selectid = nodeid;
                    Getgroupdata(nodeid, "1", etcId, name);
                }
            }
        } else {
            TreeView tv = this.getView().getControl("yem_treeviewap");
            tv.deleteAllNodes();
            TreeNode rootNode = new TreeNode(null, "0", "无数据", true);
            tv.addNode(rootNode);
            tv.checkNode(rootNode);
        }
    }

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

    /**
     * 根据设备部件ID
     * 1.获取设备部件图片
     *
     * @param nodeid 设备部件id
     */
    private void Getgroupdata(String nodeid, String type, String etcId, String name) {
        if (!nodeid.equals("123245678910")) {
            DynamicObject component = BusinessDataServiceHelper.loadSingle(nodeid, "yem_em_component");
            if (component != null) {
                this.getView().getModel().setValue("yem_ecataloggroup", component);
                String imageUrls = component.getString("yem_imageurl");
                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");
            }
        }
    }

    /**
     * 构建图片单据体
     *
     * @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 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 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.equals("123245678910")) {
                QFilter qFilterdev = new QFilter("yem_framenumber", QCP.equals, complete);
                DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_em_devicefiles", "id", qFilterdev.toArray());
                if (billType != null) {
                    DynamicObject devicefiles = BusinessDataServiceHelper.loadSingle(billType.getString("id"), "yem_em_devicefiles");
                    DynamicObjectCollection yem_retrofitting = devicefiles.getDynamicObjectCollection("yem_retrofitting");
                    //重新构建Data
                    DynamicObjectCollection data = reconData(yem_retrofitting);
                    getQueryResult().setCollection(data);
                    getQueryResult().setDataCount(data.size());
                    Setistcardviewap(data);
                    return data;
                }
            } else {
                QFilter qFilters = new QFilter("group.id", QCP.equals, Long.valueOf(selectid));
                DynamicObjectCollection data = QueryServiceHelper.query("yem_em_part", "id, number,name,yem_pnumber,yem_atlasno,yem_enname,yem_materielmodel,yem_remark,yem_qty,yem_qtytext,yem_isreplace,yem_pricetext,yem_weight,yem_weighttext", new QFilter[]{qFilters});
                getQueryResult().setCollection(data);
                getQueryResult().setDataCount(data.size());
                // 把列数据返回
                DynamicObjectCollection datas = DealData(data);
                Setistcardviewap(datas);
                return datas;
            }
            return EmptData();
        }
    }

    /**
     * 重新构建Data
     *
     * @param data 待处理数据包
     * @return 返回数据包
     */
    public DynamicObjectCollection reconData(DynamicObjectCollection data) {
        DynamicObjectCollection NewdataCollection = new DynamicObjectCollection();
        DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject("yem_em_part");
        for (int i = 0; i < data.size(); i++) {
            DynamicObject newDynObject = new DynamicObject(dynamicObject.getDynamicObjectType());
            newDynObject.set("yem_atlasno", i + 1);//图册编号
            newDynObject.set("yem_pnumber", data.get(i).getDynamicObject("yem_materiel").getString("number"));//零件编号
            newDynObject.set("name", data.get(i).getDynamicObject("yem_materiel").getString("name"));//零件名称
            newDynObject.set("yem_enname", "");//英文名称
            newDynObject.set("yem_qtytext", data.get(i).getBigDecimal("yem_qty1").toString());//数量
            newDynObject.set("yem_remark", data.get(i).getString("yem_desc"));//备注
            NewdataCollection.add(newDynObject);
        }
        return NewdataCollection;
    }


    public DynamicObjectCollection EmptData(){
        DynamicObjectCollection NewdataCollection = new DynamicObjectCollection();
        DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject("yem_em_part");
//        for (int i = 0; i < data.size(); i++) {
        DynamicObject newDynObject = new DynamicObject(dynamicObject.getDynamicObjectType());
//            newDynObject.set("yem_atlasno", i + 1);//图册编号
//            newDynObject.set("yem_pnumber", data.get(i).getDynamicObject("yem_materiel").getString("number"));//零件编号
//            newDynObject.set("name", data.get(i).getDynamicObject("yem_materiel").getString("name"));//零件名称
//            newDynObject.set("yem_enname", "");//英文名称
//            newDynObject.set("yem_qtytext", data.get(i).getBigDecimal("yem_qty1").toString());//数量
//            newDynObject.set("yem_remark", data.get(i).getString("yem_desc"));//备注
        NewdataCollection.add(newDynObject);
//        }
        return NewdataCollection;
    }

    /**
     * 处理特殊逻辑
     * 1. 数量
     * 2. 替换件
     *
     * @param data 查询的数据集合
     * @return 返回数据包
     */
    public DynamicObjectCollection DealData(DynamicObjectCollection data) {
        for (int i = 0; i < data.size(); i++) {
            DynamicObject newDynObject = data.get(i);
            BigDecimal yem_qty = newDynObject.getBigDecimal("yem_qty");
            if (yem_qty.compareTo(BigDecimal.ZERO) == 0) {
                newDynObject.set("yem_qtytext", "按需");
            } else {
                newDynObject.set("yem_qtytext", yem_qty.toString());
            }
            BigDecimal yem_weight = newDynObject.getBigDecimal("yem_weight");
            if(yem_weight.compareTo(BigDecimal.ZERO)>0){
                newDynObject.set("yem_weighttext", yem_weight.setScale(4, RoundingMode.HALF_UP));
            }
            //通过零件编码过滤出替换零件编码
            String yem_pnumber = newDynObject.getString("yem_pnumber");
            QFilter qFilter = new QFilter("yem_pnumber", QCP.equals, yem_pnumber);
            qFilter.and(new QFilter("yem_replace1", QCP.not_equals, "C"));
            DynamicObject yem_em_substitution = BusinessDataServiceHelper.loadSingle("yem_em_substitution", "id,yem_tnumber,yem_tname,yem_tenname,yem_tqty", qFilter.toArray());
            if (yem_em_substitution != null) {
                newDynObject.set("yem_pnumber", yem_em_substitution.getString("yem_tnumber"));
                newDynObject.set("name", yem_em_substitution.getString("yem_tname"));
                newDynObject.set("yem_enname", yem_em_substitution.getString("yem_tenname"));
                newDynObject.set("yem_qtytext", yem_em_substitution.getString("yem_tqty"));
                if(!yem_pnumber.equals(yem_em_substitution.getString("yem_tnumber"))){
                    newDynObject.set("yem_isreplace", true);
                }

            }
            //单价：取数逻辑，查询时获取已审核的配件价格库中当前配件编码的最新【标准销售价】；
            QFilter Filter = new QFilter("yem_billtype.number", QFilter.equals, "yem_pricelibrary_PJ");
            Filter.and(new QFilter("billstatus", QFilter.equals, "C"));
            Filter.and(new QFilter("yem_accessory.yem_material.number", QFilter.equals, newDynObject.getString("yem_pnumber")));
            DynamicObjectCollection pricelibrary = QueryServiceHelper.query("yem_pricelibrary",
                    "yem_accessory.yem_standsalesprice",
                    new QFilter[]{Filter},"createtime desc");
            if(pricelibrary.size()>0){
                newDynObject.set("yem_pricetext", pricelibrary.get(0).getBigDecimal("yem_accessory.yem_standsalesprice").setScale(4, RoundingMode.HALF_UP));
            }
        }
        return data;
    }

    /**
     * 给图号单据体赋值
     *
     * @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();
                entryentity.set("yem_atlasnumber", dataObject.get("yem_atlasno"));
                entryentity.set("yem_atlasid", dataObject.get("id"));
            }
        }
        this.getView().updateView("yem_entryentity");
    }

}
