package nc.ui.hr.baod_orders.view;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JViewport;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import com.borland.jbcl.layout.VerticalFlowLayout;
import nc.bs.logging.Logger;
import nc.ui.pub.beans.UIDialog;
import nc.ui.pub.beans.UITable;
import nc.ui.pub.beans.UITablePane;
import nc.ui.pub.beans.UITextField;
import nc.ui.pub.beans.table.ColumnGroup;
import nc.ui.pub.beans.table.GroupableTableHeader;
import nc.ui.pub.print.version55.print.output.common.FileChooserPane;
import nc.ui.querytemplate.dlg.ButtonPanel;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;

public class CostOutputDialog extends UIDialog {

	private static final long serialVersionUID = -8255260629066398635L;
	private ButtonPanel buttonPanel;
	private FileChooserPane filechooserpane;
	private UITextField TextField;
	private UITablePane costp;

	@SuppressWarnings("deprecation")
	public CostOutputDialog(Container parent, UITablePane costaccountuipanel) {
		costp = costaccountuipanel;
		setLayout(new VerticalFlowLayout());
		setSize(new Dimension(400, 120));
		getContentPane().add(getOutputFileChooserPanel());
		getContentPane().add(getSheetNamePrefixTextField());
		getContentPane().add(getButtonPanel(), "South");
	}

	private Component getOutputFileChooserPanel() {
		JPanel jp = new JPanel();
		jp.add(new JLabel("输出文件路径"));
		if (filechooserpane == null) {
			FileSystemView fsv = FileSystemView.getFileSystemView();
			filechooserpane = new FileChooserPane("全员收入统计表" + new UFDate().toLocalString() + ".xls");
			filechooserpane.setCurrentDirectory(fsv.getHomeDirectory().toString());
			filechooserpane.setFileFilter(new FileFilter() {

				@Override
				public String getDescription() {
					return ".xls";
				}

				@Override
				public boolean accept(File file) {
					if (file.getName().endsWith(".xls") || file.isDirectory()) {
						return true;
					}
					return false;
				}
			});
		}
		jp.add(filechooserpane);
		return jp;
	}

	private Component getSheetNamePrefixTextField() {
		JPanel jp = new JPanel();
		jp.add(new JLabel("SHEET名称"));
		if (TextField == null) {
			TextField = new UITextField();
			TextField.setPreferredSize(new Dimension(250, 20));
			TextField.setMaxLength(100);
			TextField.setText("全员收入统计表");
		}
		jp.add(TextField);
		return jp;
	}

	private ButtonPanel getButtonPanel() {
		if (this.buttonPanel == null) {
			this.buttonPanel = new ButtonPanel(new FlowLayout(1, 5, 10));
			this.buttonPanel.addOKActionListener(new OKAction());
			this.buttonPanel.addCancelActionListener(new CancelAction());
		}
		return this.buttonPanel;
	}
	private class OKAction implements ActionListener {

		/* 将数据导出处理 */
		@SuppressWarnings("static-access")
		public void actionPerformed(ActionEvent e) {
			JViewport jv2 = (JViewport) costp.getComponent(2);
			JViewport jv3 = (JViewport) costp.getComponent(3);
			ArrayList<String> arrh = new ArrayList<String>();
			Map<String, String> arrhc = new HashMap<String, String>();
			ArrayList<Object[]> arrb = new ArrayList<Object[]>();
			GroupableTableHeader gth = (GroupableTableHeader) jv3.getComponent(0);
			UITable ut = (UITable) jv2.getComponent(0);
			JTableHeader tableHeader = ut.getTableHeader();
			/* 表体数据 */
			int rowCount = ut.getRowCount();
			int columnCount = ut.getColumnCount();
			for (int j = 0; j < rowCount; j++) {
				Object[] rs = new Object[columnCount];
				for (int j2 = 0; j2 < columnCount; j2++) {
					rs[j2] = ut.getValueAt(j, j2);
				}
				arrb.add(rs);
			}
			/* 表头数据 */
			TableColumnModel columnModel = tableHeader.getColumnModel();
			int cc = columnModel.getColumnCount();
			for (int i = 0; i < cc; i++) {
				TableColumn column = columnModel.getColumn(i);
				Object headerValue = column.getHeaderValue();
				arrh.add(String.valueOf(headerValue));
				Enumeration<?> columnGroups = gth.getColumnGroups(column);
				if (columnGroups != null) {
					ColumnGroup nextElement = (ColumnGroup) columnGroups.nextElement();
					String comb = nextElement.getText();
					arrhc.put(String.valueOf(i), comb);
				}
			}
			Logger.info("-----------------表体数据----------------");
			for (int i = 0; i < arrb.size(); i++) {
				Logger.info(arrb.get(i).toString());
			}
			Logger.info("--------------结尾------------------");
			/* 导出数据 */
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet();
			/* 处理表头 */
			HSSFRow rowh = sheet.createRow(0);
			HSSFRow rowh1 = sheet.createRow(1);
			int fist = 0;
			String fvist = null;
			for (int i = 0; i < arrh.size(); i++) {
				HSSFCell cell = rowh.createCell(i);
				HSSFCell cell1 = rowh1.createCell(i);
				HSSFCellStyle style = workbook.createCellStyle();
				style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); // 填充单元格
				style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
				style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
				style.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 下边框
				style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
				style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
				style.setFillForegroundColor(IndexedColors.AQUA.getIndex());
				cell.setCellStyle(style);
				cell.setCellStyle(style);
				cell.setCellValue(String.valueOf(arrh.get(i)));
				cell1.setCellStyle(style);
				cell1.setCellStyle(style);
				cell1.setCellValue(String.valueOf(arrh.get(i)));
				if (arrhc.get(String.valueOf(i)) != null) {
					String arrhcv = arrhc.get(String.valueOf(i));
					HSSFCellStyle combst = workbook.createCellStyle();
					combst.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					combst.setFillForegroundColor(IndexedColors.AQUA.getIndex());
					combst.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); // 填充单元格
					combst.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
					combst.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 下边框
					combst.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
					combst.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
					cell.setCellValue(arrhcv);
					cell.setCellStyle(combst);
					if (fvist != null && !arrhcv.equals(fvist)) {
						CellRangeAddress region = new CellRangeAddress(0, 0, fist, i - 1);
						sheet.addMergedRegion(region);
						fvist = arrhcv;
						fist = i;
					} else if (arrhcv.equals(fvist)) {
						if (i == arrh.size() - 1) {
							CellRangeAddress regionr = new CellRangeAddress(0, 0, fist, i);
							sheet.addMergedRegion(regionr);
						}
					} else {
						fvist = arrhcv;
						fist = i;
					}
				} else {
					CellRangeAddress region = new CellRangeAddress(0, 1, i, i);
					sheet.addMergedRegion(region);
				}
			}
			/* 处理表体 */
			for (int i = 0; i < arrb.size(); i++) {
				HSSFRow rowb = sheet.createRow(i + 2);
				Object[] objects = arrb.get(i);
				for (int j = 0; j < objects.length; j++) {
					HSSFCell cell = rowb.createCell(j);
					HSSFCellStyle style = workbook.createCellStyle();
					HSSFDataFormat dataFormat = workbook.createDataFormat();
					cell.setCellValue(String.valueOf(objects[j] == null ? "" : objects[j]));
					if (objects[j] instanceof UFDouble) {
						style.setDataFormat(dataFormat.getBuiltinFormat("General"));
						cell.setCellValue(((UFDouble) objects[j]).doubleValue());
					}
					if (objects[j] instanceof BigDecimal) {
						style.setDataFormat(dataFormat.getBuiltinFormat("General"));
						cell.setCellValue(((BigDecimal) objects[j]).doubleValue());
					}
					style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
					style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
					style.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 下边框
					style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
					style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
					cell.setCellStyle(style);
				}
			}
			for (int i = 0; i < columnCount; i++) {
				sheet.setColumnWidth(i, 5000);
			}
			workbook.setSheetName(0, TextField.getText());
			FileOutputStream out = null;
			try {
				String filePath = filechooserpane.getFilePath();
				out = new FileOutputStream(filePath);
				workbook.write(out);
				out.close();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			closeOK();
		}
	}
	private class CancelAction implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			closeCancel();
		}
	}
}
