package com.qmth.qrzk.repository.user.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;

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.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qmth.qrzk.repository.common.base.BaseDao;
import com.qmth.qrzk.repository.service.query.TaskQueryParams;
import com.qmth.qrzk.repository.task.TaskBatch;
import com.qmth.qrzk.repository.user.model.Attachment;
import com.qmth.qrzk.repository.user.model.Course;
import com.qmth.qrzk.repository.user.model.TkjsTask;
import com.qmth.qrzk.repository.user.model.TkjsTaskUserLink;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.utils.Consts;
import com.qmth.qrzk.repository.utils.DateHelper;
import com.qmth.qrzk.repository.utils.General;

@Service
public class TkjsTaskServiceImpl {
	
	@Autowired private BaseDao dao;
	
	@Autowired
	private CourseServiceImpl courseService;
	
	@Autowired
	private BookServiceImpl bookService;
	
	@Autowired
	private TaskBatchImpl taskBatchService;
	
	public List<TkjsTask> getTkjsTasksWithStatByBatchId(int batchId){
		List<TkjsTask> tasks = dao.getList("getTkjsTasksByBatchId", batchId);
		Map<Integer,Object[]> teacherDataMap = new LinkedHashMap<Integer, Object[]>();
		for(TkjsTask t:tasks){
			t.setCourseCode(t.getCourse().getCode());
			t.setCourseName(t.getCourse().getName());
			String teachers = "";
			int inputNum = 0;
			for(TkjsTaskUserLink ul:t.getTeacherLinks()){
				Map<String,Object> param = new HashMap<String, Object>();
				param.put("courseId", t.getCourseId());
				param.put("teacherId", ul.getTeacherId());
				param.put("planStartTime", t.getPlanStartTime());
				param.put("planEndTime", t.getPlanEndTime());
				int statInfo2 = dao.getObject("statTeacherJobByCourseIdAndTeacherId", param);
				inputNum += statInfo2;
				Object[] teacherData = teacherDataMap.get(ul.getTeacherId());
				if(teacherData == null){
					teacherData = new Object[2];
					teacherDataMap.put(ul.getTeacherId(), teacherData);
					teacherData[0] = Consts.UserMap.get(ul.getTeacherId()).getName();
					teacherData[1] = 0;
				}
				teacherData[1] = (Integer)teacherData[1] + statInfo2;
				teachers = teachers + Consts.UserMap.get(ul.getTeacherId()).getName() + "(" + statInfo2 + ")，";
			}
			if(teachers.length() > 0){
				teachers = teachers.substring(0, teachers.length() - 1);
			}
			t.setInputNum(inputNum);
			t.setTeachers(teachers);
		}
		{
			TkjsTask total = new TkjsTask();
			total.setCourseCode("总计");
			total.setCourseName("");
			String teachers = "";
			for(Object[] teacherData:teacherDataMap.values()){
				teachers = teachers + teacherData[0] + "(" + teacherData[1] + ")，";
			}if(teachers.length() > 0){
				teachers = teachers.substring(0, teachers.length() - 1);
			}
			total.setTeachers(teachers);
			for(TkjsTask job:tasks){
				total.setInputNum(total.getInputNum() + job.getInputNum());
			}
			tasks.add(total);
		}
		return tasks;
	}
	
	public List<TkjsTask> queryTodoTkjsTasks(TaskQueryParams params){
		return dao.getPagerList("queryTodoTkjsTasks", params);
	}
	
	public TkjsTask getTkjsTaskById(int taskId){
		TkjsTask task = dao.get("getTkjsTaskById", taskId);
		return task;
	}
	
	public TkjsTask addTkjsTask(TkjsTask task,User curUser){
		TaskBatch taskBatch = taskBatchService.findById(task.getBatchId());
		task.setPlanStartTime(taskBatch.getPlanStartTime());
		task.setPlanEndTime(taskBatch.getPlanEndTime());
		
		task.setCreatedBy(curUser.getId());
		task.setCreatedTime(new Date());
		task.setUpdatedBy(curUser.getId());
		task.setUpdatedTime(new Date());
		dao.insert("addTkjsTask", task);
		for(TkjsTaskUserLink userLink:task.getTeacherLinks()){
			userLink.setTkjsTaskId(task.getId());
			dao.insert("addTkjsTaskUserLink", userLink);
		}
		return getTkjsTaskById(task.getId());
	}
	
	public void deleteTkjsTasks(int[] taskIds){
		for(int id:taskIds){
			dao.delete("delTkjsTaskUserLinksByTaskId", id);
			dao.delete("delTkjsTaskById", id);
		}
	}

	public void deleteTkjsTaskById(int id){
		dao.delete("delTkjsTaskUserLinksByTaskId", id);
		dao.delete("delTkjsTaskById", id);
	}
	
	public void updateTkjsTask(TkjsTask task){
		dao.update("updateTkjsTask", task);
		updateTkjsTaskUserLinks(task);
	}
	
	public void updateTkjsTaskUserLinks(TkjsTask task){
		dao.delete("delTkjsTaskUserLinksByTaskId", task.getId());
		for(TkjsTaskUserLink userLink:task.getTeacherLinks()){
			userLink.setTkjsTaskId(task.getId());
			dao.insert("addTkjsTaskUserLink", userLink);
		}
	}
	
	public void saveImportData(int batchId,List<TkjsTask> list,JSONObject object,User curUser){
		TaskBatch taskBatch = taskBatchService.findById(batchId);
		List<String> loginList=new ArrayList<String>();
		Map<String,User> tempMap=new HashMap<String,User>();
		for(Map.Entry<Integer, User> entry : Consts.UserMap.entrySet()){
			tempMap.put(entry.getValue().getLoginName(), entry.getValue());
			loginList.add(entry.getValue().getLoginName());
		}
		boolean existsCourseCode=true;
		boolean isSameCourseCode=false;
		int i=1;
		Set<String> courseCodeSet = new HashSet<String>();
		
		List<TkjsTask> paperTasks = dao.getList("getTkjsTasksByBatchId", batchId);
		
		//把当前批次下所有的课程代码和任务单编号放到map里面
		for(TkjsTask pp:paperTasks){
			Course course=courseService.findById(pp.getCourseId());
			courseCodeSet.add(course.getCode());
		}
		
		for(TkjsTask at:list){
			
			Course course=courseService.findByCode(at.getCourseCode());
			//校验课程代码是否在系统中存在
			if(course==null){
				existsCourseCode=false;
				break;
			}
			//校验课程代码是否在批次中存在
			if(courseCodeSet.contains(at.getCourseCode())){
				isSameCourseCode=true;
				break;
			}
			
			String[] teacherArr = at.getTeachers().split(",|，");
			for(String teacherLoginName:teacherArr){
				if(!loginList.contains(teacherLoginName)){
					//返回前端用户登录名不存在
					object.put("result", "fail");
					object.put("lineNum",i );
					object.put("msg", "命题教师[" + teacherLoginName + "]用户信息不存在");
					return;
				}
				TkjsTaskUserLink userLink = new TkjsTaskUserLink();
				userLink.setTeacherId(tempMap.get(teacherLoginName).getId());
				at.getTeacherLinks().add(userLink);
			}
			i++;
		}
		
		if(!existsCourseCode){
			object.put("result", "fail");
			object.put("lineNum",i);
			object.put("msg", "导入的课程代码在基础库中不存在");
		}else if(isSameCourseCode){	//导入的信息中存在相同的courseCode
			object.put("result", "fail");
			object.put("lineNum",i);
			object.put("msg", "导入的文件该批次下存在相同的课程编号");
		}else{
			for(TkjsTask at:list){
				Course course=courseService.findByCode(at.getCourseCode());
				at.setCourseId(course.getId());
				at.setBatchId(batchId);
				at.setPlanStartTime(taskBatch.getPlanStartTime());
				at.setPlanEndTime(taskBatch.getPlanEndTime());
				
				at.setCreatedBy(curUser.getId());
				at.setCreatedTime(new Date());
				at.setUpdatedBy(curUser.getId());
				at.setUpdatedTime(new Date());
				dao.insert("addTkjsTask", at);
				for(TkjsTaskUserLink userLink:at.getTeacherLinks()){
					userLink.setTkjsTaskId(at.getId());
					dao.insert("addTkjsTaskUserLink", userLink);
				}
			}
			if(object.isEmpty()){
				object.put("result", "success");
				object.put("successNum", list.size());
				object.put("msg", "导入成功!");
			}
		}
	}

	@SuppressWarnings("unchecked")
	public List<Map<String,Object>> statInputQuestByCourse(Date startDate,Date endDate){
		Map<String,Date> param = new HashMap<String, Date>();
		param.put("startDate", startDate);
		param.put("endDate", endDate);
		List<Map<String, Object>> statInputData = dao.getList("statInputQuestByCourse",param);
		List<Map<String, Object>> statAuditData = dao.getList("statAuditInputQuestByCourse",param);
		Map<String,Integer> statAuditMap = new HashMap<String, Integer>();
		for(Map<String, Object> stat:statAuditData){
			statAuditMap.put(stat.get("courseCode") + "-" + stat.get("statusCode"), General.toInteger(stat.get("num"), 0));
		}
		Map<String,Map<String, Object>> resultMap = new LinkedHashMap<String,Map<String, Object>>();
		int draftNum = 0;
		int approvedNum = 0;
		int rejectedNum = 0;
		int finalApprovedNum = 0;
		int finalRejectedNum = 0;
		int total = 0;
		for(Map<String, Object> stat:statInputData){
			String courseCode = (String) stat.get("courseCode");
			String courseName = (String) stat.get("courseName");
			int num = General.toInteger(stat.get("num"), 0);
			Map<String, Object> result = resultMap.get(courseCode);
			if(result == null){
				result = new HashMap<String, Object>();
				result.put("courseCode", courseCode);
				result.put("courseName", courseName);
				int draftNumTmp = General.toInteger(statAuditMap.get(courseCode + "-QUESTION_DRAFT"), 0);
				int approvedNumTmp = General.toInteger(statAuditMap.get(courseCode + "-QUESTION_APPROVED"), 0);
				int rejectedNumTmp = General.toInteger(statAuditMap.get(courseCode + "-QUESTION_REJECTED"), 0);
				int finalApprovedNumTmp = General.toInteger(statAuditMap.get(courseCode + "-QUESTION_FINAL_APPROVED"), 0);
				int finalRejectedNumTmp = General.toInteger(statAuditMap.get(courseCode + "-QUESTION_FINAL_REJECTED"), 0);
				draftNum += draftNumTmp;
				approvedNum += approvedNumTmp;
				rejectedNum += rejectedNumTmp;
				finalApprovedNum += finalApprovedNumTmp;
				finalRejectedNum += finalRejectedNumTmp;
				result.put("draftNum", draftNumTmp);
				result.put("approvedNum", approvedNumTmp);
				result.put("rejectedNum", rejectedNumTmp);
				result.put("finalApprovedNum", finalApprovedNumTmp);
				result.put("finalRejectedNum", finalRejectedNumTmp);
				resultMap.put(courseCode,result);
			}
			int sum = General.toInteger(result.get("sum"), 0) + num;
			total += num;
			result.put("sum", sum);
			List<Map<String, Object>> typeNums = (List<Map<String, Object>>) result.get("typeNums");
			if(typeNums == null){
				typeNums = new ArrayList<Map<String,Object>>();
				result.put("typeNums", typeNums);
			}
			typeNums.add(stat);
		}
		List<Map<String,Object>> results = new ArrayList<Map<String,Object>>(resultMap.values());
		Map<String, Object> totalResult = new HashMap<String, Object>();
		totalResult.put("courseCode","总计：");
		totalResult.put("draftNum", draftNum);
		totalResult.put("approvedNum", approvedNum);
		totalResult.put("rejectedNum", rejectedNum);
		totalResult.put("finalApprovedNum", finalApprovedNum);
		totalResult.put("finalRejectedNum", finalRejectedNum);
		totalResult.put("sum", total);
		List<Map<String, Object>> typeNums = new ArrayList<Map<String,Object>>();
		typeNums.add(new HashMap<String, Object>());
		totalResult.put("typeNums", typeNums);
		results.add(totalResult);
		return results;
	}
	
	@SuppressWarnings("unchecked")
	public List<Map<String,Object>> statInputQuestByTeacher(Date startDate,Date endDate){
		Map<String,Date> param = new HashMap<String, Date>();
		param.put("startDate", startDate);
		param.put("endDate", endDate);
		List<Map<String, Object>> statData = dao.getList("statInputQuestByTeacher",param);
		Set<String> dateStrSet = new HashSet<String>();
		for(Map<String, Object> stat:statData){
			dateStrSet.add((String)stat.get("createdTime"));
		}
		List<String> dateStrList = new ArrayList<String>(dateStrSet);
		Collections.sort(dateStrList, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
		});
		List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
		Map<String,Object> thMap = new HashMap<String, Object>();
		thMap.put("dateStrList", dateStrList);
		results.add(thMap);

		Map<String,Integer> dataStrNumMapForTotal = new LinkedHashMap<String, Integer>();
		for(String str:(List<String>)thMap.get("dateStrList")){
			dataStrNumMapForTotal.put(str, null);
		}
		
		Map<Integer,Map<String, Object>> resultMap = new LinkedHashMap<Integer,Map<String, Object>>();
		int total = 0;
		for(Map<String, Object> stat:statData){
			int userId = General.toInteger(stat.get("userId"), 0);
			String userName = (String) stat.get("userName");
			String createdTime = (String) stat.get("createdTime");
			int num = General.toInteger(stat.get("num"), 0);
			Map<String, Object> result = resultMap.get(userId);
			if(result == null){
				result = new HashMap<String, Object>();
				result.put("userName", userName);
				Map<String,Integer> dataStrNumMap = new LinkedHashMap<String, Integer>();
				for(String str:(List<String>)thMap.get("dateStrList")){
					dataStrNumMap.put(str, null);
				}
				result.put("dataStrNumMap", dataStrNumMap);
				resultMap.put(userId,result);
			}
			Map<String,Integer> dataStrNumMap = (Map<String,Integer>)result.get("dataStrNumMap");
			dataStrNumMap.put(createdTime, num);
			int sum = General.toInteger(result.get("sum"), 0) + num;
			dataStrNumMapForTotal.put(createdTime, General.toInteger(dataStrNumMapForTotal.get(createdTime), 0) + num);
			total += num;
			result.put("sum", sum);
		}
		results.addAll(resultMap.values());
		Map<String, Object> totalResult = new HashMap<String, Object>();
		totalResult.put("userName","总计：");
		totalResult.put("sum", total);
		totalResult.put("dataStrNumMap", dataStrNumMapForTotal);
		results.add(totalResult);
		return results;
	}
	
	@SuppressWarnings("unchecked")
	public Attachment exportInputStat(Date startDate,Date endDate,User curUser){
		String title = "时间段：" + DateHelper.toLongString(startDate) + "至" + DateHelper.toLongString(endDate) + "。\r\n报表生成时间：" + DateHelper.getNow();
		List<Map<String,Object>> statByCourse = statInputQuestByCourse(startDate, endDate);
		List<Map<String,Object>> statByTeacher = statInputQuestByTeacher(startDate, endDate);
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个字体
	    HSSFFont normalFont1 = workbook.createFont();
	    normalFont1.setColor(HSSFColor.BLACK.index);
		
		// 生成一个字体
	    HSSFFont normalFont2 = workbook.createFont();
	    normalFont2.setColor(HSSFColor.BLACK.index);
	    normalFont2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	    
	    //标题边框，粗体，居中对齐，不可换行
  		HSSFCellStyle border_th = workbook.createCellStyle();
  		border_th.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		border_th.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  		border_th.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		border_th.setWrapText(false);
  		border_th.setFont(normalFont2);
	    
	    //普通字符边框，居左对齐，可换行
  		HSSFCellStyle border_str = workbook.createCellStyle();
  		border_str.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		border_str.setAlignment(HSSFCellStyle.ALIGN_LEFT);
  		border_str.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		border_str.setWrapText(true);
  		border_str.setFont(normalFont1);
	    
	    //数值边框，居右对齐，不可换行
  		HSSFCellStyle border_num = workbook.createCellStyle();
  		border_num.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		border_num.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		border_num.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		border_num.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		border_num.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
  		border_num.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		border_num.setWrapText(false);
  		border_num.setFont(normalFont1);
	    
  		{
			HSSFSheet sheetByCourse = workbook.createSheet("按课程统计");
			sheetByCourse.setColumnWidth(0, 3000);
			sheetByCourse.setColumnWidth(1, 5000);
			sheetByCourse.setColumnWidth(2, 4000);
			sheetByCourse.setColumnWidth(3, 2000);
			sheetByCourse.setColumnWidth(4, 2000);
			sheetByCourse.setColumnWidth(5, 3000);
			sheetByCourse.setColumnWidth(6, 3000);
			sheetByCourse.setColumnWidth(7, 3000);
			sheetByCourse.setColumnWidth(8, 3000);
			sheetByCourse.setColumnWidth(9, 2000);
			{
				HSSFRow row0 = sheetByCourse.createRow(0);
				row0.setHeight((short)600);
				sheetByCourse.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));
				HSSFCell ce = row0.createCell(0);
		        ce.setCellValue("按课程统计结果，" + title);
		        ce.setCellStyle(border_str);
		        row0.createCell(1).setCellStyle(border_str);
		        row0.createCell(2).setCellStyle(border_str);
		        row0.createCell(3).setCellStyle(border_str);
		        row0.createCell(4).setCellStyle(border_str);
		        row0.createCell(5).setCellStyle(border_str);
		        row0.createCell(6).setCellStyle(border_str);
		        row0.createCell(7).setCellStyle(border_str);
		        row0.createCell(8).setCellStyle(border_str);
		        row0.createCell(9).setCellStyle(border_str);
			}
			{
				HSSFRow row1 = sheetByCourse.createRow(1);
				row1.setHeight((short)300);
				HSSFCell ce0 = row1.createCell(0);
		        ce0.setCellValue("课程代码");
		        ce0.setCellStyle(border_th);
				HSSFCell ce1 = row1.createCell(1);
		        ce1.setCellValue("课程名称");
		        ce1.setCellStyle(border_th);
				HSSFCell ce2 = row1.createCell(2);
		        ce2.setCellValue("题型名称");
		        ce2.setCellStyle(border_th);
				HSSFCell ce3 = row1.createCell(3);
		        ce3.setCellValue("数量");
		        ce3.setCellStyle(border_th);
				HSSFCell ce4 = row1.createCell(4);
		        ce4.setCellValue("草稿");
		        ce4.setCellStyle(border_th);
				HSSFCell ce5 = row1.createCell(5);
		        ce5.setCellValue("审核通过");
		        ce5.setCellStyle(border_th);
				HSSFCell ce6 = row1.createCell(6);
		        ce6.setCellValue("审核拒绝");
		        ce6.setCellStyle(border_th);
				HSSFCell ce7 = row1.createCell(7);
		        ce7.setCellValue("终审通过");
		        ce7.setCellStyle(border_th);
				HSSFCell ce8 = row1.createCell(8);
		        ce8.setCellValue("终审拒绝");
		        ce8.setCellStyle(border_th);
				HSSFCell ce9 = row1.createCell(9);
		        ce9.setCellValue("总计");
		        ce9.setCellStyle(border_th);
			}
			{
				int index = 0;
				for(int i=0;i<statByCourse.size();i++){
					Map<String,Object> stat = statByCourse.get(i);
			        List<Map<String, Object>> typeNums = (List<Map<String, Object>>) stat.get("typeNums");
			        for(int j=0;j<typeNums.size();j++){
			        	Map<String, Object> typeNum = typeNums.get(j);
			        	
						HSSFRow row = sheetByCourse.createRow(2+index);
						
						if(j == 0){
							sheetByCourse.addMergedRegion(new CellRangeAddress(2+index, 2+index + typeNums.size()-1, 0, 0));
							sheetByCourse.addMergedRegion(new CellRangeAddress(2+index, 2+index + typeNums.size()-1, 1, 1));
							sheetByCourse.addMergedRegion(new CellRangeAddress(2+index, 2+index + typeNums.size()-1, 4, 4));
							sheetByCourse.addMergedRegion(new CellRangeAddress(2+index, 2+index + typeNums.size()-1, 5, 5));
							sheetByCourse.addMergedRegion(new CellRangeAddress(2+index, 2+index + typeNums.size()-1, 6, 6));
							sheetByCourse.addMergedRegion(new CellRangeAddress(2+index, 2+index + typeNums.size()-1, 7, 7));
							sheetByCourse.addMergedRegion(new CellRangeAddress(2+index, 2+index + typeNums.size()-1, 8, 8));
							sheetByCourse.addMergedRegion(new CellRangeAddress(2+index, 2+index + typeNums.size()-1, 9, 9));
						}
						if(i == statByCourse.size()-1){
							sheetByCourse.addMergedRegion(new CellRangeAddress(2+index, 2+index, 0, 3));
						}
						HSSFCell ce0 = row.createCell(0);
						HSSFCell ce1 = row.createCell(1);
						HSSFCell ce4 = row.createCell(4);
						HSSFCell ce5 = row.createCell(5);
						HSSFCell ce6 = row.createCell(6);
						HSSFCell ce7 = row.createCell(7);
						HSSFCell ce8 = row.createCell(8);
						HSSFCell ce9 = row.createCell(9);
						if(j == 0){
							ce0.setCellValue(General.null2String(stat.get("courseCode")));
							if(i < statByCourse.size()-1){
								ce1.setCellValue(General.null2String(stat.get("courseName")));
							}
							ce4.setCellValue(General.toInteger(stat.get("draftNum"), 0));
							ce5.setCellValue(General.toInteger(stat.get("approvedNum"), 0));
							ce6.setCellValue(General.toInteger(stat.get("rejectedNum"), 0));
							ce7.setCellValue(General.toInteger(stat.get("finalApprovedNum"), 0));
							ce8.setCellValue(General.toInteger(stat.get("finalRejectedNum"), 0));
							ce9.setCellValue(General.toInteger(stat.get("sum"), 0));
						}
				        ce0.setCellStyle(border_str);
				        ce1.setCellStyle(border_str);
				        ce4.setCellStyle(border_num);
				        ce5.setCellStyle(border_num);
				        ce6.setCellStyle(border_num);
				        ce7.setCellStyle(border_num);
				        ce8.setCellStyle(border_num);
				        ce9.setCellStyle(border_num);
				        
						HSSFCell ce2 = row.createCell(2);
						if(i < statByCourse.size()-1){
							ce2.setCellValue(General.null2String(typeNum.get("typeName")));
						}
				        ce2.setCellStyle(border_str);
						HSSFCell ce3 = row.createCell(3);
						if(i < statByCourse.size()-1){
							ce3.setCellValue(General.toInteger(typeNum.get("num"), 0));
						}
				        ce3.setCellStyle(border_num);
				        index++;
			        }
				}
			}
  		}
  		
  		{
			HSSFSheet sheetByTeacher = workbook.createSheet("按命题教师统计");
			Map<String,Object> first = statByTeacher.get(0);
			List<String> dateStrList = (List<String>)first.get("dateStrList");
			
			sheetByTeacher.setColumnWidth(0, 3000);
			for(int i=0;i<dateStrList.size();i++){
				sheetByTeacher.setColumnWidth(1 + i, 3000);
			}
			sheetByTeacher.setColumnWidth(1 + dateStrList.size(), 2000);
			{
				HSSFRow row0 = sheetByTeacher.createRow(0);
				if(dateStrList.size() == 0){
					row0.setHeight((short)1600);
				}else if(dateStrList.size() == 1){
					row0.setHeight((short)1000);
				}else if(dateStrList.size() == 2 || dateStrList.size() == 3){
					row0.setHeight((short)850);
				}else{
					row0.setHeight((short)600);
				}
				sheetByTeacher.addMergedRegion(new CellRangeAddress(0, 0, 0, 1 + dateStrList.size()));
				HSSFCell ce = row0.createCell(0);
		        ce.setCellValue("按命题教师统计，" + title);
		        ce.setCellStyle(border_str);
		        row0.createCell(1).setCellStyle(border_str);
		        for(int i=0;i<=dateStrList.size();i++){
		        	row0.createCell(1+i).setCellStyle(border_str);
		        }
			}
			{
				HSSFRow row1 = sheetByTeacher.createRow(1);
				row1.setHeight((short)300);
				HSSFCell ce0 = row1.createCell(0);
		        ce0.setCellValue("姓名");
		        ce0.setCellStyle(border_th);
		        for(int i=0;i<dateStrList.size();i++){
					HSSFCell ce1 = row1.createCell(1+i);
			        ce1.setCellValue(dateStrList.get(i));
			        ce1.setCellStyle(border_th);
		        }
				HSSFCell ce2 = row1.createCell(1+dateStrList.size());
		        ce2.setCellValue("总计");
		        ce2.setCellStyle(border_th);
			}
			{
				for(int i=1;i<statByTeacher.size();i++){
					Map<String,Object> stat = statByTeacher.get(i);
					HSSFRow row = sheetByTeacher.createRow(1+i);
					HSSFCell ce0 = row.createCell(0);
					ce0.setCellValue((String)stat.get("userName"));
					ce0.setCellStyle(border_str);
					Map<String,Integer> dataStrNumMap = (Map<String,Integer>)stat.get("dataStrNumMap");
					int j=0;
					for(Integer num:dataStrNumMap.values()){
						HSSFCell ce1 = row.createCell(1+j);
						if(num == null){
							ce1.setCellValue("");
						}else{
							ce1.setCellValue(num);
						}
						ce1.setCellStyle(border_num);
						j++;
					}
					HSSFCell ce2 = row.createCell(1+dateStrList.size());
			        ce2.setCellValue(General.toInteger(stat.get("sum"),0));
			        ce2.setCellStyle(border_num);
				}
			}
  		}
		
		File xlsFile = General.newTmpFile();
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(xlsFile);
			workbook.write(fos);
		} catch (Exception e) {
			throw new RuntimeException("写入Excel数据到临时文件：" + xlsFile.getAbsolutePath() + "中失败，原因：" + e.getMessage(), e);
		} finally{
			General.close(fos);
		}
		File newFile = General.newAttFile();
		xlsFile.renameTo(newFile);
		Attachment att = new Attachment();
		att.setCreatedBy(curUser.getId());
		att.setOriginalName("题库建设报表_" + DateHelper.getNow(DateHelper.shortSimpleDateFormatWithoutSplit) + ".xls");
		att.setCurName(newFile.getName());
		att.setFileLength(newFile.length());
		att.setStorePath(newFile.getAbsolutePath());
		att.setStatus(Consts.AttachmentStatus.DRAFT);
		dao.insert("addAttachment", att);
		return att;
	}
}
