package com.hmsoft.common.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.OldExcelFormatException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.hmsoft.model.CoursePlan;
import com.hmsoft.model.School;
import com.hmsoft.model.StatisObj;

/**
 * 
 * @author zq
 *
 */
public class POIUtil {

	private POIUtil() {}
	
	public static Map<String, Object> readExcel(final File excelFile) {
		InputStream is = null;
		try {
			is = new BufferedInputStream(new FileInputStream(excelFile));
			if (excelFile.getName().toLowerCase().endsWith("xls")) {
				return readFromXls(is);
				//return JxlUril.readFromXls(is);
			} else if (excelFile.getName().toLowerCase().endsWith("xlsx")) {
				return readFromXlsx(is);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (OldExcelFormatException e) {
			throw e; 
		}
		finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	private static Map<String, Object> readFromXls(final InputStream is) {
		HSSFWorkbook book = null;
		final Map<String, Object> result = new HashMap<String, Object>();
		final List<CoursePlan> list = new ArrayList<CoursePlan>();
		final StringBuilder errorSb = new StringBuilder();
		final Map<String, String> existCourseMap = new HashMap<String, String>();
		try {
			book = new HSSFWorkbook(is);
        	final HSSFSheet sheet = book.getSheetAt(0);  
            int lastRow = sheet.getLastRowNum();
            for (int m=1; m<=lastRow; m++) {
            	final HSSFRow row = sheet.getRow(m);
            	String courseCode = row.getCell(0).getStringCellValue();
            	String courseName = row.getCell(1).getStringCellValue();
            	String outlineName = row.getCell(2).getStringCellValue();
            	String bookName = row.getCell(3).getStringCellValue();
            	String bianZhu = row.getCell(4).getStringCellValue();
            	String press = row.getCell(5).getStringCellValue();
            	String publications = row.getCell(6).getStringCellValue();
            	String cengci = row.getCell(7).getStringCellValue();
            	//
            	final CoursePlan courplan = new CoursePlan();
            	courplan.setBianZhu(bianZhu);
            	courplan.setBookName(bookName);
            	courplan.setCourseCode(courseCode);
            	courplan.setCourseName(courseName);
            	courplan.setCoursePlanId(m);
            	courplan.setOutlineName(outlineName);
            	courplan.setPress(press);
            	courplan.setPublications(publications);
            	courplan.setCengci(cengci);
            	list.add(courplan);
            	if (existCourseMap.get(courseCode) != null) {
            		errorSb.append("第").append(m).append("行,课程编码:'" ).append(courseCode).append("'已经存在;");
            	}
            }
		} catch (IOException e) {
			errorSb.append("导入错误:").append(e.getMessage()).append(";");
			e.printStackTrace();
		} catch (OldExcelFormatException e) {
			throw e; 
		} finally {
			if (book != null) {
				try {
					book.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		result.put("data", list);
		result.put("errMsg", errorSb.toString());
		return result;
	}
	
	private static Map<String, Object> readFromXlsx(final InputStream is) {
		XSSFWorkbook book = null;
		final Map<String, Object> result = new HashMap<String, Object>();
		final List<CoursePlan> list = new ArrayList<CoursePlan>();
		final StringBuilder errorSb = new StringBuilder();
		final Map<String, String> existCourseMap = new HashMap<String, String>();
		try {
            book = new XSSFWorkbook(is);
            XSSFSheet sheet = book.getSheetAt(0);  
            int lastRow = sheet.getLastRowNum();
            // 将数据项存入map(除去表头即第一行)  
            for (int m=1; m<=lastRow; m++) {
            	final XSSFRow row = sheet.getRow(m);
            	String courseCode = row.getCell(0).getStringCellValue();
            	String courseName = row.getCell(1).getStringCellValue();
            	String outlineName = row.getCell(2).getStringCellValue();
            	String bookName = row.getCell(3).getStringCellValue();
            	String bianZhu = row.getCell(4).getStringCellValue();
            	String press = row.getCell(5).getStringCellValue();
            	String publications = row.getCell(6).getStringCellValue();
            	String cengci = row.getCell(7).getStringCellValue();
            	//
            	final CoursePlan courplan = new CoursePlan();
            	courplan.setBianZhu(bianZhu);
            	courplan.setBookName(bookName);
            	courplan.setCourseCode(courseCode);
            	courplan.setCourseName(courseName);;
            	courplan.setCoursePlanId(m);
            	courplan.setOutlineName(outlineName);
            	courplan.setPress(press);
            	courplan.setPublications(publications);
            	courplan.setCengci(cengci);
            	//add
            	list.add(courplan);
            	if (existCourseMap.get(courseCode) != null) {
            		errorSb.append("第").append(m).append("行,课程编码:'" ).append(courseCode).append("'已经存在;");
            	}
            }
		} catch (IOException e) {
			errorSb.append("导入错误:").append(e.getMessage()).append(";");
			e.printStackTrace();
		} finally {
			if (book != null) {
				try {
					book.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		result.put("data", list);
		result.put("errMsg", errorSb.toString());
		return result;
	}
	
	/**
	 * 导出计划.
	 * @param path
	 * @param planList
	 */
	public static void writeToXlsx(final List<CoursePlan> planList, final String path) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("最终计划");
		sheet.setDefaultColumnWidth((short) 15);
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell0 = row.createCell(0);
		HSSFCell cell1 = row.createCell(1);
		HSSFCell cell2 = row.createCell(2);
		HSSFCell cell3 = row.createCell(3);
		HSSFCell cell4 = row.createCell(4);
		HSSFCell cell5 = row.createCell(5);
		HSSFCell cell6 = row.createCell(6);
		HSSFCell cell7 = row.createCell(7);
		HSSFCell cell8 = row.createCell(8);
		HSSFCell cell9 = row.createCell(9);
		cell0.setCellValue(new HSSFRichTextString("课程代码"));
		cell1.setCellValue(new HSSFRichTextString("课程名称"));
		cell2.setCellValue(new HSSFRichTextString("课程大纲"));
		cell3.setCellValue(new HSSFRichTextString("教材名称"));
		cell4.setCellValue(new HSSFRichTextString("编著"));
		cell5.setCellValue(new HSSFRichTextString("出版社"));
		cell6.setCellValue(new HSSFRichTextString("版次"));
		cell7.setCellValue(new HSSFRichTextString("层次"));
		cell8.setCellValue(new HSSFRichTextString("选择该课程学校"));
		cell9.setCellValue(new HSSFRichTextString("命题办指定"));
		for (int i=0; i<planList.size(); i++) {
			HSSFRow datarow = sheet.createRow(i+1);
			CoursePlan plan = planList.get(i);
			HSSFCell datacell0 = datarow.createCell(0);
			datacell0.setCellValue(new HSSFRichTextString(plan.getCourseCode()));
			HSSFCell datacell1 = datarow.createCell(1);
			datacell1.setCellValue(new HSSFRichTextString(plan.getCourseName()));
			HSSFCell datacell2 = datarow.createCell(2);
			datacell2.setCellValue(new HSSFRichTextString(plan.getOutlineName()));
			HSSFCell datacell3 = datarow.createCell(3);
			datacell3.setCellValue(new HSSFRichTextString(plan.getBookName()));
			HSSFCell datacell4 = datarow.createCell(4);
			datacell4.setCellValue(new HSSFRichTextString(plan.getBianZhu()));
			HSSFCell datacell5 = datarow.createCell(5);
			datacell5.setCellValue(new HSSFRichTextString(plan.getPress()));
			HSSFCell datacell6 = datarow.createCell(6);
			datacell6.setCellValue(new HSSFRichTextString(plan.getPublications()));
			HSSFCell datacell7 = datarow.createCell(7);
			datacell7.setCellValue(new HSSFRichTextString(plan.getCengci()));
			HSSFCell datacell8 = datarow.createCell(8);
			
			String schName = "";
			if (plan.getSchoolId() != null && plan.getSchoolId().longValue() != 0) {
				schName = plan.getSchoolName();
			} else {
				schName = getSchoolName(Long.parseLong(plan.getSchSelectIds()));
			}
			datacell8.setCellValue(new HSSFRichTextString(schName));//为保持一致
			HSSFCell datacell9 = datarow.createCell(9);
			datacell9.setCellValue(new HSSFRichTextString(plan.getSchoolName()));
		}
		try {
			FileOutputStream fos = new FileOutputStream(new File(path));
			workbook.write(fos);
			fos.close();
			workbook.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static String getSchoolName(long schoolId) {
		List<School> schools = ShoolDateUtil.getAllSchoolData();
		for (School sch : schools) {
			if (sch.getSchoolId().longValue() == schoolId) {
				return sch.getSchoolName();
			}
		}
		return "";
	}
	
	//征集统计
	public static void writeStatisToXlsx(final List<StatisObj> statisList, final String path) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("统计");
		sheet.setDefaultColumnWidth((short) 15);
		sheet.setColumnWidth(3, 40*256);
		HSSFCellStyle styleBold = workbook.createCellStyle();
		HSSFCellStyle styleContent = workbook.createCellStyle();
		styleContent.setWrapText(true);
		HSSFFont font = workbook.createFont();
		font.setBold(true);
		styleBold.setFont(font);
		
		HSSFRow row = sheet.createRow(0);
		
		HSSFCell cell0 = row.createCell(0);
		HSSFCell cell1 = row.createCell(1);
		HSSFCell cell2 = row.createCell(2);
		HSSFCell cell3 = row.createCell(3);
		
		cell0.setCellValue(new HSSFRichTextString("序号"));
		cell0.setCellStyle(styleBold);
		
		cell1.setCellValue(new HSSFRichTextString("学校名称"));
		cell1.setCellStyle(styleBold);
		
		cell2.setCellValue(new HSSFRichTextString("课程数量"));
		cell2.setCellStyle(styleBold);
		
		cell3.setCellValue(new HSSFRichTextString("所选课程"));
		cell3.setCellStyle(styleBold);
		
		//cell2.setCellStyle(new HSSFCellStyle().set);
		int totalCourses = 0;
		for (int i=0; i<statisList.size(); i++) {
			HSSFRow datarow = sheet.createRow(i+1);
			StatisObj stat = statisList.get(i);
			
			HSSFCell datacell0 = datarow.createCell(0);
			datacell0.setCellValue(new HSSFRichTextString(String.valueOf(i + 1)));
			
			HSSFCell datacell1 = datarow.createCell(1);
			datacell1.setCellValue(new HSSFRichTextString(stat.getSchoolName()));
			
			HSSFCell datacell2 = datarow.createCell(2);
			datacell2.setCellValue(new HSSFRichTextString(stat.getCount().toString()));
			
			HSSFCell datacell3 = datarow.createCell(3);
			datacell3.setCellStyle(styleContent);
			datacell3.setCellValue(new HSSFRichTextString(stat.getCourseShow()));
			
			totalCourses += stat.getCount();
		}
		HSSFRow lastRow = sheet.createRow(statisList.size() + 1);
		HSSFCell cellHzCaption = lastRow.createCell(0);
		HSSFCell cellSchNum = lastRow.createCell(1);
		HSSFCell cellCourseNum = lastRow.createCell(2);
		cellHzCaption.setCellValue("汇总");
		cellHzCaption.setCellStyle(styleBold);
		cellSchNum.setCellValue(new HSSFRichTextString(String.valueOf(statisList.size())));
		cellCourseNum.setCellValue(new HSSFRichTextString(String.valueOf(totalCourses)));
		try {
			FileOutputStream fos = new FileOutputStream(new File(path));
			workbook.write(fos);
			fos.close();
			workbook.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
