package com.yem.ensign.weboffice.dynamic;

import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.FormShowParameter;
import kd.bos.form.control.Button;
import kd.bos.form.control.Control;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.servicehelper.BusinessDataServiceHelper;

/**
 * 动态数据源字段选择表单插件
 *@author hdd
 *@date 2020-08-25 下午3:50:56
 */
public class DyquerydatasouchoiceEdit extends AbstractFormPlugin{

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

		FormShowParameter showParameter = this.getView().getFormShowParameter();
		Map<String, Object> cusMap = showParameter.getCustomParams();
		if(cusMap.containsKey("dyqueryId")) {
			String dyqueryId = cusMap.get("dyqueryId").toString();
			DynamicObject dyquerydatasou = BusinessDataServiceHelper.loadSingle(dyqueryId,"yem_dyquerydatasou");
			if(dyquerydatasou!=null) {
				DynamicObjectCollection srcEntryentitys = dyquerydatasou.getDynamicObjectCollection("yem_entryentity");
				if(srcEntryentitys!=null && srcEntryentitys.size()>0) {
					IDataModel model = this.getModel();
					DynamicObjectCollection entryentitys = model.getEntryEntity("yem_entryentity");
					entryentitys.clear();
					for(int i =0;i<srcEntryentitys.size();i++) {
						DynamicObject entryentity = srcEntryentitys.get(i);
						DynamicObject row = entryentitys.addNew();
						row.set("yem_textfield", entryentity.getString("yem_textfield"));
						row.set("yem_textfieldcn", entryentity.getString("yem_textfieldcn"));
					}
				}
			}
		}
	}
	
	@Override
	public void afterBindData(EventObject e) {
		super.afterBindData(e);
	}
	
	@Override
	public void registerListener(EventObject e) {
		super.registerListener(e);
		Button btnok = this.getView().getControl("btnok");
        if (null != btnok) {
            this.addClickListeners(new String[] {"btnok"});
        }
	}
	
	@Override
	public void click(EventObject evt) {
		Control c = (Control) evt.getSource();
        if ("btnok".equals(c.getKey().toLowerCase())) {
    		IDataModel model = this.getModel();
    		int rowIndex = model.getEntryCurrentRowIndex("yem_entryentity");
    		DynamicObject row = model.getEntryRowEntity("yem_entryentity", rowIndex);
    		String yem_textfield = row.getString("yem_textfield");
    		String yem_textfieldcn = row.getString("yem_textfieldcn");
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("yem_textfield", yem_textfield);
            map.put("yem_textfieldcn", yem_textfieldcn);
            this.getView().returnDataToParent(map);
            this.getView().close();
        }
	}
}
