package cn.net.connor.createTempDrawings.dialogs;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.*;

import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.DateButton;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;
import com.teamcenter.rac.util.UIUtilities;

public class CreateTempDrawingDialog extends JFrame implements ActionListener{
	private AbstractAIFApplication application;
	private TCSession tcSession ;
	private InterfaceAIFComponent selectComponent;
	private JLabel drawingObjTypeLabel;//图纸对象类型标签
	private JComboBox<String> drawingObjTypeComboBox;//图纸对象类型下拉输入框
	private JButton okButton;//确认按钮
	private JButton button1;//按钮
	private JButton button2;//按钮
	private List<String> drawingObjTypeInfos = new ArrayList<String>();//首选项中配置的对象类型信息
	private JFrame buildFram;
	private String currentChoosePropPreferenceName;//当前选中类型的
	private JLabel idLabel;
	private JTextField idTextField;
	private JLabel revLabel;
	private JComboBox<String> revComboBox;
	private List<String> showPropsInfoList = new ArrayList<>();
	private JButton closeButton;
	private JButton buildButton;
	// 添加日期格式化工具
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 属性组件集合
	 */
	private Map<String,JComponent> propComponentMap = new HashMap<>();
	

	/**
	 * 类构造函数
	 * @param application
	 * @param selectComponent
	 */
	public CreateTempDrawingDialog(AbstractAIFApplication application, InterfaceAIFComponent selectComponent) {
		try {
			this.application = application;
			this.tcSession = (TCSession) this.application.getSession();
			this.selectComponent = selectComponent;
			
			System.out.println("开始加载创建临时图纸面板！");
			List<String> list1 = getPreferenceInfos("SB6_Create_LS_Design");
			if (list1.isEmpty() || list1.size() <= 0) {
				MessageBox.post("获取首选项SB6_Create_LS_Design配置信息失败，请检查配置是否正确！" , "提示", MessageBox.INFORMATION);
				return;
			}else {
				if (this.drawingObjTypeInfos != null && this.drawingObjTypeInfos.size() > 0) {
					this.drawingObjTypeInfos.clear();
				}
				this.drawingObjTypeInfos.addAll(list1);
			}
			initUI();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}

	/**
	 * 根据首选项名称获取首选项配置信息
	 * @param preferenceName 首选项名称
	 * @return List<String>
	 */
	public List<String> getPreferenceInfos(String preferenceName) {
		List<String> drawingObjPropInfosList = new ArrayList<>();
		TCPreferenceService preferenceService = tcSession.getPreferenceService();
		String[] values = preferenceService.getStringValues(preferenceName);
		if (values != null && values.length > 0) {
			for (int i = 0; i < values.length; i++) {
				drawingObjPropInfosList.add(values[i]);
			}
		}else {
			System.out.println("获取首选项["+preferenceName+"]配置信息失败，请检查配置是否正确！");
		}
		System.out.println("共获取到首选项["+preferenceName+"]中的["+values.length+"]条配置信息");
		return drawingObjPropInfosList;

	}

	/**
	 * 创建临时图纸对象-选择类型的看板
	 */
	private void initUI() throws Exception {
		this.setTitle("请选择图纸类型");
		this.setSize(400, 500);
        this.setLayout(new BorderLayout());

        JPanel centerPanel = new JPanel(new GridBagLayout());
		JPanel buttomPanel = new JPanel(new FlowLayout());
		
		this.drawingObjTypeLabel = new JLabel("图纸对象类型		");
		//获取图纸对象类型
		List<String> typList = getDrawingObjTypeShowName();
		if (typList.isEmpty() || typList.size() <= 0) {
			System.out.println("获取图纸对象类型失败，请检查相关首选项是否配置正确！");
			return;
		}
		String[] drawingTypes = typList.toArray(new String[0]);
		this.drawingObjTypeComboBox = new JComboBox<String>(drawingTypes);
		drawingObjTypeComboBox.setPreferredSize(new Dimension(200, drawingObjTypeComboBox.getPreferredSize().height));
		drawingObjTypeComboBox.setEditable(false);

		GridBagConstraints gbc = new GridBagConstraints();
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.anchor = GridBagConstraints.WEST;
		gbc.insets = new Insets(0, 0, 0, 12); // 右边留出 10 像素的间距
		centerPanel.add(this.drawingObjTypeLabel, gbc);

		gbc.gridx = 1;
		centerPanel.add(drawingObjTypeComboBox, gbc);

		this.okButton = new JButton("确认");
		buttomPanel.add(okButton);
		

		//构造主面板
		this.add(centerPanel, BorderLayout.CENTER);
		this.add(buttomPanel, BorderLayout.SOUTH);
		
		
		//按钮时间监听
		this.okButton.addActionListener(this);
		
		

		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		this.setResizable(true);
  		this.setPreferredSize(new Dimension(800,600));
  		this.pack(); // 自动调整窗口大小以适应内部组件

		//放到屏幕中央
		UIUtilities.centerToScreen(this);
		
		this.setVisible(true);

	}

	/**
	 * 获取创建临时图纸对象时，选择类型界面的类型名称集合
	 * @return List<String>
	 */
	private List<String> getDrawingObjTypeShowName() {
		List<String> drawingObjTypeList = new ArrayList<>();
		if (this.drawingObjTypeInfos != null && this.drawingObjTypeInfos.size() > 0){
			for (int i = 0; i < this.drawingObjTypeInfos.size(); i++) {
				String drawingObjTypeInfo = this.drawingObjTypeInfos.get(i);
				String[] drawingObjTypeInfoArray = drawingObjTypeInfo.split("=");
				if (drawingObjTypeInfoArray.length == 3) {//配置的信息中只有两个=符号
					drawingObjTypeList.add(drawingObjTypeInfoArray[0]);
				}else{
					System.out.println("配置信息：["+drawingObjTypeInfo+"]格式不正确，请检查相关首选项是否配置正确！");
				}
			}
		}

		return drawingObjTypeList;
	}

	/**
	 * 获取选中的图纸类型对应的首选项名称
	 * @return
	 */
	private String getSelectTypePreferenceName() {
		String returnValue = null;
		//当前选中的图纸类型
		String chooseType1 = (String) this.drawingObjTypeComboBox.getSelectedItem();

		List<String> drawingObjTypeList = new ArrayList<>();
		if (this.drawingObjTypeInfos != null && this.drawingObjTypeInfos.size() > 0){
			for (int i = 0; i < this.drawingObjTypeInfos.size(); i++) {
				String drawingObjTypeInfo = this.drawingObjTypeInfos.get(i);
				String[] drawingObjTypeInfoArray = drawingObjTypeInfo.split("=");
				if (drawingObjTypeInfoArray.length == 3) {//配置的信息中只有两个=符号
					//遍历到的类型名称
					String typeName = drawingObjTypeInfoArray[0];
					if (chooseType1 != null && typeName != null){
						if (chooseType1.equals(typeName)) {
							returnValue = drawingObjTypeInfoArray[2];
							break;
						}
					}
				}else{
					System.out.println("配置信息：["+drawingObjTypeInfo+"]格式不正确，请检查相关首选项是否配置正确！");
				}
			}
		}

		return returnValue;
	}
	
	

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO 自动生成的方法存根
		Object s = e.getSource();
		try {
			if (s.equals(this.okButton)) {
				String chooseType = (String) this.drawingObjTypeComboBox.getSelectedItem();
				System.out.println("当前选中图纸对象类型="+chooseType);
				// 关闭当前窗口
				this.dispose();
				buildDrawingObjTypeFrame();
			}else if (s.equals(this.closeButton)) {
				System.out.println("触发‘关闭’按钮");
				// 关闭新建窗口
				this.buildFram.dispose();
			}else if (s.equals(this.buildButton)) {
				System.out.println("触发‘新建’按钮");
				// 校验必填项
				if(!checkRequiredProp()){
					System.out.println("校验未通过！");
					return ;
				}else {
					System.out.println("校验已通过！");
				}





				// 关闭新建窗口
				this.buildFram.dispose();
			}

			 
		} catch (Exception e2) {
			// TODO: handle exception
		}
			
		
	}

	/**
	 * 校验必填属性，弹出提示窗口
	 * @return
	 */
	private boolean checkRequiredProp() {
		 System.out.println("propComponentMap.size="+propComponentMap.size());
		if (propComponentMap.size()>0) {
			System.out.println("1");
			for (Map.Entry<String, JComponent> entry : propComponentMap.entrySet()) {
				String key = entry.getKey();
				Object value = getComponentValue(entry.getValue());
				System.out.println("开始校验属性："+key);
				if (key.contains("*")) {
					System.out.println("属性【"+key+"】包含必选项！");
					if (value == null || value.equals("")) {
						MessageBox.post("必填项属性【"+key+"】不可为空！" , "提示", MessageBox.INFORMATION);
						return false;
					}
				}
				
				System.out.println(key + ": " + value);
			}
		}
		
		return true;
	}

	/**
	 * @根据不同类型的组件获取组件的值
	 * @param component
	 * @return
	 */
	public String getComponentValue(JComponent component) {
		System.out.println("开始根据不同类型的组件取值");
		if (component instanceof JTextField) {
			System.out.println("JTextField");
			return ((JTextField) component).getText();
		} else if (component instanceof JComboBox) {
			System.out.println("JComboBox");
			JComboBox<String> comboBox = (JComboBox<String>) component;
			return (String)comboBox.getSelectedItem();
		} else if (component instanceof DateButton) {
			System.out.println("DateButton");
			DateButton dateButton = (DateButton) component;
			Date date = dateButton.getDate();
			if (date == null){
				return null;
			}
			String dateInput = dateFormat.format(date).replaceAll("(\\d{4})-0(\\d)-", "$1-$2-") + " 00:00";
			System.out.println("dateInput="+dateInput);
			return dateInput;
		}else {
			System.out.println("意料之外的组件！");
		}
		return null;
	}
	

	/**
	 * 绘制对象类型的创建对话框
	 * @return
	 * @throws TCException 
	 */
	public JFrame buildDrawingObjTypeFrame() throws TCException{
		System.out.println("创建新图纸界面！");
		this.propComponentMap.clear();

		// 创建新界面
		JFrame frame = new JFrame();
		frame.setTitle("临时图纸创建界面");
		this.setSize(400, 500);
        this.setLayout(new BorderLayout());

        JPanel centerPanel1 = new JPanel(new GridBagLayout());
		JPanel buttomPanel1 = new JPanel(new FlowLayout());

		//1.属性条目区域
		this.idLabel = new JLabel("ID*");
		String idValue = getIdValue(this.selectComponent);

		if (idValue != null){
			this.idTextField = new JTextField(idValue);
		}
		this.revLabel = new JLabel("版本");
		String[] revs = {"S01"};//版本下拉框数组
		this.revComboBox = new JComboBox<String>(revs);
//		this.revComboBox.setEditable(true);

//布局
		// ID Label
		GridBagConstraints gbcIdLabel = new GridBagConstraints();
		gbcIdLabel.gridx = 0;
		gbcIdLabel.gridy = 0;
		gbcIdLabel.anchor = GridBagConstraints.WEST;
		gbcIdLabel.insets = new Insets(5, 5, 5, 5);
		centerPanel1.add(this.idLabel, gbcIdLabel);

		// ID TextField
		GridBagConstraints gbcIdField = new GridBagConstraints();
		gbcIdField.gridx = 1;
		gbcIdField.gridy = 0;
		gbcIdField.anchor = GridBagConstraints.WEST;

		// 设置自定义宽度
		Dimension textFieldSize = new Dimension(200, idTextField.getPreferredSize().height); // 将200设为所需的宽度
		idTextField.setPreferredSize(textFieldSize);

		centerPanel1.add(this.idTextField, gbcIdField);
		propComponentMap.put("ID*", idTextField);


		// 版本 Label
		GridBagConstraints gbcRevLabel = new GridBagConstraints();
		gbcRevLabel.gridx = 0;
		gbcRevLabel.gridy = 1;
		gbcRevLabel.anchor = GridBagConstraints.WEST;
		gbcRevLabel.insets = new Insets(5, 5, 5, 5);
		centerPanel1.add(this.revLabel, gbcRevLabel);

		// 版本 ComboBox
		GridBagConstraints gbcRevCombo = new GridBagConstraints();
		gbcRevCombo.gridx = 1;
		gbcRevCombo.gridy = 1;
		gbcRevCombo.anchor = GridBagConstraints.WEST;

		// 设置自定义宽度
		Dimension comboBoxSize = new Dimension(200, revComboBox.getPreferredSize().height); // 将200设为所需的宽度
		revComboBox.setPreferredSize(comboBoxSize);

		centerPanel1.add(this.revComboBox, gbcRevCombo);
		propComponentMap.put("版本", revComboBox);


		String preferenceName = getSelectTypePreferenceName();
		System.out.println("preferenceName = " + preferenceName);
		int propIndex  = 2;
		if (preferenceName != null){
			List<String> propList = getPreferenceInfos(preferenceName);
			System.out.println("propList.size = "+propList.size());
			for(String propInfo : propList){//propInfo格式为：*有效期=Form.sb6_validuntil=date=Form.sb6_validuntil
				String[] propConfigInfoArray= propInfo.split("=");
				String validPropName = null;
				if (propConfigInfoArray.length >= 3){
					String name = propConfigInfoArray[0];
					String type = propConfigInfoArray[2];

					// prop Label
					if (name != null && name.contains("*")){
						validPropName = removeAsterisk(name);
						name = validPropName + "*";
					}
					validPropName = name;

					JLabel propLabel = new JLabel(name);
					GridBagConstraints gbcPropLabel = new GridBagConstraints();
					gbcPropLabel.gridx = 0;
					gbcPropLabel.gridy = propIndex;
					gbcPropLabel.anchor = GridBagConstraints.WEST;
					gbcPropLabel.insets = new Insets(5, 5, 5, 5);
					centerPanel1.add(propLabel, gbcPropLabel);

					// prop value组件
					if (type != null){
						String typeValue = type.split(":")[0];
						if (typeValue.equals("string")){
							JTextField propTextField = new JTextField();

							GridBagConstraints gbcPropCombo = new GridBagConstraints();
							gbcPropCombo.gridx = 1;
							gbcPropCombo.gridy = propIndex;
							gbcPropCombo.anchor = GridBagConstraints.WEST;

							// 设置自定义宽度
							Dimension propValueSize = new Dimension(200, propTextField.getPreferredSize().height); // 将200设为所需的宽度
							propTextField.setPreferredSize(propValueSize);

							centerPanel1.add(propTextField, gbcPropCombo);
							propComponentMap.put(validPropName, propTextField);
						}else if (typeValue.equals("date")){
							DateButton dateButton = new DateButton(null, "yyyy-MM-dd", false, false, false);

							GridBagConstraints gbcPropCombo = new GridBagConstraints();
							gbcPropCombo.gridx = 1;
							gbcPropCombo.gridy = propIndex;
							gbcPropCombo.anchor = GridBagConstraints.WEST;

							// 设置自定义宽度
							Dimension propValueSize = new Dimension(200, dateButton.getPreferredSize().height); // 将200设为所需的宽度
							dateButton.setPreferredSize(propValueSize);
							
							centerPanel1.add(dateButton, gbcPropCombo);
							propComponentMap.put(validPropName, dateButton);
						} else if (typeValue.equals("lov")) {
							//TODO 根据冒号后面的LOV名称获取多个lov值，封装成数组添加到propComboBox中
							//TODO 文档中的继承属性来源又是个啥？？？
							String[] lovs = {"lov1","lov2","lov3"};//模拟多个lov值
							JComboBox<String> propComboBox = new JComboBox<String>(lovs);


							GridBagConstraints gbcPropCombo = new GridBagConstraints();
							gbcPropCombo.gridx = 1;
							gbcPropCombo.gridy = propIndex;
							gbcPropCombo.anchor = GridBagConstraints.WEST;

							// 设置自定义宽度
							Dimension propValueSize = new Dimension(200, propComboBox.getPreferredSize().height); // 将200设为所需的宽度
							propComboBox.setPreferredSize(propValueSize);

							centerPanel1.add(propComboBox, gbcPropCombo);
							propComponentMap.put(validPropName, propComboBox);
							
						}
					}
					propIndex ++;
				}
			}
		}else {
			System.out.println("未找到选中类型对应的首选项，请检查首选项SB6_Create_LS_Design配置是否正确！");
		}

		//2.按钮区域
		this.closeButton = new JButton("关闭");
		buttomPanel1.add(closeButton);
		this.buildButton = new JButton("新建");
		buttomPanel1.add(buildButton);

		//按钮事件监听
		this.closeButton.addActionListener(this);
		this.buildButton.addActionListener(this);

		frame.add(centerPanel1, BorderLayout.CENTER);
		frame.add(buttomPanel1, BorderLayout.SOUTH);

		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setResizable(true);
		frame.setPreferredSize(new Dimension(800,600));
		frame.pack(); // 自动调整窗口大小以适应内部组件

		//放到屏幕中央
		UIUtilities.centerToScreen(this);

		frame.setVisible(true);
		
		this.buildFram = frame;
		
		return frame;

	}

	/**
	 * 根据选中对象(业务逻辑)获取ID输入框中的默认值
	 * @param selectComponent2 选中对象
	 * @return ID输入框中的默认值
	 * @throws TCException 
	 */
	private String getIdValue(InterfaceAIFComponent selectComponent2) throws TCException {
//		String idValue = "";
		
		if(selectComponent2 instanceof TCComponentItemRevision){
			System.out.println("当前选中对象是版本对象，开始获取创建界面的ID属性值");
			TCComponentItemRevision itemRevision = (TCComponentItemRevision) selectComponent2;
			String idValue = itemRevision.getStringProperty("item_id");
			if (idValue != null && !idValue.equals("")){
				return idValue.replace("_","");
			}else {{
				return null;//获取版本对象的ID失败
			}}
		}else if (selectComponent instanceof TCComponentFolder) {
			System.out.println("当前选中对象是文件夹对象，创建界面的ID属性值置空");
			return "";
		}else {
			return  null;
		}
	}

	/**
	 * 去除字符串中的星号 *
	 */
	public String removeAsterisk(String str) {
		if (str == null || str.isEmpty()) {
			return "";
		}

		// 替换掉所有的 * 符号
		return str.replaceAll("\\*", "");
	}
	

}
