package com.qmth.qrzk.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

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

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
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.RestController;

import com.qmth.qrzk.dao.repositories.BatchRepo;
import com.qmth.qrzk.dao.repositories.PrintProvTaskRepo;
import com.qmth.qrzk.dao.repositories.SupplyCourseRepo;
import com.qmth.qrzk.dao.repositories.UserRepo;
import com.qmth.qrzk.repository.constants.WebConstants;
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.utils.General;
import com.qmth.qrzk.repository.utils.ServerConfig;
import com.qmth.qrzk.supplypaper.model.PrintProvTask;
import com.qmth.qrzk.supplypaper.service.PrintTaskService;

/**
 * 供卷扫描任务
 * @author wubaizhi
 *
 */
@RestController
@RequestMapping("scantasks")
public class SupplyScanTaskController {

	@Autowired private PrintProvTaskRepo provTaskRepo;
	@Autowired private SupplyCourseRepo supplyCourseRepo;
	@Autowired private UserRepo userRepo;
	@Autowired private PrintTaskService printTaskSrv;
	@Autowired private BatchRepo batchRepo;
	
	/**
	 * 根据id查找
	 * @param id
	 * @return
	 */
	@RequestMapping(value="{id}",method=RequestMethod.GET)
	public PrintProvTask get(@PathVariable long id){
		return provTaskRepo.findOne(id);
	}
	
	/**
	 * 根据批次和用户查找
	 * @param batchId 批次id
	 * @param userId 用户id
	 * @return
	 */
	@RequestMapping(method=RequestMethod.GET)
	public List<PrintProvTask> queryByBatchAndUser(@RequestParam int batchId, HttpSession session){
		User user = (User) session.getAttribute(WebConstants.WEB_SESSION_USER);
		if(user != null){
			List<PrintProvTask> result = provTaskRepo.findByBatchIdAndScanUserId(batchId, user.getId(), new Sort("provCode"));
			return result;
		}
		return null;
	}
	
	@RequestMapping(value="queryAvailProvs/{batchId}", method=RequestMethod.GET)
	public List<PrintProvTask> queryAvailProvs(@PathVariable int batchId){
		 List<PrintProvTask> result = provTaskRepo.findByBatchIdAndScanUserId(batchId, null, new Sort("provCode"));
		return result;
	}
	
	/**
	 * 导出封装任务数据
	 * @param response
	 * @param batchId
	 * @throws IOException 
	 */
	@RequestMapping(value="exportData/{batchId}", method=RequestMethod.GET)
	public void exportData(HttpServletResponse response,  @PathVariable int batchId) throws IOException{
		String tmpDirPath = ServerConfig.getInstance().getWorkInfo().getProperty("TemporaryDirPath");
		File tmpDir = new File(tmpDirPath);
		File tmpFile = new File(tmpDir,UUID.randomUUID().toString());
		try{
			tmpFile.createNewFile();
		}catch(Exception e){
			e.printStackTrace();
			response.getWriter().println("无法在服务器上的临时目录[" + tmpDirPath + "]里面创建文件，原因：" + e.getMessage());
			return;
		}
		PaperBatch batch = batchRepo.findOne(batchId);
		List<PrintProvTask> tasks = null;
		List<User> scanners = userRepo.findByRole(Role.SCAN_ROLE_CODE);
		for(User user : scanners){
			tasks = provTaskRepo.findByBatchIdAndScanUserId(batchId, user.getId(), new Sort("provCode"));
			user.setTasks(tasks);
		}
		printTaskSrv.writeScanTasksIntoFile(tmpFile, scanners);
		InputStream is = null;
		OutputStream os = null;
		try {
			response.setContentType("application/x-download");// 设置为下载application/x-download
			String filedisplay = batch.getTitle() + "-封装任务_" + General.formatDate(new Date(),"yyyyMMdd") + ".xls";
			String filenamedisplay = URLEncoder.encode(filedisplay, "UTF-8");
			response.addHeader("Content-Disposition", "attachment;filename="+ filenamedisplay);
			is = new FileInputStream(tmpFile);
			os = response.getOutputStream();
			IOUtils.copyLarge(is, os);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			General.close(is);
			General.close(os);
			General.delete(tmpFile);
		}
	}
	
	/**
	 * 根据批次查找相关用户
	 * @param batchId 批次id
	 * @return
	 */
	@RequestMapping(value="users",method=RequestMethod.GET)
	public List<User> queryByBatch(@RequestParam int batchId){
		List<PrintProvTask> tasks = null;
		List<User> scanners = userRepo.findByRole(Role.SCAN_ROLE_CODE);
		for(User user : scanners){
			tasks = provTaskRepo.findByBatchIdAndScanUserId(batchId, user.getId(), new Sort("provCode"));
			user.setTasks(tasks);
		}
		return scanners;
	}
	
	
	/**
	 * 将省份任务关联用户，如果用户id为空则为取消关联
	 * @param userId
	 * @param idArr 任务id数组
	 * @return
	 */
	@RequestMapping(value="users",method=RequestMethod.PUT)
	public AjaxResponse updateByUser(@RequestParam(required=false) Integer userId,@RequestParam long[] idArr){
		printTaskSrv.assignScanTask(userId, idArr);
		return new AjaxResponse(true);
	}
	
	@RequestMapping(value="taskitems/paperScanned/{taskItemId}",method=RequestMethod.POST)
	public AjaxResponse updateTaskItemPaperScanned(@PathVariable long taskItemId){
		AjaxResponse result = new AjaxResponse(true);
		try {
			printTaskSrv.updateTaskItemPaperScanned(taskItemId);
		} catch (Exception e) {
			e.printStackTrace();
			result.setResult(false);
			result.setMsg("扫描试卷更新失败。");
		}
		
		return result;
	}
	
	@RequestMapping(value="taskitems/answerScanned/{taskItemId}",method=RequestMethod.POST)
	public AjaxResponse updateTaskItemAnswerScanned(@PathVariable long taskItemId){
		AjaxResponse result = new AjaxResponse(true);
		try {
			printTaskSrv.updateTaskItemAnswerScanned(taskItemId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setResult(false);
			result.setMsg("扫描答案更新失败。");
		}
		return result;
	}
	
	@RequestMapping(value="/avail",method=RequestMethod.GET)
	public AjaxResponse taskAssignAvailable(@RequestParam int batchId){
		AjaxResponse result = new AjaxResponse(true);
		List<PrintProvTask> printTasks = provTaskRepo.findByBatchId(batchId, null);
		
		if(printTasks.size() == 0){
			result.setResult(false);
			result.setMsg("请先分配打印任务。");
		}
		
		return result;
	}
}
