package com.qmth.qrzk.supplypaper.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qmth.qrzk.batch.model.PaperStateView;
import com.qmth.qrzk.dao.repositories.BatchRepo;
import com.qmth.qrzk.dao.repositories.PaperRepo;
import com.qmth.qrzk.dao.repositories.PaperStateViewRepo;
import com.qmth.qrzk.dao.repositories.PrintProvTaskRepo;
import com.qmth.qrzk.dao.repositories.ProvinceRepo;
import com.qmth.qrzk.dao.repositories.SupplyCourseRepo;
import com.qmth.qrzk.dao.repositories.SupplyProvInfoRepo;
import com.qmth.qrzk.dao.repositories.UserRepo;
import com.qmth.qrzk.dbf.XlsImportException;
import com.qmth.qrzk.paper.model.Paper;
import com.qmth.qrzk.repository.common.enumeration.BatchType;
import com.qmth.qrzk.repository.common.enumeration.PaperFormat;
import com.qmth.qrzk.repository.common.enumeration.PaperStatus;
import com.qmth.qrzk.repository.common.enumeration.PaperType;
import com.qmth.qrzk.repository.user.model.PaperBatch;
import com.qmth.qrzk.repository.user.model.Role;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.user.service.SessionUser;
import com.qmth.qrzk.repository.utils.General;
import com.qmth.qrzk.repository.utils.StringUtils;
import com.qmth.qrzk.supplypaper.model.PrintProvTask;
import com.qmth.qrzk.supplypaper.model.PrintProvTaskItem;
import com.qmth.qrzk.supplypaper.model.Province;
import com.qmth.qrzk.supplypaper.model.SupplyCourse;
import com.qmth.qrzk.supplypaper.model.SupplyProvInfo;
import com.qmth.qrzk.supplypaper.vo.ProvCourseVO;
import com.qmth.qrzk.supplypaper.vo.SupplyCourseVO;

/**
 * 供卷业务
 * @author zhengmin
 *
 */
@Service
public class SupplyService {

	@Autowired private SupplyCourseRepo scRepo;
	@Autowired private SupplyProvInfoRepo spiRepo;
	@Autowired private ProvinceRepo provRepo;
	@Autowired private BatchRepo batchRepo;
	@Autowired private PaperRepo paperRepo;
	@Autowired private UserRepo userRepo;
	@Autowired private PrintProvTaskRepo taskRepo;
	@Autowired private PaperStateViewRepo paperStateViewRepo;
	
	@Autowired private SessionUser sessionUser;
	
	/**
	 * 保存供卷课程
	 * @param course
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public SupplyCourse saveSupplyCourse(SupplyCourse course) throws Exception{
		course.setUpdatedTime(new Date());
		
		if(course.getId() == null){
			List<SupplyCourse> exist = scRepo.findByBatchIdAndCourseCode(course.getBatchId(), course.getCourseCode());
			if(exist.size() > 0){
				throw new Exception("供卷课程重复");
			}
		}
		SupplyCourse result = scRepo.saveAndFlush(course);
		spiRepo.deleteSupplyCourseIsNull();
		return result;
	}
	
	/**
	 * 删除供卷课程
	 * @param supplyCourseId
	 */
	@Transactional
	public void removeSupplyCourse(Long supplyCourseId){
		SupplyCourse entity = scRepo.findOne(supplyCourseId);
		scRepo.delete(entity);
	}
	
	/**
	 * 保存供卷省份信息
	 * @param prov
	 * @return
	 */
	@Transactional
	public Province saveProvinceInfo(Province prov){
		return provRepo.save(prov);
	}
	
	
	/**
	 * 关联试卷
	 * @param supplyCourseId
	 * @param paper
	 */
	@Transactional
	public void assignPaper(Long supplyCourseId,long paperId){
		Paper paper = paperRepo.findOne(paperId);
		List<Paper> sameCourseCodePapers = paperRepo.findByCourseCode(paper.getCourseCode());
		SupplyCourse course = scRepo.findOne(supplyCourseId);
		course.setPaperCode(paper.getCode());
		course.setPaperId(paper.getId());
		course.setPaperStatus(PaperStatus.valueOf(paper.getStatus()));
		scRepo.save(course);
		
		//如果是毛坯，创建一个复审批次，将该试卷加入
		if(paper.getStatus().equals(PaperStatus.DRAFT.toString())){
			int batchId = course.getBatchId();
			PaperBatch batch = null;
			List<PaperBatch> exists = batchRepo.findByAdmin(String.valueOf(batchId));
			if(exists.size() > 0){
				batch = exists.get(0);
			}
			else{
				PaperBatch pb = batchRepo.findOne(course.getBatchId());
				User user = (User)sessionUser.getSessionUser();
				batch = new PaperBatch(String.valueOf(new Date().getTime()), BatchType.REVIEW, new Date(), new Date(), String.valueOf(course.getBatchId()), 
							user.getId(), new Date(), user.getId(), new Date(), "启用试卷时自动创建");
				batch.setTitle(pb.getTitle()+"试卷复审");
			}
			PaperStateView psv = new PaperStateView();
			psv.setPaperId(paper.getId());
			batchRepo.save(batch);
			psv.setBatchId(batch.getId());
			paperStateViewRepo.save(psv);
			
			/**
			 * 删除相同课程其他的试卷
			 */
			for(Paper otherPaper:sameCourseCodePapers){
				if(!otherPaper.getId().equals(paper.getId())){
					PaperStateView otherPsv = new PaperStateView();
					otherPsv.setPaperId(otherPaper.getId());
					otherPsv.setBatchId(batch.getId());
					paperStateViewRepo.delete(otherPsv);
				}
			}
		}
	}
	
	
	/**
	 * 获取批次供卷省份和课程数
	 * @param batchId
	 * @return
	 */
	public List<ProvCourseVO> buildProvCourse(Integer batchId){
		List<SupplyCourse> courses = scRepo.findByBatchId(batchId,new Sort("courseCode"));
		List<SupplyProvInfo> provInfos = new ArrayList<SupplyProvInfo>();
		for(SupplyCourse c : courses){
			provInfos.addAll(c.getSupplyProvInfo());
		}
		
		Comparator<SupplyProvInfo> comparator = new Comparator<SupplyProvInfo>() {
		    public int compare(SupplyProvInfo c1, SupplyProvInfo c2) {
		        return c1.getProvCode() - c2.getProvCode();
		    }
		};
		Collections.sort(provInfos,comparator);
		List<ProvCourseVO> list = new ArrayList<ProvCourseVO>();
		if(provInfos.size() > 0){
			Province p = null;
			SupplyProvInfo first = provInfos.get(0);
			p = provRepo.findOne(first.getProvCode());
			ProvCourseVO pc = new ProvCourseVO(p);
			for(SupplyProvInfo info : provInfos){
				if(info.getProvCode() == pc.getProvCode()){
					pc.addCourse(new SupplyCourseVO(info.getCourseCode(), info.getCourseName(), info.getPaperFormatLabel(), ""));
				}
				else{
					list.add(pc);
					p = provRepo.findOne(info.getProvCode());
					pc = new ProvCourseVO(p);
					pc.addCourse(new SupplyCourseVO(info.getCourseCode(), info.getCourseName(), info.getPaperFormatLabel(), ""));
					
				}
			}
			list.add(pc);
		}
		
		return list;
	}
	
	/**
	 * 查找所有录入员用户
	 * @return
	 */
	public List<User> findInputerUsers(){
		return userRepo.findByRole(Role.INPUT_ROLE_CODE);
	}
	
	/**
	 * 导入供卷课程(旧)
	 * @param is
	 * @param batchId
	 * @throws XlsImportException 
	 */
	@Transactional
	public void addSupplyCourseFromCourse(InputStream is,Integer batchId) throws XlsImportException{
		int curRowIndex = 0;
		int curCellIndex = 0;
		String curCellStr = null;
		try{
			//导入前清空该批次下所有课程
			List<SupplyCourse> list = scRepo.findByBatchId(batchId, null);
			for(SupplyCourse sc : list){
				scRepo.delete(sc);
			}
			//excel导入
			Workbook wb = new HSSFWorkbook(is);  
			Sheet sheet = wb.getSheetAt(0);
			int rowIndex = 0;
			List<SupplyProvInfo> provInfos = null;
			List<Province> provs = provRepo.findAll();
			if(provs.size() > 0 && provs.get(0).getCode() == Province.NATION_CODE){
				provs.remove(0);
			}
			for (Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) {
				curRowIndex = rowIndex;
	            Row row = rit.next();  
//	            int cellIndex = 0;
	            String courseCode = null;
	            String courseName = null;
	            int mergeCount = 0;
	            int sepCount = 0;
	            provInfos = new ArrayList<SupplyProvInfo>();
	            if(rowIndex != 0 && rowIndex != 1 && sheet.getLastRowNum() != rowIndex){
		            for (int cellIndex=0;cellIndex<36;cellIndex++) {
//		            for (Iterator<Cell> cit = row.cellIterator(); cit.hasNext();) {
		            	Cell cell = row.getCell(cellIndex);
		            	if(cell == null){
		            		continue;
		            	}
		            	
		                String strCell = General.getCellTextForShow((HSSFCell)cell);
		                curCellIndex = cellIndex;
		                curCellStr = strCell;
		                if(cellIndex == 1){
		            		courseCode = strCell;
		            	}
		                else if(cellIndex == 2){
		                	courseName = strCell;
		                }
		                else if(cellIndex == 3){
		                	if(General.isEmpty(strCell)){
		                		strCell = "0";
		                	}
		                	if((mergeCount = General.toInteger(strCell, -100)) == -100){
		                		throw new XlsImportException("无法解析单元格" + General.toExcelCoordinate(rowIndex, cellIndex) + "里面的合卷值：[" + strCell + "]");
		                	}
		                }
		                else if(cellIndex == 4){
		                	if(General.isEmpty(strCell)){
		                		strCell = "0";
		                	}
		                	if((sepCount = General.toInteger(strCell, -100)) == -100){
		                		throw new XlsImportException("无法解析单元格" + General.toExcelCoordinate(rowIndex, cellIndex) + "里面的分卷值：[" + strCell + "]");
		                	}
		                }
		                else if(cellIndex >= 5){
		                	if(StringUtils.isNotEmpty(strCell)){
		                		PaperFormat format = (strCell.trim().equals("合") || strCell.trim().equals("合卷"))?PaperFormat.MERGE : PaperFormat.SEPERATE;
			                	Province prov = provs.get(cellIndex - 5);
			                	System.out.print(prov.getName() + "(" + (cellIndex+1) + ")----");
			                	SupplyProvInfo info = new SupplyProvInfo();
			                	info.setProvCode(prov.getCode());
			                	info.setProvName(prov.getName());
			                	info.setPaperFormat(format);
			                	info.setBatchId(batchId);
			                	info.setCourseCode(courseCode);
			                	info.setCourseName(courseName);
			                	info.setPaperType(prov.getPaperType() != null?prov.getPaperType():PaperType.BLANK);
			                	provInfos.add(info);
		                	}
		                }
//		                cellIndex++;
		                System.out.print(strCell+" ");
		            }  
		            
		            List<Province> guoJia = provRepo.findByCode(Province.NATION_CODE);
		            if(guoJia.size() > 0){
		            	Province p = guoJia.get(0);
		            	SupplyProvInfo info = new SupplyProvInfo();
		            	info.setProvCode(p.getCode());
		            	info.setProvName(p.getName());
		            	info.setPaperFormat(PaperFormat.ALL);
		            	info.setBatchId(batchId);
		            	info.setCourseCode(courseCode);
		            	info.setCourseName(courseName);
		            	info.setPaperType(p.getPaperType() != null?p.getPaperType():PaperType.BLANK);
		            	provInfos.add(info);
		            }
	            	
		            SupplyCourse sc = new SupplyCourse();
		            sc.setCourseCode(courseCode);
		            sc.setCourseName(courseName);
		            sc.setBatchId(batchId);
		            sc.setMergeCount(mergeCount);
		            sc.setSepCount(sepCount);
		            sc.setTotal(sepCount+mergeCount);
		            sc.setSupplyProvInfo(provInfos);
		            scRepo.save(sc);
	            }
	            rowIndex++;
	            System.out.println("");
	        }
		}catch(XlsImportException e){
			throw e;
		}catch(Exception e){
			throw new XlsImportException("解析Excel出现异常，单元格坐标" + General.toExcelCoordinate(curRowIndex, curCellIndex) + "，值=[" + curCellStr + "]", e);
		}
	}
	
	/**
	 * 根据省份课程设置，构建任务条目
	 * @param batchId 批次id
	 * @param provCode 省份代码
	 * @return
	 */
	private List<PrintProvTaskItem> buildTaskItems(int batchId,int provCode){
		List<PrintProvTaskItem> result = new ArrayList<PrintProvTaskItem>();
		Sort sort = new Sort("courseCode");
		if(provCode == Province.NATION_CODE){
			List<SupplyCourse> allCourses = scRepo.findByBatchId(batchId, new Sort("courseCode"));
			for(SupplyCourse course : allCourses){
				PrintProvTaskItem taskItem = new PrintProvTaskItem(batchId,course.getCourseCode(), 
						course.getCourseName(), PrintProvTaskItem.PAPER_FORMAT_ALL,course.getPaperId(),
						2, 0);
				taskItem.setAnswerCount(1);
				result.add(taskItem);
			}
		}
		else{
			List<SupplyProvInfo> sichuan = spiRepo.findByBatchIdAndProvCode(batchId, Province.SICHUAN_CODE, null);
			List<SupplyProvInfo> list = spiRepo.findByBatchIdAndProvCode(batchId, provCode, sort);
			for(SupplyProvInfo spi : list){
				int paperFormat = PrintProvTaskItem.PAPER_FORMAT_MERGE;
				PaperFormat pf = spi.getPaperFormat();
				switch(pf){
				case MERGE:
					paperFormat = PrintProvTaskItem.PAPER_FORMAT_MERGE;
					break;
				case SEPERATE:
					paperFormat = PrintProvTaskItem.PAPER_FORMAT_SEPARATE;
				}
				int blankCount = 0;
				int acidCount = 0;
				PaperType pt = spi.getPaperType();
				switch(pt){
				case BLANK:
					blankCount = 2;
					break;
				case ACID:
					blankCount = 1;
					acidCount = 1;
					break;
				}
				if(provCode == Province.XIZANG_CODE){
					int idx = sichuan.indexOf(spi);
					if(idx > -1){
						blankCount = 0;
						acidCount = 0;
					}
				}
				PrintProvTaskItem taskItem = new PrintProvTaskItem(batchId,spi.getCourseCode(), spi.getCourseName(), 
						paperFormat, spi.getSupplyCourse().getPaperId(),blankCount, acidCount);
				taskItem.setAnswerCount(2);
				result.add(taskItem);
			}
		}
		return result;
	}
	
	@Transactional
	public void assignProvToUser(Integer batchId) throws Exception{
		//自动分配前先删除所有任务及课程
		List<PrintProvTask> tasks = taskRepo.findByBatchId(batchId, null);
		for(PrintProvTask t : tasks){
			taskRepo.delete(t);
		}
		List<ProvCourseVO> provs = this.buildProvCourse(batchId);
		//剔出四川和西藏
		ProvCourseVO sichuan = null;
		ProvCourseVO xizang = null;
		for(int i = 0 ; i < provs.size(); i++){
			if(provs.get(i).getProvCode() == Province.SICHUAN_CODE){
				sichuan = provs.get(i);
				provs.remove(i);
				i--;
			}
			if(provs.get(i).getProvCode() == Province.XIZANG_CODE){
				xizang = provs.get(i);
				provs.remove(i);
				i--;
			}
		}
		//加入国家
//		ProvCourseVO pc = new ProvCourseVO(Province.NATION_CODE, "国家",PaperType.BLANK);
//		List<SupplyCourse> allCourses = scRepo.findByBatchId(batchId, new Sort("courseCode"));
//		for(SupplyCourse sc : allCourses){
//			pc.addCourse(new SupplyCourseVO(sc.getCourseCode(), sc.getCourseName(), null));
//		}
//		provs.add(pc);
		
		//按课程数倒序排序
		Comparator<ProvCourseVO> comparator = new Comparator<ProvCourseVO>() {
		    public int compare(ProvCourseVO c1, ProvCourseVO c2) {
		        return c2.getCourseCount() - c1.getCourseCount();
		    }
		};
		Collections.sort(provs,comparator);
		
		/**
		 * 将首位轮询分配给录入员
		 */
		List<User> inputors = userRepo.findByRole(Role.INPUT_ROLE_CODE);
		if(inputors.size() == 0){
			throw new RuntimeException("系统没有配置录入员！");
		}
		int turn = provs.size()/2;
		int userIndex = 0;
		for(int i = 0;i<turn;i++){
			PrintProvTask taskA = new PrintProvTask();
			taskA.setBatchId(batchId);
			taskA.setUserId(inputors.get(userIndex).getId());
			taskA.setUsername(inputors.get(userIndex).getName());
			taskA.setPaperType(provs.get(i).getPaperType());
			taskA.setProvCode(provs.get(i).getProvCode());
			taskA.setCourseCount(provs.get(i).getCourseCount());
			taskA.setProvName(provs.get(i).getProvName());
			inputors.get(userIndex).addTask(taskA);
			List<PrintProvTaskItem> items = buildTaskItems(batchId, provs.get(i).getProvCode());
			taskA.setTaskItems(items);
			taskRepo.save(taskA);
			
			PrintProvTask taskB = new PrintProvTask();
			taskB.setBatchId(batchId);
			taskB.setUserId(inputors.get(userIndex).getId());
			taskB.setUsername(inputors.get(userIndex).getName());
			taskB.setPaperType(provs.get(turn*2-1-i).getPaperType());
			taskB.setProvCode(provs.get(turn*2-1-i).getProvCode());
			taskB.setCourseCount(provs.get(turn*2-1-i).getCourseCount());
			taskB.setProvName(provs.get(turn*2-i-1).getProvName());
			inputors.get(userIndex).addTask(taskB);
			List<PrintProvTaskItem> itemsB = buildTaskItems(batchId, provs.get(turn*2-1-i).getProvCode());
			taskB.setTaskItems(itemsB);
			taskRepo.save(taskB);
			
			if(userIndex < inputors.size()-1){
				userIndex++;
			}
			else{
				userIndex = 0;
			}
			
		}
		//找出最少的用户任务，将四川和西藏分配给他
		Comparator<User> userComp = new Comparator<User>() {
		    public int compare(User c1, User c2) {
		        return c1.getTasks().size() - c2.getTasks().size();
		    }
		};
		Collections.sort(inputors,userComp);
		User minUser = inputors.get(0);
		PrintProvTask taskSC = new PrintProvTask();
		taskSC.setBatchId(batchId);
		taskSC.setUserId(minUser.getId());
		taskSC.setUsername(minUser.getName());
		if(sichuan == null){
			throw new RuntimeException("没有给四川配置供卷！");
		}
		taskSC.setPaperType(sichuan.getPaperType());
		taskSC.setProvCode(sichuan.getProvCode());
		taskSC.setCourseCount(sichuan.getCourseCount());
		taskSC.setProvName(sichuan.getProvName());
		List<PrintProvTaskItem> itemsSC = buildTaskItems(batchId, Province.SICHUAN_CODE);
		taskSC.setTaskItems(itemsSC);
		taskRepo.save(taskSC);
		
		PrintProvTask taskXZ = new PrintProvTask();
		taskXZ.setBatchId(batchId);
		taskXZ.setUserId(minUser.getId());
		taskXZ.setUsername(minUser.getName());
		if(xizang == null){
			throw new RuntimeException("没有给西藏配置供卷！");
		}
		taskXZ.setPaperType(xizang.getPaperType());
		taskXZ.setProvCode(xizang.getProvCode());
		taskXZ.setCourseCount(xizang.getCourseCount());
		taskXZ.setProvName(xizang.getProvName());
		List<PrintProvTaskItem> itemsXZ = buildTaskItems(batchId, Province.XIZANG_CODE);
		taskXZ.setTaskItems(itemsXZ);
		taskRepo.save(taskXZ);
	}
	
	@Transactional
	public void assignProvScanTaskToUser(Integer batchId) throws Exception{
		//自动分配前先删除所有任务及课程
//		List<PrintProvTask> tasks = taskRepo.findByBatchId(batchId, null);
//		for(PrintProvTask t : tasks){
//			taskRepo.delete(t);
//		}
		List<ProvCourseVO> provs = this.buildProvCourse(batchId);
		//剔出四川和西藏
		ProvCourseVO sichuan = null;
		ProvCourseVO xizang = null;
		for(int i = 0 ; i < provs.size(); i++){
			if(provs.get(i).getProvCode() == Province.SICHUAN_CODE){
				sichuan = provs.get(i);
				provs.remove(i);
			}
			if(provs.get(i).getProvCode() == Province.XIZANG_CODE){
				xizang = provs.get(i);
				provs.remove(i);
			}
		}
		
		//按课程数倒序排序
		Comparator<ProvCourseVO> comparator = new Comparator<ProvCourseVO>() {
			public int compare(ProvCourseVO c1, ProvCourseVO c2) {
				return c2.getCourseCount() - c1.getCourseCount();
			}
		};
		Collections.sort(provs,comparator);
		
		/**
		 * 将首位轮询分配给录入员
		 */
		List<User> inputors = userRepo.findByRole(Role.INPUT_ROLE_CODE);
		if(inputors.size() == 0){
			throw new Exception("没有可分配的录入员！");
		}
		int turn = provs.size()/2;
		int userIndex = 0;
		for(int i = 0;i<turn;i++){
			PrintProvTask taskA = new PrintProvTask();
			taskA.setBatchId(batchId);
			taskA.setUserId(inputors.get(userIndex).getId());
			taskA.setUsername(inputors.get(userIndex).getName());
			taskA.setPaperType(provs.get(i).getPaperType());
			taskA.setProvCode(provs.get(i).getProvCode());
			taskA.setCourseCount(provs.get(i).getCourseCount());
			taskA.setProvName(provs.get(i).getProvName());
			inputors.get(userIndex).addTask(taskA);
			List<PrintProvTaskItem> items = buildTaskItems(batchId, provs.get(i).getProvCode());
			taskA.setTaskItems(items);
			taskRepo.save(taskA);
			
			PrintProvTask taskB = new PrintProvTask();
			taskB.setBatchId(batchId);
			taskB.setUserId(inputors.get(userIndex).getId());
			taskB.setUsername(inputors.get(userIndex).getName());
			taskB.setPaperType(provs.get(turn*2-1-i).getPaperType());
			taskB.setProvCode(provs.get(turn*2-1-i).getProvCode());
			taskB.setCourseCount(provs.get(turn*2-1-i).getCourseCount());
			taskB.setProvName(provs.get(turn*2-i-1).getProvName());
			inputors.get(userIndex).addTask(taskB);
			List<PrintProvTaskItem> itemsB = buildTaskItems(batchId, provs.get(turn*2-1-i).getProvCode());
			taskB.setTaskItems(itemsB);
			taskRepo.save(taskB);
			
			if(userIndex < inputors.size()-1){
				userIndex++;
			}
			else{
				userIndex = 0;
			}
			
		}
		//找出最少的用户任务，将四川和西藏分配给他
		Comparator<User> userComp = new Comparator<User>() {
			public int compare(User c1, User c2) {
				return c1.getTasks().size() - c2.getTasks().size();
			}
		};
		Collections.sort(inputors,userComp);
		User minUser = inputors.get(0);
		PrintProvTask taskSC = new PrintProvTask();
		taskSC.setBatchId(batchId);
		taskSC.setUserId(minUser.getId());
		taskSC.setUsername(minUser.getName());
		taskSC.setPaperType(sichuan.getPaperType());
		taskSC.setProvCode(sichuan.getProvCode());
		taskSC.setCourseCount(sichuan.getCourseCount());
		taskSC.setProvName(sichuan.getProvName());
		List<PrintProvTaskItem> itemsSC = buildTaskItems(batchId, Province.SICHUAN_CODE);
		taskSC.setTaskItems(itemsSC);
		taskRepo.save(taskSC);
		
		PrintProvTask taskXZ = new PrintProvTask();
		taskXZ.setBatchId(batchId);
		taskXZ.setUserId(minUser.getId());
		taskXZ.setUsername(minUser.getName());
		taskXZ.setPaperType(xizang.getPaperType());
		taskXZ.setProvCode(xizang.getProvCode());
		taskXZ.setCourseCount(xizang.getCourseCount());
		taskXZ.setProvName(xizang.getProvName());
		List<PrintProvTaskItem> itemsXZ = buildTaskItems(batchId, Province.XIZANG_CODE);
		taskXZ.setTaskItems(itemsXZ);
		taskRepo.save(taskXZ);
	}
	
	/**
	 * 导入供卷课程(新)    合计	各省申报分布情况																														
	 * @param is
	 * @param batchId
	 * @throws XlsImportException 
	 */
/*	@Transactional
	public void addNewSupplyCourseFromCourse(InputStream is,Integer batchId) throws XlsImportException{
		int curRowIndex = 0;
		int curCellIndex = 0;
		String curCellStr = null;
		try{
			//导入前清空该批次下所有课程
			List<SupplyCourse> list = scRepo.findByBatchId(batchId, null);
			for(SupplyCourse sc : list){
				scRepo.delete(sc);
			}
			//excel导入
			Workbook wb = new HSSFWorkbook(is);  
			Sheet sheet = wb.getSheetAt(0);
			int rowIndex = 0;
			List<SupplyProvInfo> provInfos = null;
			List<Province> provs = provRepo.findAll();
			if(provs.size() > 0 && provs.get(0).getCode() == Province.NATION_CODE){
				provs.remove(0);
			}
			for (Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) {
				curRowIndex = rowIndex;
	            Row row = rit.next();  
//	            int cellIndex = 0;
	            String courseCode = null;
	            String courseName = null;
	            int mergeCount = 0;
	            int sepCount = 0;
	            provInfos = new ArrayList<SupplyProvInfo>();
	            if(rowIndex != 0 && rowIndex != 1 && sheet.getLastRowNum() != rowIndex){
		            for (int cellIndex=0;cellIndex<36;cellIndex++) {
//		            for (Iterator<Cell> cit = row.cellIterator(); cit.hasNext();) {
		            	Cell cell = row.getCell(cellIndex);
		            	if(cell == null){
		            		continue;
		            	}
		            	
		                String strCell = General.getCellTextForShow((HSSFCell)cell);
		                curCellIndex = cellIndex;
		                curCellStr = strCell;
		                if(cellIndex == 1){
		            		courseCode = strCell;
		            	}
		                else if(cellIndex == 2){
		                	courseName = strCell;
		                }
		                else if(cellIndex == 3){ //考试单元
		                	System.out.print("考试单元："+strCell);
		                }
		                else if(cellIndex == 4){
		                	System.out.print("考试类型："+strCell);
		                }
		                else if(cellIndex == 5){
		                	if(General.isEmpty(strCell)){
		                		strCell = "0";
		                	}
		                	if((sepCount = General.toInteger(strCell, -100)) == -100){
		                		throw new XlsImportException("无法解析单元格" + General.toExcelCoordinate(rowIndex, cellIndex) + "里面的合计值：[" + strCell + "]");
		                	}
		                }
		                else if(cellIndex >= 6){
		                	if(StringUtils.isNotEmpty(strCell)){
		                		PaperFormat format = (strCell.trim().equals("合") || strCell.trim().equals("合卷"))?PaperFormat.MERGE : PaperFormat.SEPERATE;
			                	Province prov = provs.get(cellIndex - 5);
			                	System.out.print(prov.getName() + "(" + (cellIndex+1) + ")----");
			                	SupplyProvInfo info = new SupplyProvInfo();
			                	info.setProvCode(prov.getCode());
			                	info.setProvName(prov.getName());
			                	info.setPaperFormat(format);
			                	info.setBatchId(batchId);
			                	info.setCourseCode(courseCode);
			                	info.setCourseName(courseName);
			                	info.setPaperType(prov.getPaperType() != null?prov.getPaperType():PaperType.BLANK);
			                	provInfos.add(info);
		                	}
		                }
//		                cellIndex++;
		                System.out.print(strCell+" ");
		            }  
		            
		            List<Province> guoJia = provRepo.findByCode(Province.NATION_CODE);
		            if(guoJia.size() > 0){
		            	Province p = guoJia.get(0);
		            	SupplyProvInfo info = new SupplyProvInfo();
		            	info.setProvCode(p.getCode());
		            	info.setProvName(p.getName());
		            	info.setPaperFormat(PaperFormat.ALL);
		            	info.setBatchId(batchId);
		            	info.setCourseCode(courseCode);
		            	info.setCourseName(courseName);
		            	info.setPaperType(p.getPaperType() != null?p.getPaperType():PaperType.BLANK);
		            	provInfos.add(info);
		            }
	            	
		            SupplyCourse sc = new SupplyCourse();
		            sc.setCourseCode(courseCode);
		            sc.setCourseName(courseName);
		            sc.setBatchId(batchId);
		            sc.setMergeCount(mergeCount);
		            sc.setSepCount(sepCount);
		            sc.setTotal(sepCount+mergeCount);
		            sc.setSupplyProvInfo(provInfos);
		            scRepo.save(sc);
	            }
	            rowIndex++;
	            System.out.println("");
	        }
		}catch(XlsImportException e){
			throw e;
		}catch(Exception e){
			throw new XlsImportException("解析Excel出现异常，单元格坐标" + General.toExcelCoordinate(curRowIndex, curCellIndex) + "，值=[" + curCellStr + "]", e);
		}
	}*/
	
	/**
	 * 导入供卷课程(旧)  合计	  北京  天津 河北  山西  内蒙古  辽宁  吉林  黑龙江  上海
	 * @param is
	 * @param batchId
	 * @throws XlsImportException 
	 */
	@Transactional
	public void addNewSupplyCourseFromCourse(InputStream is,Integer batchId) throws XlsImportException{
		int curRowIndex = 0;
		int curCellIndex = 0;
		String curCellStr = null;
		try{
			//导入前清空该批次下所有课程
			List<SupplyCourse> list = scRepo.findByBatchId(batchId, null);
			for(SupplyCourse sc : list){
				scRepo.delete(sc);
			}
			//excel导入
			Workbook wb = new HSSFWorkbook(is);  
			Sheet sheet = wb.getSheetAt(0);
			int rowIndex = 0;
			List<SupplyProvInfo> provInfos = null;
			List<Province> provs = provRepo.findAll();
			if(provs.size() > 0 && provs.get(0).getCode() == Province.NATION_CODE){
				provs.remove(0);
			}
			for (Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) {
				curRowIndex = rowIndex;
	            Row row = rit.next();  
//	            int cellIndex = 0;
	            String courseCode = null;
	            String courseName = null;
	            int mergeCount = 0;
	            int sepCount = 0;
	            provInfos = new ArrayList<SupplyProvInfo>();
	            if(rowIndex != 0 && rowIndex != 1 && sheet.getLastRowNum() != rowIndex){
		            for (int cellIndex=0;cellIndex<37;cellIndex++) {
//		            for (Iterator<Cell> cit = row.cellIterator(); cit.hasNext();) {
		            	Cell cell = row.getCell(cellIndex);
		            	if(cell == null){
		            		continue;
		            	}
		            	
		                String strCell = General.getCellTextForShow((HSSFCell)cell);
		                curCellIndex = cellIndex;
		                curCellStr = strCell;
		                if(cellIndex == 1){
		            		courseCode = strCell;
		            	}
		                else if(cellIndex == 2){
		                	courseName = strCell;
		                }
		                else if(cellIndex == 3){ //考试单元
		                	System.out.print("考试单元："+strCell);
		                }
		                else if(cellIndex == 4){
		                	System.out.print("考试类型："+strCell);
		                }
		                else if(cellIndex == 5){
		                	if(General.isEmpty(strCell)){
		                		strCell = "0";
		                	}
		                	if((sepCount = General.toInteger(strCell, -100)) == -100){
		                		throw new XlsImportException("无法解析单元格" + General.toExcelCoordinate(rowIndex, cellIndex) + "里面的合计值：[" + strCell + "]");
		                	}
		                }
		                else if(cellIndex >= 6){
		                	if(StringUtils.isNotEmpty(strCell)){
		                		PaperFormat format = (strCell.trim().equals("合") || strCell.trim().equals("合卷"))?PaperFormat.MERGE : PaperFormat.SEPERATE;
			                	Province prov = provs.get(cellIndex - 6);// list中的省份排序=当前excel中的值-当前列的值
			                	System.out.print(prov.getName() + "(" + (cellIndex+1) + ")----");
			                	
			                	String newEdition = strCell;  //[2017新版]是否有值
			                	if(!newEdition.isEmpty()) {
				                	SupplyProvInfo info = new SupplyProvInfo();
				                	info.setProvCode(prov.getCode());
				                	info.setProvName(prov.getName());
				                	info.setPaperFormat(format);
				                	info.setBatchId(batchId);
				                	info.setCourseCode(courseCode);
				                	info.setCourseName(courseName);
				                	if( "2017新版".equals(strCell)) {
				                		info.setPaperType(getType(getIndexProName(cellIndex)));
				                	}else {
				                		info.setPaperType(getType(strCell));
				                	}
//				                	info.setPaperType(PaperType.BLANK);
				                	provInfos.add(info);
			                	}
		                	}
		                }
//		                cellIndex++;
		                System.out.print(strCell+" ");
		            }  
		            
		            List<Province> guoJia = provRepo.findByCode(Province.NATION_CODE);
		            if(guoJia.size() > 0){
		            	Province p = guoJia.get(0);
		            	SupplyProvInfo info = new SupplyProvInfo();
		            	info.setProvCode(p.getCode());
		            	info.setProvName(p.getName());
		            	//info.setPaperFormat(PaperFormat.ALL);
		            	info.setPaperFormat(PaperFormat.SEPERATE); //国家的所有改成网评卷
		            	info.setBatchId(batchId);
		            	info.setCourseCode(courseCode);
		            	info.setCourseName(courseName);
//		            	info.setPaperType(p.getPaperType() != null?p.getPaperType():PaperType.BLANK);
		            	info.setPaperType(PaperType.BLANK);  //白纸
		            	provInfos.add(info);
		            }
	            	
		            SupplyCourse sc = new SupplyCourse();
		            sc.setCourseCode(courseCode);
		            sc.setCourseName(courseName);
		            sc.setBatchId(batchId);
		            sc.setMergeCount(mergeCount);
		            sc.setSepCount(sepCount + 1);    //2019-10-08 张璇沟通国家省份全部是网评卷
//		            sc.setSepCount(sepCount);
		            sc.setTotal(sepCount+mergeCount + 1);  //2019-10-08 张璇沟通国家省份全部是网评卷
//		            sc.setTotal(sepCount+mergeCount);
		            sc.setSupplyProvInfo(provInfos);
		            scRepo.save(sc);
	            }
	            rowIndex++;
	            System.out.println("");
	        }
		}catch(XlsImportException e){
			throw e;
		}catch(Exception e){
			throw new XlsImportException("解析Excel出现异常，单元格坐标" + General.toExcelCoordinate(curRowIndex, curCellIndex) + "，值=[" + curCellStr + "]", e);
		}
	}
	
	public PaperType getType(String name) {
		Map<String, String> map = new HashMap<String, String>();	
		map.put("国家","NULL");
		map.put("北京","ACID");
		map.put("天津","ACID");
		map.put("河北","ACID");
		map.put("山西","ACID");
		map.put("内蒙古","ACID");
		map.put("辽宁","BLANK");
		map.put("吉林","BLANK");
		map.put("黑龙江","BLANK");
		map.put("上海","BLANK");
		map.put("江苏","ACID");
		map.put("浙江","ACID");
		map.put("安徽","BLANK");
		map.put("福建","ACID");
		map.put("江西","BLANK");
		map.put("山东","BLANK");
		map.put("河南","ACID");
		map.put("湖北","BLANK");
		map.put("湖南","BLANK");
		map.put("广东","BLANK");
		map.put("广西","ACID");
		map.put("海南","BLANK");
		map.put("重庆","ACID");
		map.put("四川","ACID");
		map.put("贵州","ACID");
		map.put("云南","ACID");
		map.put("西藏","ACID");
		map.put("陕西","BLANK");
		map.put("甘肃","ACID");
		map.put("青海","ACID");
		map.put("宁夏","ACID");
		map.put("新疆","BLANK");
		
		String type = map.get(name);
		PaperType paperType = null;
		if(type=="NULL") {
			paperType = PaperType.NULL;
		}else if(type=="ACID") {
			paperType = PaperType.ACID;
		}else if(type=="BLANK") {
			paperType = PaperType.BLANK;
		}
		return paperType;
	}
	
	public String getIndexProName(int cellIndex) {
		Map<String, String> map = new HashMap<String, String>();	
		map.put("6","北京");
		map.put("7","天津");
		map.put("8","河北");
		map.put("9","山西");
		map.put("10","内蒙古");
		map.put("11","辽宁");
		map.put("12","吉林");
		map.put("13","黑龙江");
		map.put("14","上海");
		map.put("15","江苏");
		map.put("16","浙江");
		map.put("17","安徽");
		map.put("18","福建");
		map.put("19","江西");
		map.put("20","山东");
		map.put("21","河南");
		map.put("22","湖北");
		map.put("23","湖南");
		map.put("24","广东");
		map.put("25","广西");
		map.put("26","海南");
		map.put("27","重庆");
		map.put("28","四川");
		map.put("29","贵州");
		map.put("30","云南");
		map.put("31","西藏");
		map.put("32","陕西");
		map.put("33","甘肃");
		map.put("34","青海");
		map.put("35","宁夏");
		map.put("36","新疆");
		
		String proName = map.get(String.valueOf(cellIndex));
		return proName;
	}
	
}
