package com.yem.em.ass.dynamic;

import com.alibaba.fastjson.JSONObject;
import com.yem.em.dynamic.NewEpcdynamicEdit;
import com.yem.em.utils.AtlasUtils;
import com.yem.wm.utils.RequestCmmp;
import com.yem.wm.utils.StringUtils;
import com.yem.wm.utils.YEM;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
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.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.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.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.util.ArrayList;
import java.util.EventObject;
import java.util.List;
import java.util.Map;

/**
 * @author zhouc
 * @date 2023/10/31 18:19
 * @className AssepcDynamicEdut
 * @description 总成设备电子目录_动态表单
 */
public class AssepcDynamicEdut extends AbstractFormPlugin implements BeforeBindDataListener, TreeNodeClickListener,CellClickListener {
    private String selectid = "1";
    private String atlasid = "";
    private String complete = "";

    /**
     * 监听事件
     *
     * @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);
        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);
        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();
        }
        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<Map> fromCmmp = null;
            List<TreeNode> list = new ArrayList<TreeNode>();
            list.add(new TreeNode(null, etcId, number, true));
            String accountId = RequestContext.get().getAccountId();
//            //1.根据电子图册编码获取1级部件编码
//            if (!"1483322460718763008".equals(accountId)) {
//                //select distinct ccode from  VIEW_BASE_ITEMSTRUC_WM where pcode='YX635H9A1B1X1A302'
//                String sql = "select distinct " + AtlasUtils.Queryfield("ccode") + "  from VIEW_BASE_ITEMSTRUC_WM where pcode='" + number + "'";
//                fromCmmp = RequestCmmp.getFromCmmp(YEM.getCurrentOrgId(), sql);
//            } else {
//                fromCmmp = AtlasUtils.Getasscomponent();
//            }
//            Map<String, String> stringStringMap = AtlasUtils.GetasscomponentName(fromCmmp,"Ass");
//            for (int i = 0; i < fromCmmp.size(); i++) {
//                Map map = fromCmmp.get(i);
//                if (map != null) {
//                    String ccode = map.get("ccode").toString();//部件编码
//                    Map<String, String> Map = AtlasUtils.GetReplace(ccode);
//                    if(Map.size()>0){
//                        list.add(new TreeNode(etcId, Map.get("yem_pnumber"), Map.get("name")));
//                    }
//                    else{
//                        if (stringStringMap.containsKey(ccode)) {
//                            list.add(new TreeNode(etcId, ccode, stringStringMap.get(ccode)));
//                        } else {
//                            list.add(new TreeNode(etcId, ccode, ccode));
//                        }
//                    }
//                }
//            }
            //根据CMMP明细表构建
            QFilter Filter = new QFilter("number", QFilter.equals, number);
            Filter.and(new QFilter("status", QFilter.equals, "C"));
            DynamicObjectCollection yem_em_cmmptable = QueryServiceHelper.query("yem_em_cmmptable",
                    "yem_entryentity.yem_ccode,yem_entryentity.yem_ccodename",
                    new QFilter[]{Filter}, "yem_entryentity.yem_ccode");
            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_ccode");
                    String ccodename = dynamicObject.getString("yem_entryentity.yem_ccodename");
                    if (StringUtils.isNotEmpty(ccodename) && StringUtils.isNotNull(ccodename)) {
                        list.add(new TreeNode(etcId, ccode, ccodename));
                    } else {
                        list.add(new TreeNode(etcId, ccode, ccode));
                    }
                }
            }
            else{
                list.add(new TreeNode(etcId, "0", "无数据"));
            }
            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 (list.size() > 1) {
            node = list.get(1);
        }
        return node;
    }

    /**
     * 根据设备部件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);
            DynamicObject component = BusinessDataServiceHelper.loadSingle("yem_em_asscomponent", "id,yem_imageurl", qFilter.toArray());
            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");
            }
        }
    }
    @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();
            if (StringUtils.isNotEmpty(selectNodeId)) {
                if (cache.get("complete") != null) {
                    complete = cache.get("complete").toString();
                }
                selectid = selectNodeId;
                Getgroupdata(selectNodeId, "0", "", "");
                this.getView().updateView("yem_billlistap");
                Getsub(treeView, selectNodeId);
            }
        }
    }

    /**
     * 根据编码查询是否有下级
     *
     * @param treeView     树模型
     * @param selectNodeId 点击节点编码
     */
    public void Getsub(TreeView treeView, String selectNodeId) {
        QFilter qFilter = new QFilter("number", QCP.equals, selectNodeId);
        qFilter.and(new QFilter("enable", QCP.equals, "1"));
        DynamicObject[] yem_em_asscomponent = BusinessDataServiceHelper.load("yem_em_asscomponent",
                "id,number,name,parent,level,longnumber",
                new QFilter[]{qFilter}, null);
        if (yem_em_asscomponent.length > 0) {
            DynamicObject parent = yem_em_asscomponent[0].getDynamicObject("parent");
            if (parent == null) {
                QFilter qFilter1 = new QFilter("longnumber", QCP.like, "%" + selectNodeId + "%");
                qFilter1.and(new QFilter("enable", QCP.equals, "1"));
                DynamicObject[] yem_em_asscomponent1 = BusinessDataServiceHelper.load("yem_em_asscomponent",
                        "id,number,name,parent.number,level,longnumber",
                        new QFilter[]{qFilter1}, "longnumber");
                for (int i = 0; i < yem_em_asscomponent1.length; i++) {
                    DynamicObject dynamicObject = yem_em_asscomponent1[i];
                    TreeNode node = null;
                    if (dynamicObject.getString("parent.number") == null) {
                        node = new TreeNode(dynamicObject.getString("parent.number"), dynamicObject.getString("number"), dynamicObject.getString("name"), true);
                    } else {
                        node = new TreeNode(dynamicObject.getString("parent.number"), dynamicObject.getString("number"), dynamicObject.getString("name"));
                    }
                    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.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.number", QCP.equals, selectid);
                DynamicObjectCollection data = QueryServiceHelper.query("yem_em_asspart", "id, number,name,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();
        }
    }

    /**
     * 给图号单据体赋值
     *
     * @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");
    }

    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_asspart");
        for (int i = 0; i < data.size(); i++) {
            DynamicObject newDynObject = new DynamicObject(dynamicObject.getDynamicObjectType());
            newDynObject.set("yem_atlasno", i + 1);//图册编号
            newDynObject.set("number", 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("number");
            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("number", 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("number")));
            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;
    }


}
