package com.qmth.qrzk.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

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.RequestHeader;
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.PrintProvTaskRepo;
import com.qmth.qrzk.dao.repositories.SupplyCourseRepo;
import com.qmth.qrzk.dao.repositories.UserRepo;
import com.qmth.qrzk.repository.common.enumeration.PaperStatus;
import com.qmth.qrzk.repository.common.enumeration.PaperType;
import com.qmth.qrzk.repository.user.model.Role;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.utils.Consts;
import com.qmth.qrzk.supplypaper.model.PrintProvTask;
import com.qmth.qrzk.supplypaper.model.PrintProvTaskItem;
import com.qmth.qrzk.supplypaper.service.PrintTaskService;

/**
 * 供暖打印任务
 * @author zhengmin
 *
 */
@RestController
@RequestMapping("printtasks")
public class PrintTaskController {

	@Autowired private PrintProvTaskRepo provTaskRepo;
	@Autowired private SupplyCourseRepo supplyCourseRepo;
	@Autowired private UserRepo userRepo;
	@Autowired private PrintTaskService printTaskSrv;
	
	/**
	 * 根据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,@RequestParam(required=false) Boolean flag,
			@RequestParam(required=false) Integer userId){
		List<PrintProvTask> result = null;
		if(userId == null && flag == null){
			result = provTaskRepo.findByBatchId(batchId, new Sort("provCode"));
		}
		else{
			result = provTaskRepo.findByBatchIdAndUserId(batchId, userId, new Sort("provCode"));
		}
		for(PrintProvTask task : result){
			task.setPrintSortNo(task.getProvCode() + "00000");
			for(PrintProvTaskItem item : task.getTaskItems()){
				item.setPrintSortNo(task.getProvCode() + item.getCourseCode());
			}
		}
		return result;
	}
	
	/**
	 * 根据批次查找
	 * @param batchId 批次id
	 * @return
	 */
	@RequestMapping(value="users",method=RequestMethod.GET)
	public List<User> queryByBatch(@RequestParam int batchId){
		List<PrintProvTask> tasks = null;
		List<User> inputers = userRepo.findByRole(Role.INPUT_ROLE_CODE);
		for(User user : inputers){
			tasks = provTaskRepo.findByBatchIdAndUserId(batchId, user.getId(), new Sort("provCode"));
			user.setTasks(tasks);
		}
		return inputers;
	}
	
	
	/**
	 * 将省份任务关联用户，如果用户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.assignTask(userId, idArr);
		return new AjaxResponse(true);
	}
	
	@RequestMapping(value="taskitems/{taskItemId}",method=RequestMethod.GET)
	public PrintProvTaskItem updateTaskItem(@PathVariable long taskItemId,@RequestParam int printType, 
			@RequestParam int count, @RequestParam(required=false) String remark, @RequestHeader(required=false) Integer userId,
			HttpServletRequest request){
		PaperType type = null;
		switch(printType){
		case 0:
			type = PaperType.BLANK;
			break;
		case 1:
			type = PaperType.ACID;
			break;
		}
		if(userId == null){
			userId = Consts.ClientIpUserMap.get(request.getRemoteAddr());
		}
		if(userId == null){
			System.err.println("客户端：" + request.getRemoteAddr() + " 登录超时，请重新登录后再操作。");
			return null;
		}
		try {
			PrintProvTaskItem item = printTaskSrv.updateTaskStatus(type, taskItemId, count, remark, userId);
			return item;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@RequestMapping(value="/avail",method=RequestMethod.GET)
	public AjaxResponse taskAssignAvailable(@RequestParam int batchId){
		AjaxResponse result = new AjaxResponse(true);
		int noPaperCnt = supplyCourseRepo.countByBatchIdAndPaperId(batchId, null);
		if(noPaperCnt > 0){
			result.setResult(false);
			result.setMsg("还有"+noPaperCnt+"门课程未启用试卷");
		}
		else{
			int draftCnt = supplyCourseRepo.countByBatchIdAndPaperStatus(batchId, PaperStatus.DRAFT.toString());
			if(draftCnt > 0){
				result.setResult(false);
				result.setMsg("启用的试卷中还有"+draftCnt+"份毛坯的");
			}
		}
		return result;
	}
}
