package com.qmth.qrzk.supplypaper.service;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qmth.qrzk.dao.repositories.PaperRepo;
import com.qmth.qrzk.dao.repositories.PrintLogRepo;
import com.qmth.qrzk.dao.repositories.PrintProvTaskItemRepo;
import com.qmth.qrzk.dao.repositories.PrintProvTaskRepo;
import com.qmth.qrzk.dao.repositories.UserRepo;
import com.qmth.qrzk.paper.model.Paper;
import com.qmth.qrzk.repository.common.enumeration.PaperType;
import com.qmth.qrzk.repository.common.enumeration.PrintType;
import com.qmth.qrzk.repository.user.model.PrintLog;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.utils.General;
import com.qmth.qrzk.supplypaper.model.PrintProvTask;
import com.qmth.qrzk.supplypaper.model.PrintProvTaskItem;

/**
 * 处理打印任务的服务类，包括分配打印任务、取消任务等
 * @author zhengmin
 *
 */
@Service
public class PrintTaskService {

	@Autowired private PrintProvTaskRepo taskRepo;
	@Autowired private PrintProvTaskItemRepo taskItemRepo;
	@Autowired private PrintLogRepo printLogRepo;
	
	@Autowired private UserRepo userRepo;

	@Autowired private PaperRepo paperRepo;
	
	/**
	 * 设置关联省份的打印任务
	 * @param userId
	 * @param taskId
	 */
	@Transactional
	public void assignTask(Integer userId,long...taskId){
		for(long id : taskId){
			taskRepo.updateUserId(userId, id);
		}
	}
	
	/**
	 * 更新白纸打印数量
	 * @param type 纸张格式，如果传null，是打印标答
	 * @param taskItemId
	 * @param count
	 * @return
	 */
	@Transactional
	public PrintProvTaskItem updateTaskStatus(PaperType type,long taskItemId,int count, String remark, int userId)
				throws Exception{
		PrintProvTaskItem item = taskItemRepo.findOne(taskItemId);
		if(item == null){
			throw new Exception("没有该打印任务");
		}
		if(type != null){
			switch(type){
				case BLANK:
					item.setBlankPrintedCount(item.getBlankPrintedCount() + count);
					break;
				case ACID:
					item.setAcidPrintedCount(item.getAcidPrintedCount() + count);
					break;
			}
		}
		else{
			item.setAnswerPrintedCount(item.getAnswerPrintedCount() + count);
		}
		taskItemRepo.save(item);
		//记录日志
		User user = userRepo.findOne(userId);
		
		PrintProvTask task = taskRepo.findOne(item.getTaskId());
		Paper paper = paperRepo.findOne(item.getPaperId());
		
		if(user == null){
			throw new Exception("用户不存在");
		}
		PrintType t1 = null;
		PrintType t2 = null;
		if(type != null){
			switch(item.getPaperFormat()){
				case 0:
					t1 = PrintType.MERGE;
					break;
				case 1:
					t1 = PrintType.SEPRATE;
					break;
				default :
					t1 = PrintType.MERGE;
					t2 = PrintType.SEPRATE;
			}
		}else{
			t1 = PrintType.ANSWER;
			type = PaperType.BLANK;
		}
			
		PrintLog log = new PrintLog(item.getBatchId(), user.getId(),user.getName(), type, t1, count
				, task.getProvName(), item.getCourseCode(), item.getCourseName(), paper.getCode());
		log.setRemark(remark);
		printLogRepo.save(log);
		
		if(t2 != null){
			PrintLog log2 = new PrintLog(item.getBatchId(), user.getId(),user.getName(), type, t2, count
					, task.getProvName(), item.getCourseCode(), item.getCourseName(), paper.getCode());
			printLogRepo.save(log2);
		}
		
		return item;
	}
	
	/**
	 * 设置关联省份的检查任务
	 * @param userId
	 * @param taskId
	 */
	@Transactional
	public void assignScanTask(Integer userId,long...taskId){
		for(long id : taskId){
			taskRepo.updateScanUserId(userId, id);
		}
	}
	
	public void writeScanTasksIntoFile(File xlsFile,List<User> scanners){
		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);
	    
  		{
			HSSFSheet sheetByCourse = workbook.createSheet("封装任务");
			sheetByCourse.setColumnWidth(0, 3000);
			sheetByCourse.setColumnWidth(1, 2000);
			sheetByCourse.setColumnWidth(2, 2000);
			sheetByCourse.setColumnWidth(3, 38000);
			{
				HSSFRow row0 = sheetByCourse.createRow(0);
//				row1.setHeight((short)300);
				HSSFCell ce0 = row0.createCell(0);
		        ce0.setCellValue("封装人");
		        ce0.setCellStyle(border_th);
				HSSFCell ce1 = row0.createCell(1);
		        ce1.setCellValue("课程数");
		        ce1.setCellStyle(border_th);
				HSSFCell ce2 = row0.createCell(2);
		        ce2.setCellValue("省份数");
		        ce2.setCellStyle(border_th);
				HSSFCell ce3 = row0.createCell(3);
		        ce3.setCellValue("负责省份");
		        ce3.setCellStyle(border_th);
			}
			{
				for(int i=0;i<scanners.size();i++){
					User scanner = scanners.get(i);
					HSSFRow row = sheetByCourse.createRow(1 + i);
					HSSFCell ce0 = row.createCell(0);
					HSSFCell ce1 = row.createCell(1);
					HSSFCell ce2 = row.createCell(2);
					HSSFCell ce3 = row.createCell(3);
					
					ce0.setCellStyle(border_str);
			        ce1.setCellStyle(border_str);
			        ce2.setCellStyle(border_str);
			        ce3.setCellStyle(border_str);
			        
			        ce0.setCellValue(General.convertNullToEmpty(scanner.getName()));
			        int courseNum = 0;
			        String provStr = "";
			        if(scanner.getTasks() != null){
			        	for(PrintProvTask task:scanner.getTasks()){
			        		courseNum += task.getPaperCount();
			        		provStr = provStr + task.getProvName() + "(" + task.getCourseCount() + ")；";
			        	}
			        	courseNum = courseNum / 2;
			        	if(provStr.length() > 0){
			        		provStr = provStr.substring(0, provStr.length() - 1);
			        	}
			        }
			        ce1.setCellValue(courseNum);
			        ce2.setCellValue((scanner.getTasks() != null ? scanner.getTasks().size():0));
			        ce3.setCellValue(provStr);
				}
			}
  		}
  		
		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);
		}
	}
	
	/**
	 * 更新任务试卷扫描状态
	 * @param type 纸张格式，如果传null，是打印标答
	 * @param taskItemId
	 * @param count
	 * @return
	 */
	@Transactional
	public PrintProvTaskItem updateTaskItemPaperScanned(long taskItemId)
				throws Exception{
		PrintProvTaskItem item = taskItemRepo.findOne(taskItemId);
		if(item == null){
			throw new Exception("没有该打印任务");
		}
		item.setIsPaperScanned(true);
		taskItemRepo.save(item);
		return item;
	}
	
	/**
	 * 更新任务试卷扫描状态
	 * @param type 纸张格式，如果传null，是打印标答
	 * @param taskItemId
	 * @param count
	 * @return
	 */
	@Transactional
	public PrintProvTaskItem updateTaskItemAnswerScanned(long taskItemId)
			throws Exception{
		PrintProvTaskItem item = taskItemRepo.findOne(taskItemId);
		if(item == null){
			throw new Exception("没有该打印任务");
		}
		item.setIsAnswerScanned(true);
		taskItemRepo.save(item);
		return item;
	}
	
}
