package com.qmth.qrzk.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qmth.qrzk.dao.repositories.PaperRepo;
import com.qmth.qrzk.dao.repositories.ProvinceRepo;
import com.qmth.qrzk.dao.repositories.SupplyConfigRepo;
import com.qmth.qrzk.dao.repositories.SupplyCourseRepo;
import com.qmth.qrzk.dao.repositories.SupplyProvInfoRepo;
import com.qmth.qrzk.paper.model.Paper;
import com.qmth.qrzk.repository.utils.StringUtils;
import com.qmth.qrzk.supplypaper.model.Province;
import com.qmth.qrzk.supplypaper.model.SupplyConfig;
import com.qmth.qrzk.supplypaper.model.SupplyCourse;
import com.qmth.qrzk.supplypaper.model.SupplyProvInfo;
import com.qmth.qrzk.supplypaper.service.SupplyService;
import com.qmth.qrzk.supplypaper.vo.ProvCourseVO;
import com.qmth.qrzk.supplypaper.vo.SupplyCourseVO;

/**
 * 用于打印
 * @author zhengmin
 *
 */
@Controller
@RequestMapping("print")
public class PrintController {

	@Autowired private SupplyService supplySrv;
	@Autowired private SupplyProvInfoRepo supplyProvInfoRepo;
	@Autowired private ProvinceRepo provRepo;
	@Autowired private SupplyConfigRepo configRepo;
	@Autowired private SupplyCourseRepo scRepo;
	@Autowired private PaperRepo paperRepo;
	
	private final int PRINT_TYPE_PAPER = 1;
	private final int PRINT_TYPE_ANSWER = 2;
	
	@RequestMapping(value="supply/provinces/{batchId}",method=RequestMethod.GET)
	@ResponseBody
	public List<Object[]> printProvs(@PathVariable int batchId){
		List<Object[]> provs = supplyProvInfoRepo.findDistinctProvs(batchId);
		return provs;
	}
	
	/**
	 * 打印回执单
	 * @param batchId 批次id
	 * @param provCode 可选，省份
	 * @param printType 打印试卷还是标答
	 * @return
	 */
	@RequestMapping(value="supply/paperreceipt/{batchId}",method=RequestMethod.GET)
	public ModelAndView paperReceipt(@PathVariable int batchId,@RequestParam(required=false) Integer provCode,
			@RequestParam int printType){
		ModelAndView view = new ModelAndView("print/paperReceipt");
		List<ProvCourseVO> list = null;
		//----------------------------------------------------------------//2018-7-19
		List<Paper> papers = paperRepo.findBySupplyBatchId(batchId);
		Map<String, String> map = new HashMap<String, String>();
		for (Paper p : papers) {
			if (StringUtils.isNotEmpty(p.getZyPath())) {
				map.put(p.getCourseCode(), "转印说明");
			}
		}
		//----------------------------------------------------------------//2018-7-19
		if(provCode == null){
			list = supplySrv.buildProvCourse(batchId);
		}
		else{
			Province p = provRepo.findOne(provCode);
			ProvCourseVO pvo = new ProvCourseVO(p);
			List<SupplyProvInfo> infos = supplyProvInfoRepo.findByBatchIdAndProvCode(batchId, provCode,new Sort("courseCode"));
			for(SupplyProvInfo info : infos){//2018-7-19
				SupplyCourseVO cvo = new SupplyCourseVO(info.getCourseCode(), info.getCourseName(), info.getPaperFormatLabel(), map.get(info.getCourseCode()));
				pvo.addCourse(cvo);
			}
			list = new ArrayList<ProvCourseVO>();
			list.add(pvo);
		}
		
		//打印试卷回执单时，将合卷与分卷合并分组
		if(printType == PRINT_TYPE_PAPER){
			for(ProvCourseVO pvo : list){
				List<SupplyCourseVO> courses = pvo.getCourses();
				String lastCoursePaperFormat = "";
				ArrayList<ArrayList<SupplyCourseVO>> courseGroups = new ArrayList<ArrayList<SupplyCourseVO>>();
				
				List<SupplyCourseVO> curCourseGroup = new ArrayList<SupplyCourseVO>();
				for(SupplyCourseVO course : courses){
					if("".equals(lastCoursePaperFormat) || !course.getPaperFormat().equals(lastCoursePaperFormat)){
						lastCoursePaperFormat = course.getPaperFormat();
						ArrayList<SupplyCourseVO> courseGroup = new ArrayList<SupplyCourseVO>();
						courseGroups.add(courseGroup);	
						curCourseGroup = courseGroup;
					}
					course.setZyDesc(map.get(course.getCourseCode()));//2018-7-19
					curCourseGroup.add(course);
				}
				
				pvo.setCourseGroups(courseGroups);
			}
		}
		
		//返回参数设置信息
		List<SupplyConfig> configList = configRepo.findByBatchId(batchId);
		if(configList.size()>0){
			view.addObject("config",configList.get(0));
		}
		String label = null;
		switch(printType){
		case PRINT_TYPE_PAPER:
			label = "试卷";
			break;
		case PRINT_TYPE_ANSWER:
			label = "试题参考答案及评分标准";
			break;
			
		}
		view.addObject("label",label);
		view.addObject("printType",printType);
		view.addObject("list",list);
		return view;
	}
	
	/**
	 * 打印省份标签
	 * @param batchId
	 * @param provCode
	 * @return
	 */
	@RequestMapping(value="supply/label/{batchId}",method=RequestMethod.GET)
	public ModelAndView printProvLabel(@PathVariable int batchId,@RequestParam(required=false) Integer provCode){
		ModelAndView view = new ModelAndView("print/provLabel");
		List<String> labels = new ArrayList<String>();
		if(provCode == null){
			List<Object[]> provs = supplyProvInfoRepo.findDistinctProvs(batchId);
			for(Object[] p : provs){
				labels.add(String.valueOf(p[1]));
			}
		}
		else{
			Province p = provRepo.findOne(provCode);
			labels.add(p.getName());
		}
		List<SupplyConfig> configList = configRepo.findByBatchId(batchId);
		if(configList.size()>0){
			view.addObject("config",configList.get(0));
		}
		view.addObject("labels",labels);
		return view;
	}
	
	/**
	 * 打印地址
	 * @param batchId
	 * @param provCode
	 * @return
	 */
	@RequestMapping(value="supply/address/{batchId}",method=RequestMethod.GET)
	public ModelAndView printAddress(@PathVariable int batchId,@RequestParam(required=false) Integer provCode){
		ModelAndView view = new ModelAndView("print/address");
		List<Province> address = new ArrayList<Province>();
		List<ProvCourseVO> list = null;
		if(provCode == null){
			list = supplySrv.buildProvCourse(batchId);
			for(ProvCourseVO vo : list){
				Province p = new Province();
				p.setCode(vo.getProvCode());
				p.setName(vo.getProvName());
				p.setOffice(vo.getOffice());
				p.setZipcode(vo.getZipcode());
				p.setAddress(vo.getAddress());
				p.setPhone(vo.getPhone());
				p.setReceiver(vo.getReceiver());
				int courseCount = vo.getCourseCount();
				if(p.getCode() == Province.SICHUAN_CODE){
					int addCnt = supplyProvInfoRepo.countXIZANGAlone(batchId);
					courseCount += addCnt;
				}
				int rem = courseCount%5;
				int labelCount = courseCount/5;
				if(rem > 0)
					labelCount++;
				
				for(int i= 0;i<labelCount;i++){
					if(p.getCode() != Province.XIZANG_CODE)
					address.add(p);
				}
			}
		}
		else if(provCode != Province.XIZANG_CODE){
			Province p = provRepo.findOne(provCode);
			int courseCount = supplyProvInfoRepo.countByProvCodeAndBatchId(provCode, batchId);
			if(provCode == Province.SICHUAN_CODE){
				int addCnt = supplyProvInfoRepo.countXIZANGAlone(batchId);
				courseCount += addCnt;
			}
			int rem = courseCount%5;
			int labelCount = courseCount/5;
			if(rem > 0)
				labelCount++;
			
			for(int i= 0;i<labelCount;i++){
				address.add(p);
			}
		}
		List<SupplyConfig> configList = configRepo.findByBatchId(batchId);
		if(configList.size()>0){
			view.addObject("config",configList.get(0));
		}
		view.addObject("labels",address);
		return view;
	}
	
	@RequestMapping(value="supply/course/batch/{batchId}",method=RequestMethod.GET)
	public ModelAndView printSupplyCourse(@PathVariable Integer batchId){
		ModelAndView view = new ModelAndView("print/supplyCourse");
		view.addObject("supplyCourses", scRepo.findByBatchId(batchId,new Sort("courseCode")));
		
		//返回参数设置信息
		List<SupplyConfig> configList = configRepo.findByBatchId(batchId);
		if(configList.size()>0){
			view.addObject("config",configList.get(0));
		}
				
		return view;
	}
	
	@RequestMapping(value="supply/courses/{batchId}",method=RequestMethod.GET)
	@ResponseBody
	public List<SupplyCourse> printCourses(@PathVariable int batchId){
		List<SupplyCourse> courses = scRepo.findByBatchId(batchId, new Sort(new Order(Direction.ASC, "courseCode")));
		return courses;
	}
	
	@RequestMapping(value="supply/paperCover/{batchId}", method=RequestMethod.GET)
	public ModelAndView printSupplyPaperCover(@PathVariable Integer batchId
			,@RequestParam int printType
			,@RequestParam(required=false) Integer provCode
			,@RequestParam(required=false) String courseCode){
		ModelAndView view = new ModelAndView("print/supplyPaperCover");
		
		List<SupplyProvInfo> supplyProvInfos = new ArrayList<SupplyProvInfo>();
		Order provOrder = new Order(Direction.ASC, "provCode");
		Order courseOrder = new Order(Direction.ASC, "courseCode");
		
		if(provCode == null){
			if("".equals(courseCode) || "all".equalsIgnoreCase(courseCode) || null == courseCode){
				supplyProvInfos = supplyProvInfoRepo.findByBatchId(batchId, new Sort(provOrder, courseOrder));
			}else{
				supplyProvInfos = supplyProvInfoRepo.findByBatchIdAndCourseCode(batchId, courseCode, new Sort(provOrder));
			}
		}else{
			if("".equals(courseCode) || "all".equalsIgnoreCase(courseCode) || null == courseCode){
				supplyProvInfos = supplyProvInfoRepo.findByBatchIdAndProvCode(batchId, provCode, new Sort(courseOrder));
			}else{
				supplyProvInfos = supplyProvInfoRepo.findByBatchIdAndCourseCodeAndProvCode(batchId, courseCode, provCode);
				
			}
		}
		
		//因为西藏的试卷寄往四川，所以不需要打印西藏的试卷贴纸。在打印四川的试卷贴纸时，将西藏有而四川没有试卷加入到四川的试卷列表中一起打印，省份标记为四川。
		if(printType == 1){
			if(null == provCode){
				//打印所有省份的试卷贴纸时，先将列表中西藏的全部清除
				List<SupplyProvInfo> supplyProvInfosSC = new ArrayList<SupplyProvInfo>();
				List<SupplyProvInfo> supplyProvInfosXZ = new ArrayList<SupplyProvInfo>();

				for(int i = 0; i < supplyProvInfos.size(); ){
					SupplyProvInfo supplyProvInfo = supplyProvInfos.get(i);
					if(supplyProvInfo.getProvCode() == Province.SICHUAN_CODE){
						supplyProvInfosSC.add(supplyProvInfo);
						supplyProvInfos.remove(i);
					}else if(supplyProvInfo.getProvCode() == Province.XIZANG_CODE){
						supplyProvInfosXZ.add(supplyProvInfo);
						supplyProvInfos.remove(i);
					}else{
						i++;
					}
				}
				
				for(SupplyProvInfo supplyProvInfoXZ : supplyProvInfosXZ){
					boolean exists = false;
					int i = 0;
					for(; i < supplyProvInfosSC.size(); i++){
						SupplyProvInfo supplyProvInfo = supplyProvInfosSC.get(i);
						if(supplyProvInfo.getCourseCode().equals(supplyProvInfoXZ.getCourseCode())){
							exists = true;
							break;
						}
						
						if(supplyProvInfo.getCourseCode().compareTo(supplyProvInfoXZ.getCourseCode()) > 0){
							break;
						}
					}
					
					if(!exists){
						supplyProvInfoXZ.setProvCode(Province.SICHUAN_CODE);
						supplyProvInfoXZ.setProvName("四川");
						supplyProvInfosSC.add(i, supplyProvInfoXZ);
					}
				}
				
				for(int i = 0; i < supplyProvInfos.size(); i++){
					SupplyProvInfo supplyProvInfo = supplyProvInfos.get(i);
					if(supplyProvInfo.getProvCode() > Province.SICHUAN_CODE){
						supplyProvInfos.addAll(i, supplyProvInfosSC);
						break;
					}
				}
			} else if(provCode == Province.XIZANG_CODE){
				supplyProvInfos.clear();
			} else if(provCode == Province.SICHUAN_CODE){
				List<SupplyProvInfo> supplyProvInfosXZ = supplyProvInfoRepo.findByBatchIdAndProvCode(batchId, Province.XIZANG_CODE, new Sort(courseOrder));
				for(SupplyProvInfo supplyProvInfoXZ : supplyProvInfosXZ){
					boolean exists = false;
					int i = 0;
					for(; i < supplyProvInfos.size(); i++){
						SupplyProvInfo supplyProvInfo = supplyProvInfos.get(i);
						if(supplyProvInfo.getCourseCode().equals(supplyProvInfoXZ.getCourseCode())){
							exists = true;
							break;
						}
						
						if(supplyProvInfo.getCourseCode().compareTo(supplyProvInfoXZ.getCourseCode()) > 0){
							break;
						}
					}
					
					if(!exists){
						supplyProvInfoXZ.setProvCode(Province.SICHUAN_CODE);
						supplyProvInfoXZ.setProvName("四川");
						supplyProvInfos.add(i, supplyProvInfoXZ);
					}
				}
			}
		}
		
		view.addObject("printType", printType);		
		view.addObject("supplyProvCourses", supplyProvInfos);
		//返回参数设置信息
		List<SupplyConfig> configList = configRepo.findByBatchId(batchId);
		if(configList.size()>0){
			view.addObject("config",configList.get(0));
		}
		return view;
	}
}
