package com.yem.em.dynamic;

import com.microsoft.schemas.office.visio.x2012.main.TextType;
import com.yem.em.utils.BaseDataFilterUtils;
import com.yem.em.utils.EmptyUtils;
import com.yem.wm.utils.StringUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.IBillModel;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.filter.FilterParameter;
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.ShowType;
import kd.bos.form.cardentry.CardEntry;
import kd.bos.form.container.Container;
import kd.bos.form.control.*;
import kd.bos.form.control.events.*;
import kd.bos.form.events.*;
import kd.bos.form.field.DecimalEdit;
import kd.bos.form.field.PictureEdit;
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.CreateListColumnsListener;
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 javax.xml.soap.Text;
import java.util.*;
import java.util.List;

/**
 * @author zhouc
 * @date 2023/8/24 18:28
 * @className EpcdynamicEdit
 * @description 设备电子目录_动态表单插件 废弃
 */
public class EpcdynamicEdit extends AbstractFormPlugin implements TreeNodeClickListener, CreateListColumnsListener, BeforeBindDataListener, CellClickListener, ClickListener, RowClickEventListener {

    private String selectid = "1";
    private String atlasid = "";

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> customParas = showParameter.getCustomParams();
//        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 (StringUtils.isNotEmpty(etcId)) {
//            List<TreeNode> list = new ArrayList<TreeNode>();
//            QFilter qFilter = new QFilter("yem_equipmentlist.id", QCP.equals, Long.valueOf(etcId));
//            QFilter qFilter1 = new QFilter("enable", QCP.equals, "1");
////            QFilter qFilter2 = new QFilter("parent", QCP.equals, 0);
//            QFilter qFilter3 = new QFilter("status", QCP.equals, "C");
//            list.add(new TreeNode(null, etcId, name, true));
//            //查询设备部件（新）
//            DynamicObject[] etcmanualsub = BusinessDataServiceHelper.load("yem_em_component", "id,number,name,parent,level,longnumber",
//                    new QFilter[]{qFilter, qFilter1, qFilter3}, "longnumber");//,qFilter2
//            if (etcmanualsub.length > 0) {
//                for (int i = 0; i < etcmanualsub.length; i++) {
//                    DynamicObject component = etcmanualsub[i];
//                    DynamicObject parent = component.getDynamicObject("parent");
//                    if (parent == null) {
//                        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")));
//                    }
//                }
//                TreeView treeView = getControl("yem_treeviewap");
//                treeView.addNodes(list);
//                treeView.expand(etcId);
//                TreeNode node = GetLastNode(list, etcId);
//                if (node != null) {
//                    treeView.focusNode(node);
//                    treeView.checkNode(node);
//                    String nodeid = node.getId();
//                    selectid = nodeid;
//                    Getgroupdata(nodeid, "1", etcId, name);
//                    filtrationList(nodeid);
//                }
//            }
//        } else {
//            TreeView tv = this.getView().getControl("yem_treeviewap");
//            tv.deleteAllNodes();
//            TreeNode rootNode = new TreeNode(null, "0", "无数据", true);
//            tv.addNode(rootNode);
//            tv.checkNode(rootNode);
//        }
    }

    @Override
    public void initialize() {
        super.initialize();
        BillList billList = this.getControl("yem_billlistap");
        // 注册监听
        billList.addCreateListColumnsListener(this);
        billList.addBeforeBindDataListener(this);
//        billList.addAfterBindDataListener(this);
    }

    private TreeNode GetLastNode(List<TreeNode> list, String etcId) {
        TreeNode node = null;
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (etcId.equals(list.get(i).getParentid())) {
                    node = list.get(i);
                    break;
                }
            }
        }
        return node;
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        TreeView treeView = this.getView().getControl("yem_treeviewap");
        treeView.addTreeNodeClickListener(this);
        TextEdit yem_atlasnumber = this.getControl("yem_atlasnumber");
        yem_atlasnumber.addClickListener(this);
        CardEntry yem_entryentity = this.getView().getControl("yem_entryentity");
        yem_entryentity.addCellClickListener(this);

        PictureEdit yem_picturefield = this.getView().getControl("yem_picturefield");
        yem_picturefield.addItemClickListener(this);

        CardEntry yem_entryentity1 = this.getView().getControl("yem_entryentity1");
        yem_entryentity1.addCellClickListener(this);
        this.addClickListeners("yem_picturefield");
    }

    @Override
    public void entryRowClick(RowClickEvent evt) {
        RowClickEventListener.super.entryRowClick(evt);
        CardEntry cardEntry = (CardEntry) evt.getSource();
        String key = cardEntry.getKey();
    }


    /**
     * 树点击事件
     *
     * @param evt 上下文
     */
    @Override
    public void treeNodeClick(TreeNodeEvent evt) {
        TreeNodeClickListener.super.treeNodeClick(evt);
        TreeView treeView = (TreeView) evt.getSource();
        if (treeView.getKey().equals("yem_treeviewap")) {
            String selectNodeId = evt.getNodeId().toString();
            if (StringUtils.isNotEmpty(selectNodeId)) {
                int name = evt.getRowKey();
                selectid = selectNodeId;
                this.getView().updateView("yem_billlistap");
                Getgroupdata(selectNodeId, "0", "", "");//
                QFilter qFilters = new QFilter("group.id", QCP.equals, Long.valueOf(selectid));
                DynamicObjectCollection data = QueryServiceHelper.query("yem_em_part", "id, number,name,yem_atlasno,yem_enname,yem_materielmodel,yem_remark,yem_qty",
                        new QFilter[]{qFilters});
                Setistcardviewap(data);
            }
        }
    }

    /**
     * 根据设备部件ID
     * 1.获取设备部件图片
     *
     *
     * @param nodeid 设备部件id
     */
    private void Getgroupdata(String nodeid, String type, String etcId, String name) {
        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");
        }
    }

    /**
     *  根据上级分组id过滤单据列表
     *  2.根据设备部件内码获取设备零件明细(新)
     * @param nodeid 设备部件内码
     */
    public void  filtrationList(String nodeid){
        BillList yem_billlistap = getControl("yem_billlistap");
        QFilter qFilters = new QFilter("group.id", QCP.equals, Long.valueOf(nodeid));
        FilterParameter FilterParameter = new FilterParameter(qFilters, "asec");
        FilterParameter.setFilter(qFilters);
        yem_billlistap.setFilterParameter(FilterParameter);//加载有筛选条件的单据列表
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();

    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        Control c = (Control) evt.getSource();
        String key = c.getKey().toLowerCase();
        if (key.equals("yem_atlasnumber")) {

        }
    }

    @Override
    public void beforeClick(BeforeClickEvent evt) {
        super.beforeClick(evt);
        Control c = (Control) evt.getSource();
        String key = c.getKey().toLowerCase();
        if (key != null) {

        }
    }

    @Override
    public void beforeBindData(BeforeBindDataEvent beforeBindDataEvent) {
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> customParas = showParameter.getCustomParams();
        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 (StringUtils.isNotEmpty(etcId)) {
            List<TreeNode> list = new ArrayList<TreeNode>();
            QFilter qFilter = new QFilter("yem_equipmentlist.id", QCP.equals, Long.valueOf(etcId));
            QFilter qFilter1 = new QFilter("enable", QCP.equals, "1");
//            QFilter qFilter2 = new QFilter("parent", QCP.equals, 0);
            QFilter qFilter3 = new QFilter("status", QCP.equals, "C");
            list.add(new TreeNode(null, etcId, name, true));
            //查询设备部件（新）
            DynamicObject[] etcmanualsub = BusinessDataServiceHelper.load("yem_em_component", "id,number,name,parent,level,longnumber",
                    new QFilter[]{qFilter, qFilter1, qFilter3}, "longnumber");//,qFilter2
            if (etcmanualsub.length > 0) {
                for (int i = 0; i < etcmanualsub.length; i++) {
                    DynamicObject component = etcmanualsub[i];
                    DynamicObject parent = component.getDynamicObject("parent");
                    if (parent == null) {
                        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")));
                    }
                }
                TreeView treeView = getControl("yem_treeviewap");
                treeView.addNodes(list);
                treeView.expand(etcId);
                TreeNode node = GetLastNode(list, etcId);
                if (node != null) {
                    treeView.focusNode(node);
                    treeView.checkNode(node);
                    String nodeid = node.getId();
                    selectid = nodeid;
                    Getgroupdata(nodeid, "1", etcId, name);
                    filtrationList(nodeid);
                }
            }
        } else {
            TreeView tv = this.getView().getControl("yem_treeviewap");
            tv.deleteAllNodes();
            TreeNode rootNode = new TreeNode(null, "0", "无数据", true);
            tv.addNode(rootNode);
            tv.checkNode(rootNode);
        }
        BillList billList = this.getControl("yem_billlistap");
        billList.addCreateListDataProviderListener(new CreateListDataProviderListener() {
            @Override
            public void createListDataProvider(BeforeCreateListDataProviderArgs args) {
                args.setListDataProvider(new BillListDataProvider());
            }
        });
//        this.getView().updateView("yem_billlistap");
    }

    @Override
    public void cellClick(CellClickEvent e) {
//        String key = e.getFieldKey();
        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();
        BillList bl = this.getControl("yem_billlistap");
        ListSelectedRowCollection rowList = bl.getCurrentListAllRowCollection();
        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);
                }
            }
        }
        bl.setCellStyle(cslist);
    }

    @Override
    public void cellDoubleClick(CellClickEvent e) {
        String key = e.getFieldKey();
        if (key != null) {

        }

    }

    @Override
    public void createListColumns(BeforeCreateListColumnsArgs beforeCreateListColumnsArgs) {

    }


    // 内部类，为单据列表控件添加值
    public class BillListDataProvider extends ListDataProvider {
        @Override
        public DynamicObjectCollection getData(int start, int limit) {
            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",
                    new QFilter[]{qFilters});
            getQueryResult().setCollection(data);
            getQueryResult().setDataCount(data.size());
            // 把列数据返回
            Setistcardviewap(data);
            return data;
        }
    }

    public void Setistcardviewap(DynamicObjectCollection data) {
        //获取卡片控件
        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 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");
    }
}
