package com.qmth.qrzk.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import com.qmth.qrzk.dao.repositories.PaperRepo;
import com.qmth.qrzk.dao.repositories.SupplyCourseRepo;
import com.qmth.qrzk.paper.model.Paper;
import com.qmth.qrzk.repository.constants.WebConstants;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.supplypaper.model.SupplyCourse;
import com.qmth.qrzk.supplypaper.service.SupplyService;
import com.qmth.qrzk.supplypaper.vo.ProvCourseVO;

/**
 * 供卷课程
 * @author zhengmin
 *
 */
@RestController
@RequestMapping("supply/course")
public class SupplyCourseController {

	@Autowired private SupplyCourseRepo scRepo;
	@Autowired private PaperRepo paperRepo;
	@Autowired private SupplyService supplyService;
	
	/**
	 * 通过批次id查找的供卷课程
	 * @param batchId - 批次id
	 * @return
	 */
	@RequestMapping(value="/batch/{batchId}",method=RequestMethod.GET)
	public Collection<SupplyCourse> findByBactchId(
				@PathVariable Integer batchId){
		return scRepo.findByBatchId(batchId,new Sort("courseCode"));
	}
	
	/**
	 * 通过id查找
	 * @param id
	 * @return
	 */
	@RequestMapping(value="{id}",method=RequestMethod.GET)
	public SupplyCourse findById(
				@PathVariable long id){
		return scRepo.findOne(id);
	}
	
	/**
	 * 保存
	 * @param course
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST)
	public AjaxResponse save(@RequestBody SupplyCourse course,HttpSession session) throws Exception{
		User user = (User) session.getAttribute(WebConstants.WEB_SESSION_USER);
		if(user != null){
			if(course.getId() == null)
			course.setCreatedBy(user.getId());
			supplyService.saveSupplyCourse(course);
		}
		else{
			throw new Exception("会话过期");
		}
		return new AjaxResponse(true);
	}
	
	/**
	 * 删除供卷课程
	 * @param id
	 * @return
	 */
	@RequestMapping(value="{id}",method=RequestMethod.DELETE)
	public AjaxResponse remove(@PathVariable Long id){
		supplyService.removeSupplyCourse(id);
		return new AjaxResponse(true);
	}
	
	/**
	 * 查询状态不为启用，且没有供卷的试卷
	 * @param courseCode
	 * @return
	 */
	@RequestMapping(value="/paper/{batchId}/{courseCode}",method=RequestMethod.GET)
	public List<Paper> findPaper(@PathVariable Integer batchId, @PathVariable String courseCode){
		List<Paper> list = paperRepo.findSupplyCoursePaper(batchId, courseCode);
		return list;
	}
	
	/**
	 * 关联试卷
	 * @param paper
	 * @return
	 */
	@RequestMapping(value="{id}/paper/{paperId}",method=RequestMethod.PUT)
	public AjaxResponse assignPaper(@PathVariable long paperId,
			@PathVariable Long id){
		supplyService.assignPaper(id, paperId);
		return new AjaxResponse(true);
	}
	
	/**
	 * 分配打印任务重，获取省份及课程数量
	 * @param batchId
	 * @return
	 */
	@RequestMapping(value="/print/prov/{batchId}",method=RequestMethod.GET)
	public List<ProvCourseVO> printTaskProvince(@PathVariable Integer batchId){
		return supplyService.buildProvCourse(batchId);
	}
	
	/**
	 * 安排打印任务时，读取所有录入员用户信息
	 */
	@RequestMapping(value="/print/user",method=RequestMethod.GET)
	public List<User> findInputerUsers(){
		return supplyService.findInputerUsers();
	}
	
	/**
	 * 上传供卷课程
	 * @param batchId
	 * @param file
	 * @throws IOException
	 */
	@ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/upload/{batchId}")
    public Map<String, Object> upload(@PathVariable Integer batchId,@RequestParam("file") MultipartFile file){
		System.out.println(String.format(file.getOriginalFilename()));
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
	        if (!file.isEmpty()) {
	             //supplyService.addSupplyCourseFromCourse(file.getInputStream(),batchId);//老模版导入
	             supplyService.addNewSupplyCourseFromCourse(file.getInputStream(),batchId);
	             resultMap.put("flag", "success");
	        }else{
	        	resultMap.put("flag", "failed");
	        	resultMap.put("msg", "上传的是空文件！");
	        }
		}catch(Exception e){
			e.printStackTrace();
			resultMap.put("flag", "failed");
        	resultMap.put("msg", e.getMessage());
		}
		return resultMap;
    }
	
	
	@RequestMapping(value="/print/assign",method=RequestMethod.GET)
	public AjaxResponse assignTask(@RequestParam Integer batchId) throws Exception{
		AjaxResponse res = null;
		try {
			supplyService.assignProvToUser(batchId);
			res = new AjaxResponse(true);
		} catch (Exception e) {
			e.printStackTrace();
			res = new AjaxResponse(false, e.getMessage());
		}
		return res;
	}
	
	@RequestMapping(value="/scan/assign",method=RequestMethod.GET)
	public AjaxResponse assignScanTask(@RequestParam Integer batchId) throws Exception{
		supplyService.assignProvScanTaskToUser(batchId);
		return new AjaxResponse(true);
	}
	
	@RequestMapping("/expStartedPapers/{batchId}")
	public ModelAndView expStartedPapers(HttpServletRequest request,HttpServletResponse response,  @PathVariable int batchId) {
		// 根据批次id查询出该批次所有启用试卷
		List<SupplyCourse> scList = scRepo.findByBatchId(batchId,new Sort("paperCode"));
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("scList", scList);
		return new ModelAndView(new AbstractExcelView() {
			@Override
			protected void buildExcelDocument(Map<String, Object> model,
					HSSFWorkbook workbook, HttpServletRequest request,
					HttpServletResponse response) throws Exception {
				HSSFSheet sheet = workbook.createSheet("启用试卷列表");

				HSSFRow row = sheet.createRow(0);
				HSSFCell cell = row.createCell(0);
				cell.setCellValue("试卷编号");
				
				int i=0;
				@SuppressWarnings("unchecked")
				List<SupplyCourse> scList = (List<SupplyCourse>)model.get("scList");
				for(SupplyCourse sc:scList){
					row=sheet.createRow(i+1);
					cell=row.createCell(0);
					cell.setCellValue(sc.getPaperCode());
					i++;
				}

				sheet.setColumnWidth(0, 15 * 256);
				
			    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
				String filename = sdf.format(new Date()) + "_StartedPapers.xls";// 设置下载时客户端Excel的名称
				response.setContentType("application/vnd.ms-excel");
				response.setHeader("Content-disposition", "attachment;filename="+ filename);
				OutputStream ouputStream = response.getOutputStream();
				workbook.write(ouputStream);
				ouputStream.flush();
				ouputStream.close();
			}
		}, map);   
	}
}
