package yem.wm.cm.ht.dynamic;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.events.ClickListener;
import kd.bos.form.control.events.RowClickEvent;
import kd.bos.form.control.events.RowClickEventListener;
import kd.bos.form.plugin.AbstractFormPlugin;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
import java.util.Map;

/**
 * 下拉列表选择(动态表单)
 * @author zhangh
 *
 */
public class ComboItemsSelectEdit extends AbstractFormPlugin implements ClickListener, RowClickEventListener{
	String entryKey = "yem_entryentity";
	
	@Override
	public void initialize() {
		this.addClickListeners(new String[]{"yem_btnok"});
		EntryGrid entryGrid = (EntryGrid) this.getView().getControl("yem_entryentity");
		entryGrid.addRowClickListener((RowClickEventListener) this);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void afterCreateNewData(EventObject e) {
		Object value = this.getView().getFormShowParameter().getCustomParams().get("comboProp");
		List<Map<String, Object>> items = (List<Map<String, Object>>) (value instanceof List ? value : new ArrayList<>());
		if (items != null && items.size() > 0) {
			IDataModel model = this.getModel();
			int[] rowIndexs = model.batchCreateNewEntryRow(this.entryKey, items.size());
			int i = 0;
			for (Map<String, Object> item : items) {
				model.setValue("yem_fimagekey", item.get("ImageKey"), rowIndexs[i]);
				LocaleString locStr = new LocaleString();
				locStr.setLocaleValue_zh_CN((String) item.get("CnName"));
				locStr.setLocaleValue_en((String) item.get("EnName"));
				model.setValue("yem_fcaption", locStr, rowIndexs[i]);
				model.setValue("yem_fvalue", item.get("Value"), rowIndexs[i]);
				++i;
			}
		}
		this.getPageCache().put("value", SerializationUtils.toJsonString((Object) items));
	}
	
	@Override
	public void click(EventObject evt) {
		String key =((Control) evt.getSource()).getKey();
		switch (key) {
			case "yem_btnok" : {
				this.returnData();
				break;
			}
		}
	}

	private void returnData() {
		EntryGrid entryGrid = (EntryGrid) this.getView().getControl("yem_entryentity");
		int rowIndex = entryGrid.getEntryState().getFocusRow();
		DynamicObject entryRowEntity = this.getModel().getEntryRowEntity("yem_entryentity", rowIndex);
		this.getView().returnDataToParent(entryRowEntity);
		this.getView().close();
	}
	
	@Override
	public void entryRowDoubleClick(RowClickEvent evt) {
		this.returnData();
		this.getView().close();
	}

}
