package yem.wm.cm.ht.dynamic;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.utils.StringUtils;
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 kd.bos.servicehelper.BusinessDataServiceHelper;

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

/**
 * 基础资料动态表单
 * @author zhangh
 *
 */
public class BaseDataSelectEdit 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);
	}

	@Override
	public void afterCreateNewData(EventObject e) {
		IDataModel model = this.getModel();
		String billkey = (String) this.getView().getFormShowParameter().getCustomParams().get("billkey");//获取主实体对象单据名
		if (StringUtils.isNotEmpty(billkey)) {
			DynamicObject[] bills = BusinessDataServiceHelper.load(billkey, "id,name,number", null);
			int[] rowIndexs = model.batchCreateNewEntryRow(this.entryKey, bills.length);
			int i = 0;
			for (DynamicObject bill : bills) {
				LocaleString locStr = new LocaleString();
				locStr.setLocaleValue_zh_CN((String) (String) bill.getLocaleString("name").getLocaleValue_zh_CN());
				locStr.setLocaleValue_en((String)bill.getLocaleString("name").getLocaleValue_en());
				model.setValue("yem_fcaption", locStr, rowIndexs[i]);
				model.setValue("yem_fvalue", bill.getString("number"), rowIndexs[i]);
				model.setValue("yem_baseid", bill.getString("id"), rowIndexs[i]);
				++i;
			}
		}
	}
	
	@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[] selectRows = entryGrid.getSelectRows();
		List<DynamicObject> list = new ArrayList<>();
		for (int rowIndex : selectRows) {
			DynamicObject entryRowEntity = this.getModel().getEntryRowEntity("yem_entryentity", rowIndex);
			list.add(entryRowEntity);
		}
		
		this.getView().returnDataToParent(list);
		this.getView().close();
	}
	
	@Override
	public void entryRowDoubleClick(RowClickEvent evt) {
		this.returnData();
		this.getView().close();
	}
}
