package yem.wmc.ydn.formplugin.form;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EventObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.IDataEntityType;
import kd.bos.entity.BillEntityType;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.EntryType;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.SubEntryType;
import kd.bos.entity.property.EntryProp;
import kd.bos.entity.property.LinkEntryProp;
import kd.bos.entity.tree.TreeNode;
import kd.bos.form.ClientProperties;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.Search;
import kd.bos.form.control.TreeView;
import kd.bos.form.control.events.SearchEnterEvent;
import kd.bos.form.control.events.SearchEnterListener;
import kd.bos.form.control.events.TreeNodeClickListener;
import kd.bos.form.control.events.TreeNodeEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.util.StringUtils;
import yem.base.common.utils.YEM;

/**
 * 字段选择器-表单插件
 * @description:用于批量选择单据实体字段值
 * @author longh
 * @date 2022年6月27日 下午4:29:21
 */
public class MetaPropertyEdit extends AbstractFormPlugin implements TreeNodeClickListener, SearchEnterListener {
	private static List<String> noPropNames = new ArrayList<>();
	static {
		noPropNames.add("LongProp");
		noPropNames.add("LinkEntryProp");
		noPropNames.add("DynamicLocaleProperty");
	}

	@Override
	public void afterCreateNewData(EventObject e) {
		super.afterCreateNewData(e);
		IFormView view = this.getView();
		FormShowParameter fsp = view.getFormShowParameter();
		String entityKey = (String) fsp.getCustomParam("entityKey");
		Boolean isMulti = fsp.getCustomParam("isMulti") == null ? false : (Boolean) fsp.getCustomParam("isMulti");
		Boolean alone = fsp.getCustomParam("alone") == null ? false : (Boolean) fsp.getCustomParam("alone");
		Collection<String> showKeys = fsp.getCustomParam("showKeys");
		if(StringUtils.isEmpty(entityKey)) {
    		entityKey = "pm_purorderbill";//用于预览展示
    	}
		if(entityKey != null) {
			MainEntityType entityType = EntityMetadataCache.getDataEntityType(entityKey);
			DynamicObjectCollection entryEntity = this.getModel().getDataEntity(true).getDynamicObjectCollection("yem_entryentity");
			entryEntity.clear();
			TreeView tree = (TreeView) view.getControl("yem_treeviewap");
			this.initMetaData(tree, entryEntity, entityType, alone, showKeys);
		}
		Map<String, Object> param = new HashMap<>();
        param.put(ClientProperties.IsMultiSelect, isMulti);
        view.updateControlMetadata("yem_entryentity", param);
	}
	
	private void initMetaData(TreeView tree, DynamicObjectCollection entryEntity, IDataEntityType entityType, boolean alone, Collection<String> showKeys) {
		boolean isInit = false;
		String entityKey = entityType.getName();
		if(!alone || (alone && showKeys.contains(entityKey))) {
			isInit = true;
		}
		if(tree != null) {
			TreeNode node = new TreeNode("", entityKey, entityType.getDisplayName().getLocaleValue());
			node.setIsOpened(true);
			if(entityType instanceof BillEntityType) {
				if(isInit) {
					node.addChild(new TreeNode(entityKey, "head", "单据头"));
				}
				tree.addNode(node);
			}else if(isInit && entityType instanceof EntryType) {
				node.setParentid(entityType.getParent().getName());
				tree.addNode(node);
			}
		}
		List<IDataEntityType> entryTypes = new ArrayList<>();
		for (IDataEntityProperty property : entityType.getProperties()) {
			String number = property.getName();
			String classSimpleName = property.getClass().getSimpleName();
			if(property instanceof EntryProp && !(property instanceof LinkEntryProp)) {
				entryTypes.add(((EntryProp) property).getItemType());
			}else if(isInit && (!noPropNames.contains(classSimpleName) || "id".equals(number))){
				DynamicObject row = entryEntity.addNew();
				String displayName = property.getDisplayName() != null ? property.getDisplayName().getLocaleValue() : 
					"id".equals(number) ? "ID" : "";
				String fullnumber = number;
				String fullname = displayName;
				IDataEntityType parent = property.getParent();
				if(parent instanceof SubEntryType) {
					IDataEntityType grandParent = parent.getParent();
					fullnumber = grandParent.getName() + "." + parent.getName() + "." + fullnumber;
					fullname = grandParent.getDisplayName().getLocaleValue() + "." + parent.getDisplayName().getLocaleValue() + "." + fullname;
				}else if(parent instanceof EntryType) {
					fullnumber = parent.getName() + "." + fullnumber;
					fullname = parent.getDisplayName().getLocaleValue() + "." + fullname;
				}
				row.set("yem_number", number);
				row.set("yem_fullnumber", fullnumber);
				row.set("yem_name", displayName);
				row.set("yem_fullname", fullname);
				row.set("yem_datatype", classSimpleName);
			}
		}
		for (IDataEntityType entryType : entryTypes) {
			initMetaData(tree, entryEntity, entryType, alone, showKeys);
		}
	}
	
	@Override
	public void registerListener(EventObject e) {
		super.registerListener(e);
		this.addClickListeners(new String[]{"btnok"});
		TreeView treeView = this.getControl("yem_treeviewap");
		treeView.addTreeNodeClickListener(this);
		Search searchap = this.getControl("yem_searchap");
		searchap.addEnterListener(this);
	}
	
	@Override
    public void treeNodeClick(TreeNodeEvent e) {
    	String nodeId = e.getNodeId().toString();
    	IFormView view = this.getView();
		FormShowParameter fsp = view.getFormShowParameter();
		String entityKey = (String) fsp.getCustomParam("entityKey");
		Boolean alone = fsp.getCustomParam("alone") == null ? false : (Boolean) fsp.getCustomParam("alone");
		Collection<String> showKeys = fsp.getCustomParam("showKeys") == null ? Collections.emptyList() : fsp.getCustomParam("showKeys");
    	if(StringUtils.isEmpty(entityKey)) {
    		entityKey = "pm_purorderbill";//用于预览展示
    	}
    	MainEntityType entityType = EntityMetadataCache.getDataEntityType(entityKey);
		DynamicObjectCollection entryEntity = this.getModel().getDataEntity(true).getDynamicObjectCollection("yem_entryentity");
		entryEntity.clear();
		List<String> showList = new ArrayList<>();
		if(nodeId.equals(entityKey) && !alone) {
			this.initMetaData(null, entryEntity, entityType, false, showList);
		}else {
			if(nodeId.equals(entityKey) && alone) {
				showList.addAll(showKeys);
	    	}else if(nodeId.equals("head")){
	    		showList.add(entityKey);
	    	}else {
	    		showList.add(nodeId);
	    	}
			this.initMetaData(null, entryEntity, entityType, true, showList);
		}
		view.updateView("yem_entryentity");
    }
	
	@Override
	public void search(SearchEnterEvent e) {
		String text = e.getText();
		IFormView view = this.getView();
		view.updateView("yem_entryentity");
		DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("yem_entryentity");
		EntryGrid grid = (EntryGrid) view.getControl("yem_entryentity");
		if (YEM.isNotEmpty(text)) {
			List<Integer> indexs = new ArrayList<>();
			for (int rowIndex = 0; rowIndex < entryEntity.size(); ++rowIndex) {
				DynamicObject o = entryEntity.get(rowIndex);
				if (o.getString("yem_number").contains(text) || o.getString("yem_name").contains(text)) {
					indexs.add(rowIndex);
				}
			}
			if (indexs.isEmpty()) {
				view.showTipNotification("未找到符合条件的数据。");
			} else {
				int[] rowIndexes = indexs.stream().mapToInt(Integer::valueOf).toArray();
				grid.setRowBackcolor("#eff3fd", rowIndexes);
				grid.focusCell(rowIndexes[0], "yem_number");
			}
		}
	}
	
	@Override
	public void click(EventObject evt) {
		super.click(evt);
		String key = ((Control) evt.getSource()).getKey();
		switch (key) {
		case "btnok" :
			IFormView view = this.getView();
			EntryGrid entry = view.getControl("yem_entryentity");
			int[] selectRowIndexs = entry.getSelectRows();
			if(selectRowIndexs.length > 0) {
				DynamicObjectCollection selectRows = new DynamicObjectCollection();
				for (int i : selectRowIndexs) {
					selectRows.add(this.getModel().getEntryRowEntity("yem_entryentity", i));
				}
				view.returnDataToParent(selectRows);
				view.close();
			}else {
				view.showTipNotification("未选择数据。");
			}
			break;
		default:
			break;
		}
	}

}
