package cn.net.connor.std.processedit.choose;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.util.Registry;

import cn.net.connor.std.aifrcp.KDialogController;
import cn.net.connor.std.aifrcp.util.KUtil;
import cn.net.connor.std.processedit.util.KExcelTable;
import cn.net.connor.std.processedit.util.KExcelTable.Config;
import cn.net.connor.std.processedit.util.PrefComponent;

public class ChooseDialogController extends KDialogController {

	private String typeName;
	private String[] config;
	private List<PrefComponent> prefComponents;
	// private Map<String, JTextComponent> otherComps;
	private ChooseDialog dialog;
	protected File excelFile;
	protected List<Config> configs = new ArrayList<Config>();
	protected List<String> searchCols = new ArrayList<String>();
	protected Map<String, JTextField> searchComps = new HashMap<String, JTextField>();
	protected KExcelTable tableBean;
	protected boolean isNHJSChooseSafeDesc = false;
	private static final String PREFIX_NHJS_CHOOSE_SAFE_DESC = "#NHJS_SAFE_DESC#";
	private static final Registry REG = Registry.getRegistry(ChooseDialogController.class);

	public ChooseDialogController(AbstractAIFApplication app, String type, PrefComponent bean, List<PrefComponent> prefComponents) {
		this.typeName = type;
		this.config = bean.getExcelConfig();
		this.prefComponents = prefComponents;
	}

	@Override
	public boolean init() throws Exception {
		this.dialog = (ChooseDialog) aifDialog;
		int len = KUtil.getLen(config);
		if (len == 0) {
			System.out.println("No Choose Config");
			throw new TCException(REG.getString("novalidchooseconfig.ERROR"));
		}
		String uid = config[0];
		this.isNHJSChooseSafeDesc = uid.startsWith(PREFIX_NHJS_CHOOSE_SAFE_DESC);
		if(this.isNHJSChooseSafeDesc) {
			uid = uid.substring(PREFIX_NHJS_CHOOSE_SAFE_DESC.length());
		}
		System.out.println(">> Uid: " + uid);
		if (!KUtil.isEmpty(typeName)) {
			int ind = uid.indexOf("" + typeName + ":");
			if (ind > 0) {
				uid = uid.substring(ind + typeName.length() + 1);
			}
		}
		int ind = uid.indexOf(';');
		if (ind > 0) {
			uid = uid.substring(0, ind);
		}
		System.out.println(">> Uid for type [" + typeName + "] is: " + uid);
		if (KUtil.isEmpty(uid)) {
			throw new TCException(REG.getString("novalidchooseconfig.ERROR"));
		}
		TCComponentDataset excelDataset = null;
		try {
			excelDataset = (TCComponentDataset) session.stringToComponent(uid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (excelDataset == null || !"MSExcelX".equals(excelDataset.getType())) {
			throw new TCException(REG.getString("novalidchooseconfig.ERROR"));
		}
		// Read Config
		for (int i = 1; i < len; i++) {
			String pref = config[i];
			String[] split = pref.split("=", -1);
			int splitCnt = KUtil.getLen(split);
			String tableCol = null, excelCol = null, propConfig = null;
			int prefW = 100;
			if (splitCnt > 0) {
				tableCol = split[0];
			}
			if (splitCnt > 1) {
				excelCol = split[1];
			}
			if (splitCnt > 2) {
				propConfig = split[2];
			}
			if (splitCnt > 3) {
				try {
					prefW = Integer.parseInt(split[3]);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (!KUtil.isEmpty(tableCol) && !KUtil.isEmpty(excelCol)) {
				if (tableCol.startsWith("#")) {
					tableCol = tableCol.substring(1);
					System.out.println(">> Add Search: " + tableCol);
					if (!this.searchCols.contains(tableCol)) {
						this.searchCols.add(tableCol);
					}
				}
				this.configs.add(new Config(tableCol, excelCol, propConfig, prefW));
			} else {
				System.out.println("ERROR Config: " + pref);
			}
		}
		this.excelFile = KUtil.getDatasetFile(excelDataset);
		if (this.excelFile == null || !this.excelFile.exists()) {
			throw new TCException(REG.getString("novalidchooseconfig.ERROR"));
		}
		this.tableBean = new KExcelTable(configs, excelFile.getAbsolutePath(), this.isNHJSChooseSafeDesc);
		return true;
	}

	public void doSearch() throws Exception {
		Map<String, String> searchInfo = new HashMap<String, String>();
		System.out.println("Perform Search..");
		for (String colName : this.searchComps.keySet()) {
			String value = this.searchComps.get(colName).getText();
			if (!KUtil.isEmpty(value)) {
				System.out.println(">> " + colName + " = " + value);
				searchInfo.put(colName, value);
			}
		}
		this.tableBean.performSearch(searchInfo);
	}

	public void doSelect() throws Exception {
		LinkedHashMap<Config, String> data = this.tableBean.getSelectedData();
		if (data == null || data.size() <= 0) {
			System.out.println("No Select Info");
			dialog.disposeDialog();
			return;
		}
		System.out.println("Selected Row: " + Arrays.toString(data.values().toArray()));
		for (Config colConfig : data.keySet()) {
			String val = data.get(colConfig);
			String addition = colConfig.getAdditionalInfo();
			if (KUtil.isEmpty(addition)) {
				continue;
			}
			System.out.println(">> Set " + addition + " = " + val);
			for (PrefComponent comp : this.prefComponents) {
				if (addition.equals(comp.getPropConfig())) {
					System.out.println(comp.getValueComp());
					if (comp.getValueComp() instanceof JTextArea) {
						// 安全说明进行追加
						JTextArea textArea = (JTextArea) comp.getValueComp();
						textArea.setText(textArea.getText() + val);
					} else {
						comp.setValue(val);
					}
				}
			}
		}
		dialog.disposeDialog();
	}

}
