package nc.ui.arap.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileOutputStream;

import javax.swing.Icon;
import javax.swing.JFileChooser;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;

import nc.bs.framework.common.NCLocator;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.sfbase.client.ClientToolKit;
import nc.ui.arap.view.ArapBillCardForm;
import nc.ui.pub.bill.BillCardPanel;
import nc.ui.pubapp.uif2app.actions.BodyAddLineAction;

/**
 * 导出
 * @author YY
 *
 */
public class OutputBodyAction extends BodyAddLineAction{
	private static final long serialVersionUID = 3494691988068685023L;
	private ArapBillCardForm editorModel;
	private Icon icon = ClientToolKit.loadImageIcon("\\themeroot\\blue\\themeres\\ui\\toolbaricons\\cite_model_normal.png");
	private IUAPQueryBS iuap = (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
	private Sheet sheet = null;
	public ArapBillCardForm getEditorModel() {
		return editorModel;
	}

	public void setEditorModel(ArapBillCardForm arapBillCardForm) {
		this.editorModel = arapBillCardForm;
	}
	
	public OutputBodyAction(){
		setCode("OutputBodyAction");
		setBtnName("导出");
		setName("导出");
		putValue("AcceleratorKey", KeyStroke.getKeyStroke(82, 8));
		setShowNameInToolbar(true);
		setIsShow(true);
		putValue("ShortDescription", "导出");
		putValue("SmallIcon", icon);

	}
	
	@Override
	public void doAction(ActionEvent e) throws Exception {
		//只有应付单（非项目） 应付单（项目）可以使用
		String type = sqlexecuteQuery("billtypename", "bd_billtype", "pk_billtypeid", this.editorModel.getBillCardPanel().getHeadItem("pk_tradetypeid").getValueObject().toString());		
		if(!"应付单（非项目）".equals(type) && !"应付单（项目）".equals(type) && !"预付核销单（非项目）".equals(type) && !"预付核销单（项目）".equals(type)) {
			return;
		}
		// 创建文件选择器  
	    JFileChooser fileChooser = new JFileChooser();  
	    fileChooser.setDialogTitle("选择导出路径");  
	    // 设置文件选择器模式为保存模式，以便用户可以选择保存的文件路径  
	    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); // 只显示文件，不显示文件夹
	    // 创建文件过滤器
	    FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel文件 (*.xls)", "xls");
	    fileChooser.setFileFilter(filter);
	    // 设置文件选择器的文件名  
	    fileChooser.setSelectedFile(new File("MyFileName"));  
	    // 显示隐藏文件
	    fileChooser.setFileHidingEnabled(false); // 将隐藏的文件显示出来
	    // 显示文件选择器对话框，并等待用户选择路径  
	    int result = fileChooser.showSaveDialog(null);
	    // 检查用户是否选择了路径
	    if (result == JFileChooser.APPROVE_OPTION) {
	        // 创建一个新的工作簿
	        Workbook workbook = new HSSFWorkbook();
	        // 创建一个工作表
	        sheet = workbook.createSheet("Sheet1");
	        outputData(this, type);
	        // 创建一个新的CellStyle  
			CellStyle cellStyle = workbook.createCellStyle();  
			// 应用新的样式到第一行第一列的单元格  
			Cell firstCell = sheet.getRow(0).getCell(0);  
			sheet.getRow(0).setHeight((short)1500);
		    cellStyle.setWrapText(true); // 设置文本换行
		    firstCell.setCellStyle(cellStyle);
	        // 创建文件输出流并使用正确的文件路径
	        File selectedFile = fileChooser.getSelectedFile();
	        if (!selectedFile.getName().toLowerCase().endsWith(".xls")) {
	            selectedFile = new File(selectedFile.getParentFile(), selectedFile.getName() + ".xls");
	        }
	        FileOutputStream outputStream = new FileOutputStream(selectedFile);
	        workbook.write(outputStream);
	        outputStream.close();
	    } else {
	       return;
	    }
		
	}

	public void outputData(OutputBodyAction outputBodyAction, String type) throws Exception {
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 10));
		// 创建行和单元格  
		createRowAndCells(sheet, 0, "*导入须知:\n"
				+ "1.除了数量和金额，所有内容必须为文本格式;\n"
				+ "2.带*标题为必填项，请确认后进行导入;\n"
				+ "3.某行进行拆分时，请将对应的发票号带入到新行；发票号不可修改；");
		BillCardPanel cp = outputBodyAction.editorModel.getBillCardPanel();
		
		int count = cp.getRowCount();
		if("应付单（非项目）".equals(type)) {
			//非项目导出模板
			createRowAndCells(sheet, 1, "摘要*", "费用归属*", "预算编号*","预算名称*","发票号*","数量*","结算方式*","税码*","税率*","单价","金额*","税额*","价税合计*","民航发展基金",
					"汇款附言","客户","客户层级","原发票日期yyyy-mm-dd hh:mm:ss","备注","人员","成本归属部门*","物料*");  
			
			for (int i = 0; i < count; i++) {
				Row rows = sheet.createRow(i+2); 
				//摘要
		        rows.createCell(0).setCellValue(getBodyValueAt(cp, i, "def25", "name", "bd_defdoc", "pk_defdoc"));
		        //费用归属
		        rows.createCell(1).setCellValue(getBodyValueAt(cp, i, "def30", "name", "bd_defdoc", "pk_defdoc"));
		        //预算编号
		        rows.createCell(2).setCellValue(cp.getBodyValueAt(i, "def1") == null ? null : cp.getBodyValueAt(i, "def1").toString());
		        //预算名称
		        rows.createCell(3).setCellValue(getBodyValueAt(cp, i, "pk_subjcode", "name", "bd_inoutbusiclass", "pk_inoutbusiclass"));
		        //发票号
		        rows.createCell(4).setCellValue(cp.getBodyValueAt(i, "def12") == null ? null : cp.getBodyValueAt(i, "def12").toString());
		        //数量
		        rows.createCell(5).setCellValue(cp.getBodyValueAt(i, "quantity_cr") == null ? null : cp.getBodyValueAt(i, "quantity_cr").toString());
		        //结算方式
		        rows.createCell(6).setCellValue(getBodyValueAt(cp, i, "pk_balatype", "name", "bd_balatype", "pk_balatype"));
		        //税码
		        rows.createCell(7).setCellValue(getBodyValueAt(cp, i, "taxcodeid", "description", "bd_taxcode", "pk_taxcode"));
		        //税率
		        rows.createCell(8).setCellValue(cp.getBodyValueAt(i, "taxrate") == null ? null : cp.getBodyValueAt(i, "taxrate").toString());
		        //单价
		        rows.createCell(9).setCellValue(cp.getBodyValueAt(i, "price") == null ? null : cp.getBodyValueAt(i, "price").toString());
		        //金额
		        rows.createCell(10).setCellValue(cp.getBodyValueAt(i, "local_notax_cr") == null ? null : cp.getBodyValueAt(i, "local_notax_cr").toString());
		        //税额
		        rows.createCell(11).setCellValue(cp.getBodyValueAt(i, "local_tax_cr") == null ? null : cp.getBodyValueAt(i, "local_tax_cr").toString());
		        //价税合计
		        rows.createCell(12).setCellValue(cp.getBodyValueAt(i, "local_money_cr") == null ? null : cp.getBodyValueAt(i, "local_money_cr").toString());
		        //民航发展基金
		        rows.createCell(13).setCellValue(cp.getBodyValueAt(i, "def29") == null ? null : cp.getBodyValueAt(i, "def29").toString());
		        //汇款附言
		        rows.createCell(14).setCellValue(cp.getBodyValueAt(i, "def21") == null ? null : cp.getBodyValueAt(i, "def21").toString());
		        //客户
		        rows.createCell(15).setCellValue(getBodyValueAt(cp, i, "def13", "name", "bd_defdoc", "pk_defdoc"));
		        //客户层级
		        rows.createCell(16).setCellValue(cp.getBodyValueAt(i, "def22") == null ? null : cp.getBodyValueAt(i, "def22").toString());
		        //原发票日期
		        rows.createCell(17).setCellValue(cp.getBodyValueAt(i, "def17") == null ? null : cp.getBodyValueAt(i, "def17").toString());
		        //备注
		        rows.createCell(18).setCellValue(cp.getBodyValueAt(i, "def2") == null ? null : cp.getBodyValueAt(i, "def2").toString());
		        //人员
		        rows.createCell(19).setCellValue(cp.getBodyValueAt(i, "def40") == null ? null : cp.getBodyValueAt(i, "def40").toString());
		        //成本归属部门
		        rows.createCell(20).setCellValue(getBodyValueAt(cp, i, "def23", "name", "org_dept", "pk_dept"));
		        //物料
		        rows.createCell(21).setCellValue(getBodyValueAt(cp, i, "material", "name", "bd_material", "pk_material"));
		        
			}
		}else if("应付单（项目）".equals(type)){
			//项目导出模板
			createRowAndCells(sheet, 1, "摘要*", "费用归属*", "项目编号*","项目名称*","专业*","费用事项*","发票号*","数量*","税码*","税率*","结算方式*","单价","金额*","税额*","民航发展基金",
					"价税合计*","汇款附言","成本归属部门*","票据号/保理申请编号","备注","预算名称*","物料*");  
			for (int i = 0; i < count; i++) {
				Row rows = sheet.createRow(i+2); 
				//摘要
		        rows.createCell(0).setCellValue(getBodyValueAt(cp, i, "def25", "name", "bd_defdoc", "pk_defdoc"));
		        //费用归属
		        rows.createCell(1).setCellValue(getBodyValueAt(cp, i, "def30", "name", "bd_defdoc", "pk_defdoc"));
		        //项目编号
		        rows.createCell(2).setCellValue(cp.getBodyValueAt(i, "def18") == null ? null : cp.getBodyValueAt(i, "def18").toString());
		        //项目名称
		        rows.createCell(3).setCellValue(getBodyValueAt(cp, i, "project", "project_name", "bd_project", "pk_project"));
			    //专业
		        rows.createCell(4).setCellValue(getBodyValueAt(cp, i, "def6", "name", "bd_defdoc", "pk_defdoc"));
		        //费用事项
		        rows.createCell(5).setCellValue(getBodyValueAt(cp, i, "def7", "name", "bd_defdoc", "pk_defdoc"));
		        //发票号
		        rows.createCell(6).setCellValue(cp.getBodyValueAt(i, "def12") == null ? null : cp.getBodyValueAt(i, "def12").toString());
		        //数量
		        rows.createCell(7).setCellValue(cp.getBodyValueAt(i, "quantity_cr") == null ? null : cp.getBodyValueAt(i, "quantity_cr").toString());
		        //税码
		        rows.createCell(8).setCellValue(getBodyValueAt(cp, i, "taxcodeid", "description", "bd_taxcode", "pk_taxcode"));
		        //税率
		        rows.createCell(9).setCellValue(cp.getBodyValueAt(i, "taxrate") == null ? null : cp.getBodyValueAt(i, "taxrate").toString());
		        //结算方式
		        rows.createCell(10).setCellValue(getBodyValueAt(cp, i, "pk_balatype", "name", "bd_balatype", "pk_balatype"));
		        //单价
		        rows.createCell(11).setCellValue(cp.getBodyValueAt(i, "price") == null ? null : cp.getBodyValueAt(i, "price").toString());
		        //金额
		        rows.createCell(12).setCellValue(cp.getBodyValueAt(i, "local_notax_cr") == null ? null : cp.getBodyValueAt(i, "local_notax_cr").toString());
		        //税额
		        rows.createCell(13).setCellValue(cp.getBodyValueAt(i, "local_tax_cr") == null ? null : cp.getBodyValueAt(i, "local_tax_cr").toString());
		        //民航发展基金
		        rows.createCell(14).setCellValue(cp.getBodyValueAt(i, "def29") == null ? null : cp.getBodyValueAt(i, "def29").toString());
		        //价税合计
		        rows.createCell(15).setCellValue(cp.getBodyValueAt(i, "local_money_cr") == null ? null : cp.getBodyValueAt(i, "local_money_cr").toString());
		        //汇款附言
		        rows.createCell(16).setCellValue(cp.getBodyValueAt(i, "def21") == null ? null : cp.getBodyValueAt(i, "def21").toString());
		        //成本归属部门
		        rows.createCell(17).setCellValue(getBodyValueAt(cp, i, "def22", "name", "org_dept", "pk_dept"));
		        //票据号/保理申请编号
		        rows.createCell(18).setCellValue(cp.getBodyValueAt(i, "def5") == null ? null : cp.getBodyValueAt(i, "def5").toString());
		        //备注
		        rows.createCell(19).setCellValue(cp.getBodyValueAt(i, "def2") == null ? null : cp.getBodyValueAt(i, "def2").toString());
		        //预算名称
		        rows.createCell(20).setCellValue(getBodyValueAt(cp, i, "pk_subjcode", "name", "bd_inoutbusiclass", "pk_inoutbusiclass"));
		        //物料
		        rows.createCell(21).setCellValue(getBodyValueAt(cp, i, "material", "name", "bd_material", "pk_material"));
			}
		}else if("预付核销单（非项目）".equals(type)){
			//项目导出模板
			createRowAndCells(sheet,1,"摘要*","费用归属*","预算编号*","预算名称*","发票号*","物料*","税码*","税率*","单价","金额*","税额*","价税合计*","扣税类别*",
					"成本归属部门*","往来对象*","备注","对方单位名称*","付款部门*","应付类型*");
			for (int i = 0; i < count; i++) {
				Row rows = sheet.createRow(i+2);
				//摘要
		        rows.createCell(0).setCellValue(getBodyValueAt(cp, i, "def25", "name", "bd_defdoc", "pk_defdoc"));
		        //费用归属
		        rows.createCell(1).setCellValue(getBodyValueAt(cp, i, "def30", "name", "bd_defdoc", "pk_defdoc"));
		        //预算编号
		        rows.createCell(2).setCellValue(cp.getBodyValueAt(i, "def1") == null ? null : cp.getBodyValueAt(i, "def1").toString());
		        //预算名称
		        rows.createCell(3).setCellValue(getBodyValueAt(cp, i, "pk_subjcode", "name", "bd_inoutbusiclass", "pk_inoutbusiclass"));
		        //发票号
		        rows.createCell(4).setCellValue(cp.getBodyValueAt(i, "def12") == null ? null : cp.getBodyValueAt(i, "def12").toString());
		        //物料
		        rows.createCell(5).setCellValue(getBodyValueAt(cp, i, "material", "name", "bd_material", "pk_material"));
		        //税码
		        rows.createCell(6).setCellValue(getBodyValueAt(cp, i, "taxcodeid", "description", "bd_taxcode", "pk_taxcode"));
		        //税率
		        rows.createCell(7).setCellValue(cp.getBodyValueAt(i, "taxrate") == null ? null : cp.getBodyValueAt(i, "taxrate").toString());
		        //单价
		        rows.createCell(8).setCellValue(cp.getBodyValueAt(i, "price") == null ? null : cp.getBodyValueAt(i, "price").toString());
		        //金额
		        rows.createCell(9).setCellValue(cp.getBodyValueAt(i, "local_notax_cr") == null ? null : cp.getBodyValueAt(i, "local_notax_cr").toString());
		        //税额
		        rows.createCell(10).setCellValue(cp.getBodyValueAt(i, "local_tax_cr") == null ? null : cp.getBodyValueAt(i, "local_tax_cr").toString());
		        //价税合计
		        rows.createCell(11).setCellValue(cp.getBodyValueAt(i, "local_money_cr") == null ? null : cp.getBodyValueAt(i, "local_money_cr").toString());
		        //扣税类别
		        rows.createCell(12).setCellValue("0".equals(cp.getBodyValueAt(i, "taxtype").toString()) ? "应税内含" : "应税外加");
		        //成本归属部门
		        rows.createCell(13).setCellValue(getBodyValueAt(cp, i, "def23", "name", "org_dept", "pk_dept"));
		        //往来对象
		        int objtype = (Integer) (cp.getBodyValueAt(i, "objtype")  == null ? -1 : cp.getBodyValueAt(i, "objtype"));
		        rows.createCell(14).setCellValue(objtype == 1 ? "供应商" : objtype == 2 ? "部门" : objtype == 3 ? "业务员" : null);
		        //备注
		        rows.createCell(15).setCellValue(cp.getBodyValueAt(i, "def2") == null ? null : cp.getBodyValueAt(i, "def2").toString());
		        //对方单位名称
		        rows.createCell(16).setCellValue(getBodyValueAt(cp, i, "supplier", "name", "bd_supplier", "pk_supplier"));
		        //付款部门
		        rows.createCell(17).setCellValue(getBodyValueAt(cp, i, "pk_deptid", "name", "org_dept", "pk_dept"));
		        //应付类型
		        rows.createCell(18).setCellValue(getBodyValueAt(cp, i, "pk_tradetypeid", "billtypename", "bd_billtype", "pk_billtypeid"));
		        
			}
		}else {
			//项目导出模板
			createRowAndCells(sheet,1,"摘要*","费用归属*","项目编号*","项目名称*","专业*","费用事项*","发票号*","物料*","税码*","税率*","单价","金额*","税额*",
					"价税合计*","成本归属部门*","扣税类别*","往来对象*","对方单位名称*","备注","预算名称*","应付类型*");  
			for (int i = 0; i < count; i++) {
				Row rows = sheet.createRow(i+2);
				//摘要
		        rows.createCell(0).setCellValue(getBodyValueAt(cp, i, "def25", "name", "bd_defdoc", "pk_defdoc"));
		        //费用归属
		        rows.createCell(1).setCellValue(getBodyValueAt(cp, i, "def30", "name", "bd_defdoc", "pk_defdoc"));
		        //项目编号
		        rows.createCell(2).setCellValue(cp.getBodyValueAt(i, "def18") == null ? null : cp.getBodyValueAt(i, "def18").toString());
		        //项目名称
		        rows.createCell(3).setCellValue(getBodyValueAt(cp, i, "project", "project_name", "bd_project", "pk_project"));
		        //专业
		        rows.createCell(4).setCellValue(getBodyValueAt(cp, i, "def6", "name", "bd_defdoc", "pk_defdoc"));
		        //费用事项
		        rows.createCell(5).setCellValue(getBodyValueAt(cp, i, "def7", "name", "bd_defdoc", "pk_defdoc"));
		        //发票号
		        rows.createCell(6).setCellValue(cp.getBodyValueAt(i, "def12") == null ? null : cp.getBodyValueAt(i, "def12").toString());
		        //物料
		        rows.createCell(7).setCellValue(getBodyValueAt(cp, i, "material", "name", "bd_material", "pk_material"));
		        //税码
		        rows.createCell(8).setCellValue(getBodyValueAt(cp, i, "taxcodeid", "description", "bd_taxcode", "pk_taxcode"));
		        //税率
		        rows.createCell(9).setCellValue(cp.getBodyValueAt(i, "taxrate") == null ? null : cp.getBodyValueAt(i, "taxrate").toString());
		        //单价
		        rows.createCell(10).setCellValue(cp.getBodyValueAt(i, "price") == null ? null : cp.getBodyValueAt(i, "price").toString());
		         //金额
		        rows.createCell(11).setCellValue(cp.getBodyValueAt(i, "local_notax_cr") == null ? null : cp.getBodyValueAt(i, "local_notax_cr").toString());
		        //税额
		        rows.createCell(12).setCellValue(cp.getBodyValueAt(i, "local_tax_cr") == null ? null : cp.getBodyValueAt(i, "local_tax_cr").toString());
		        //价税合计
		        rows.createCell(13).setCellValue(cp.getBodyValueAt(i, "local_money_cr") == null ? null : cp.getBodyValueAt(i, "local_money_cr").toString());
		        //成本归属部门
		        rows.createCell(14).setCellValue(getBodyValueAt(cp, i, "def22", "name", "org_dept", "pk_dept"));
		        //扣税类别
		        rows.createCell(15).setCellValue("0".equals(cp.getBodyValueAt(i, "taxtype").toString()) ? "应税内含" : "应税外加");
		        //往来对象
		        int objtype = (Integer) (cp.getBodyValueAt(i, "objtype")  == null ? -1 : cp.getBodyValueAt(i, "objtype"));
		        rows.createCell(16).setCellValue(objtype == 1 ? "供应商" : objtype == 2 ? "部门" : objtype == 3 ? "业务员" : null);
		        //对方单位名称
		        rows.createCell(17).setCellValue(getBodyValueAt(cp, i, "supplier", "name", "bd_supplier", "pk_supplier"));
		        //备注
		        rows.createCell(18).setCellValue(cp.getBodyValueAt(i, "def2") == null ? null : cp.getBodyValueAt(i, "def2").toString());
		        //预算名称
		        rows.createCell(19).setCellValue(getBodyValueAt(cp, i, "pk_subjcode", "name", "bd_inoutbusiclass", "pk_inoutbusiclass"));
		        //应付类型
		        rows.createCell(20).setCellValue(getBodyValueAt(cp, i, "pk_tradetypeid", "billtypename", "bd_billtype", "pk_billtypeid"));
			}
		}
	}

	// 创建行和单元格的方法  
	private void createRowAndCells(Sheet sheet, int rowIndex, String... cellValues) {  
	    Row row = sheet.createRow(rowIndex);  
	    for (int i = 0; i < cellValues.length; i++) {  
	        row.createCell(i).setCellValue(cellValues[i]);  
	        
	    }  
	}  
	
	// 获取数据的方法  
	private String getBodyValueAt(BillCardPanel cp, int rowIndex, String columnName, String out, String table, String key) throws Exception {  
	    return cp.getBodyValueAt(rowIndex, columnName) == null ? null : sqlexecuteQuery(out, table, key, (String)cp.getBodyValueAt(rowIndex, columnName));  
	}  
	
	/*
	 * 数据库查询
	 */
	private String sqlexecuteQuery(String out,String table,String key,String value) throws Exception {
		
		String sql = "select "+out+" from "+table+" where "+key+" = '"+value+"'";
		
		Object object;
			object = iuap.executeQuery(sql, new ColumnProcessor());
			if (object == null) {
				return null;
			}
			return object.toString();
	}
}
