package com.connor.jingdiao.handlers;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
//import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.connor.jingdiao.util.TCUtil;
import com.connor.ml.tcm.outfile.util.MethodUtil;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentTask;
import com.teamcenter.rac.kernel.TCComponentTcFile;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;

public class StandardDialog extends JDialog {
	private static final long serialVersionUID = 1L;
	
	private TCSession session;
	private JTextArea remark;
	private JButton remarkBtn;
	private JButton exportBtn;
	private JButton closeBtn;
	private JTable impTable;
	private DefaultTableModel impModel;
	private ArrayList<TCComponentItemRevision> revlist;
	private String[] mark;
	private int mrow = -1;
//	private HashMap<String, Integer> map;
//	private LinkedHashMap<String, String[]> ruleOpsMap;
	
//	public DrawingNoApplyDialog(TCSession session, String tables[], String[] options, String[] sqlOptions, InterfaceAIFComponent[] targets) throws Exception {
	public StandardDialog(TCSession session, TCComponent[] models, TCComponentTask task, LinkedHashMap<String, String[]> ruleOpsMap, int[] cols) 
			throws Exception {
		super(AIFUtility.getActiveDesktop());
		this.session = session;
//		list = new ArrayList<>();
//		map = new HashMap<>();
//		this.ruleOpsMap = ruleOpsMap;
//		System.out.println(ruleOpsMap.toString());
		setTitle("标准化审核");
		remark = new JTextArea();
//		remark.setPreferredSize(new Dimension(10, 10));
		remark.setLineWrap(true);
		remarkBtn = new JButton("修改备注");
		exportBtn = new JButton("导出Excel");
		closeBtn = new JButton("关闭");
		JPanel btnPanel = new JPanel(new FlowLayout());
		btnPanel.add(remarkBtn);
		btnPanel.add(exportBtn);
		btnPanel.add(closeBtn);
		JScrollPane remarkPanel = new JScrollPane(remark);
		remarkPanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		JPanel topPanel = new JPanel(new BorderLayout());
		topPanel.add(BorderLayout.NORTH, new JLabel("标准化备注"));
		topPanel.add(BorderLayout.CENTER, remarkPanel);
		topPanel.add(BorderLayout.SOUTH, btnPanel);

//		ArrayList<String[]> props = new ArrayList<>();
//		String[] tableHeader = new String[] { "序号", "itemID", "名称", "版本", "加工类型", "产品分类码", "课题号", "配置码", "部件码", "图纸类型", "新图号" };
//		String[] tables = options.get(0);
		String[] tableHeader = new String[ruleOpsMap.size() + 1];
		tableHeader[0] = "序号";
		int h = 1;
		for (String s : ruleOpsMap.keySet()) {
//			String[] split = tables[h].split("=");
//			props.add(split[1].split("\\."));
			tableHeader[h] = s;
			if(s.equals("标准化备注")) {
				mark = ruleOpsMap.get(s);
				mrow = h;
			}
//			map.put(split[1], h);
			h++;
		}
		if(mrow < 0)
			throw new Exception("首选项Jd_Standard_UI配置不正确");
		impModel = new DefaultTableModel(tableHeader, 0);
		impTable = new JTable() {
			private static final long serialVersionUID = 1L;
			@Override
			public boolean isCellEditable(int row, int col) {
				return false;
			}
		};
		impTable.getTableHeader().setReorderingAllowed(false);
		impTable.setFillsViewportHeight(true);
//		impTable.setEnabled(false);
		impTable.setEnabled(true);
//		impTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		impTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		impTable.setModel(impModel);
		for (int i = 1; i < impModel.getColumnCount(); i++) {
			TableColumn col = impTable.getColumnModel().getColumn(i);
			col.setCellRenderer(new TextAreaRenderer());
			col.setPreferredWidth(150);
		}
		
		setDatas(task, (TCComponentDataset) models[0], ruleOpsMap);
		addActionListener(models, cols);

		setLayout(new BorderLayout());
		add(BorderLayout.EAST, topPanel);
		add(BorderLayout.CENTER, new JScrollPane(impTable));
		pack();
		setSize(new Dimension(1400, 500));
		setDefaultLookAndFeelDecorated(true);
		Dimension screen = getToolkit().getScreenSize();
		setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
		setAlwaysOnTop(true);
		setVisible(true);
	}

	@SuppressWarnings("rawtypes")
	private void setDatas(TCComponentTask task, TCComponentDataset model, LinkedHashMap<String, String[]> ruleOpsMap) throws Exception {
		TCComponentTcFile[] files = model.getTcFiles();
		File file = files[0].getFile(System.getProperty("java.io.tmpdir"));
		SAXReader saxReader = new SAXReader();
		Document doc = saxReader.read(file);
		Element root = doc.getRootElement();
		Element condizione = root.element("condizione");
		List typeEs = condizione.element("object_type").elements();
		ArrayList<String> types = new ArrayList<>();
		for(Object e : typeEs) {
			types.add(((Element)e).getText());
		}
		List regolaEs = condizione.element("regola").elements();
		HashMap<String, Boolean> regolas = new HashMap<>();
		for(Object e : regolaEs) {
			String t = ((Element)e).getText();
			String name = ((Element)e).getName();
			if(name.equals("item"))
				name = "object_type";
			if(t.equals("*")) {
				regolas.put(name, false);
			}else {
				regolas.put(name, true);
			}
		}
		List rows = root.element("data").elements();
		AIFComponentContext[] contexts = TCUtil.getPseudoFolder(task, "root_target_attachments").getChildren();
		revlist = new ArrayList<>();
		for(AIFComponentContext c : contexts) {
			if(!types.contains(c.getComponent().getType()))
				continue;
			TCComponentItemRevision rev = (TCComponentItemRevision) c.getComponent();
			HashMap<String, String> props = new HashMap<>();
			for(String s : regolas.keySet()) {
				if(rev.getTCProperty(s) == null) {
					System.out.println(rev+" >> "+s+"\n属性未找到");
					throw new Exception("判断条件配置错误，请检查配置信息");
				}
				props.put(s, rev.getProperty(s));
			}
		ROW:for(Object e : rows) {
				for(Object t : ((Element)e).elements()) {
					String name = ((Element)t).getName();
					if(!props.containsKey(name))
						continue;
					String text = ((Element)t).getText();
					String val = props.get(name);
					if(regolas.get(name)) {
						if(text.equals("null")) {
							if(!val.isEmpty())
								continue ROW;
						}else if(!val.equals(text))
							continue ROW;
					}else if(!regolas.get(name) && !val.contains(text)) {
						continue ROW;
					}
				}
				TCComponentItem item = rev.getItem();
				String[] row = new String[ruleOpsMap.size()+1];
				row[0] = impTable.getRowCount()+1+"";
				int i = 1;
				for(String n : ruleOpsMap.keySet()) {
					row[i] = getProp(ruleOpsMap.get(n), item, rev);
					i++;
				}
				System.out.println("row:"+Arrays.toString(row));
				impModel.addRow(row);
				revlist.add(rev);
				break;
			}
		}
	}

	private void addActionListener(TCComponent[] models, int[] cols) {
		impTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				try {
					int row = impTable.getSelectedRow();
					if(row < 0) {
						return;
					}
					remark.setText(""+impTable.getValueAt(row, mrow));
				} catch (Exception e1) {
					e1.printStackTrace();
					MessageBox.post(StandardDialog.this, "错误：" + e1.getMessage(), "ERROR", MessageBox.ERROR);
				}
			}
		});
		remarkBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					int row = impTable.getSelectedRow();
					if(row < 0) {
						MessageBox.post(StandardDialog.this, "请选择要编辑的行！", "ERROR", MessageBox.ERROR);
						return;
					}
					String text = remark.getText();
					if(text.getBytes().length > 1024) {
						MessageBox.post(StandardDialog.this, "标准化备注填写长度过长，无法修改！", "ERROR", MessageBox.ERROR);
						return;
					}
					TCComponentItemRevision rev = revlist.get(row);
					TCComponentItem item = rev.getItem();
					if(mark[0].equals("item") && item.isCheckedOut()) {
						MessageBox.post(StandardDialog.this, item+" 已签出，无法修改！", "ERROR", MessageBox.ERROR);
						return;
					}else if(mark[0].equals("rev") && rev.isCheckedOut()) {
						MessageBox.post(StandardDialog.this, rev+" 已签出，无法修改！", "ERROR", MessageBox.ERROR);
						return;
					}
					MethodUtil.openByPass(session);
					if(mark[0].equals("item")) {
						item.setProperty(mark[1], text);
					}else if(mark[0].equals("rev")) {
						rev.setProperty(mark[1], text);
					}
					impTable.setValueAt(text, row, mrow);
					MethodUtil.closeByPass(session);
				}catch(Exception e1) {
					e1.printStackTrace();
					MessageBox.post(StandardDialog.this, "错误："+e1.getMessage(), "ERROR", MessageBox.ERROR);
				}finally {
					try {
						MethodUtil.closeByPass(session);
					}catch(Exception e1) {
						e1.printStackTrace();
					}
				}
			}
		});
		//TODO
		exportBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				FileInputStream input = null;
				FileOutputStream output = null;
				XSSFWorkbook wb = null;
				try {
					File directory = TCUtil.saveExcelChooser(StandardDialog.this, "");
					if(directory==null)
						return;
					if(directory.exists())
						directory.delete();
					TCComponentDataset model = (TCComponentDataset) models[1];
					TCComponentTcFile[] files = model.getTcFiles();
					File file = files[0].getFile(System.getProperty("java.io.tmpdir"));
					input = new FileInputStream(file);
					wb = new XSSFWorkbook(input);
					XSSFSheet sheet = wb.getSheetAt(0);
					XSSFRow row;
					XSSFCell cell;
					row = getRow(sheet, cols[0]);
					TableColumnModel cm = impTable.getColumnModel();
					for(int i=0; i<cm.getColumnCount(); i++) {
						cell = getCell(row, i);
						cell.setCellValue(cm.getColumn(i).getHeaderValue().toString());
					}
					for(int i=0; i<impTable.getRowCount(); i++) {
						row = getRow(sheet, i + cols[1]);
						for(int j=0; j<impTable.getColumnCount(); j++) {
							cell = getCell(row, j);
							cell.setCellValue(impTable.getValueAt(i, j).toString());
						}
					}
					output = new FileOutputStream(file.getPath());
					wb.write(output);
					input.close();
					output.close();
					file.renameTo(directory);
					MessageBox.post(StandardDialog.this, "导出完成！", "提示", MessageBox.INFORMATION);
				}catch(Exception e1) {
					e1.printStackTrace();
					MessageBox.post(StandardDialog.this, "错误："+e1.getMessage(), "ERROR", MessageBox.ERROR);
				}finally {
					if(input!=null)
						try {
							input.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					if(output!=null)
						try {
							output.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
				}
			}
		});
		
		closeBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		});
	}
	
	private String getProp(String[] ps, TCComponentItem item, TCComponentItemRevision rev) throws Exception {
		if(ps[0].equals("item")) {
			return item.getProperty(ps[1]);
		}else if(ps[0].equals("rev")) {
			return rev.getProperty(ps[1]);
		}
		return "";
	}

	private XSSFRow getRow(XSSFSheet sheet, int num) throws Exception {
		XSSFRow row = sheet.getRow(num);
		if(row==null)
			row = sheet.createRow(num);
		return row;
	}
	private XSSFCell getCell(XSSFRow row, int col) throws Exception {
		XSSFCell cell = row.getCell(col);
		if(cell==null)
			cell = row.createCell(col);
//		if(row.getRowNum()>1)
//			cell.setCellStyle(getCell(sourceRow, col).getCellStyle());
		return cell;
	}

	public class TextAreaRenderer extends JTextArea implements TableCellRenderer {
		private static final long serialVersionUID = 1L;
//		ArrayList<Integer> area;
	     
	    public TextAreaRenderer() {
//	    	this.area = area;
	        setLineWrap(true); //利用JTextArea的自动换行方法
	        setWrapStyleWord(true);
		}

		public Component getTableCellRendererComponent(JTable table, Object value,   
	            boolean isSelected, boolean hasFocus, int row, int column) {
			// 计算当下行的最佳高度   
			int maxPreferredHeight = 22;
			JTextArea cell = new JTextArea();
//			cell.setLineWrap(true);
			for (int i=0; i<table.getColumnCount(); i++) {
				cell.setText("" + table.getValueAt(row, i));
//				maxPreferredHeight = Math.max(maxPreferredHeight,cell.getPreferredSize().height);
//				if(row == 19)
//					System.out.println(i+">>>"+table.getValueAt(row, i)+">>>"+cell.getPreferredSize().width+","+cell.getPreferredSize().height);
				maxPreferredHeight = Math.max(maxPreferredHeight, 
						(cell.getPreferredSize().width/table.getColumnModel().getColumn(i).getWidth()+1)*cell.getPreferredSize().height+7);
			}
			if (table.getRowHeight(row) != maxPreferredHeight) 
				// 少了这行则处理器瞎忙   
				table.setRowHeight(row, maxPreferredHeight);
			//System.out.println(row+":"+maxPreferredHeight);
	   
			setText(value == null ? "" : value.toString());   
			fillColor(table,this,isSelected);
			return this;   
	    }
		
		public void fillColor(JTable t,JTextArea l,boolean isSelected ){
			if(isSelected){
				l.setBackground(t.getSelectionBackground());
				l.setForeground(t.getSelectionForeground());
			} else {
	            l.setBackground(t.getBackground());
	            l.setForeground(t.getForeground());
	        }
	    }
	}
}