package com.qmth.qrzk.web.controller;


import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qmth.qrzk.repository.pager.model.PaperSkeleton;
import com.qmth.qrzk.repository.pager.model.PaperSkeletonDetail;
import com.qmth.qrzk.repository.pager.model.SkelCfg;
import com.qmth.qrzk.repository.pager.service.PagerConstructService;
import com.qmth.qrzk.repository.service.query.PaperSkeletonQueryParams;
import com.qmth.qrzk.repository.task.PaperTask;
import com.qmth.qrzk.repository.user.model.Attachment;
import com.qmth.qrzk.repository.user.model.Book;
import com.qmth.qrzk.repository.user.model.Course;
import com.qmth.qrzk.repository.user.model.QuestionType;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.user.service.IQuestionTypeService;
import com.qmth.qrzk.repository.user.service.impl.BookServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.CourseServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.PaperSkeletonService;
import com.qmth.qrzk.repository.user.service.impl.PaperTaskServiceImpl;
import com.qmth.qrzk.repository.utils.Consts;


@Controller
@RequestMapping("/paperSkeleton")
public class PaperSkeletonController extends BaseAjaxController{
	
	private static final Logger log = Logger.getLogger(PaperSkeleton.class);
	
	private static final String BASE_JSP_PATH = "paperSkeleton/";
	

	@Autowired 
	private PaperSkeletonService paperSkeletonSrv;
	
	@Autowired
	@Qualifier("questionTypeServiceImpl")
	private IQuestionTypeService questionTypeService;

	@Autowired
    private PagerConstructService pagerConstructSerivce;
	
	@Autowired
	private BookServiceImpl bookService;
	
	@Autowired
	private CourseServiceImpl courseService;
	
	@Autowired
	private PaperTaskServiceImpl paperTaskService;
	
	@RequestMapping(value = "/add")
    public ModelAndView add(HttpServletRequest request, HttpSession session) {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH + "add");
        return modelAndView;
    }
	
	@RequestMapping(value = "/redirect/paperSkeleton")
    public ModelAndView redirectPaperSkeleton(int taskId,int courseId,int bookId,String name,String courseCode, HttpSession session) throws UnsupportedEncodingException {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH + "skel");
		
		Course course = courseService.findById(courseId);
		Book book = bookService.queryById(bookId);
	    List<QuestionType> questionTypes = questionTypeService.queryByCourseId(courseId);
		
	    modelAndView.addObject("course", course);
	    modelAndView.addObject("book", book);
	    modelAndView.addObject("name", name);
	    modelAndView.addObject("bookId", bookId);
	    modelAndView.addObject("courseId", courseId);
	    modelAndView.addObject("courseCode", courseCode);
	    modelAndView.addObject("questionTypes", questionTypes);
	    modelAndView.addObject("canSkelEdit", course.getSkelCfg() != null);
	    modelAndView.addObject("hasPaper", false);
	    modelAndView.addObject("taskId", taskId);
	    modelAndView.addObject("task", paperTaskService.getPaperTaskById(taskId));
        return modelAndView;
    }
	
	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request, HttpSession session) {
		return new ModelAndView(BASE_JSP_PATH + "list");
	}
	
	@RequestMapping(value="/queryPaperSkeletons")
	@ResponseBody
	public Map<String, Object> queryPaperSkeletons(PaperSkeletonQueryParams params){
		Map<String,Object> result = new HashMap<String, Object>();
		List<PaperSkeleton> rows = paperSkeletonSrv.queryPaperSkeletons(params);
		result.put("rows", rows);
		result.put("total", params.getTotalNum());
		return result;
	}
	
	@RequestMapping(value = "/audit")
	public ModelAndView audit(HttpServletRequest request, HttpSession session) {
		return new ModelAndView(BASE_JSP_PATH + "list");
	}	
	//sunrao
	@RequestMapping(value ="/queryByBookId")
    @ResponseBody
    public String queryByBookId(HttpServletRequest request, String courseId,String bookId){
        JSONArray array=new JSONArray();
        
        if(courseId != null && !"".equals(courseId))
        {
            List<PaperSkeleton> listSketion =pagerConstructSerivce.findSkectionsByCourse(Integer.parseInt(courseId),Integer.parseInt(bookId));
            
            for(PaperSkeleton skeletion : listSketion){
                JSONObject object=new JSONObject();
                object.put("id", skeletion.getId());
                object.put("name", skeletion.getName());
                array.add(object);
            }
        }
        
        return array.toString();
    }
	
	@RequestMapping(value="/submitAudit")
	@ResponseBody
	public Map<String,Object> submitAudit(int skeletonId, HttpSession session){
		try{
			User user = getCurUser(session);
			paperSkeletonSrv.submitAudit(skeletonId, user.getId());
			Map<String,Object> resultMap = successResult("细目表提交审核成功");
			return resultMap;
		}catch(Exception e){
			log.error("提交审核细目表[id=" + skeletonId + "]失败，原因：" + e.getMessage(), e);
			return failedResult("提交审核细目表失败");
		}
	}
	
	@RequestMapping(value="/saveAudit")
	@ResponseBody
	public Map<String,Object> saveAudit(int skeletonId,int auditResult,String remark, HttpSession session){
		try{
			User user = getCurUser(session);
			paperSkeletonSrv.saveAudit(skeletonId, user.getId(), auditResult, remark);
			Map<String,Object> resultMap = successResult("保存细目表的审核结果成功");
			return resultMap;
		}catch(Exception e){
			log.error("保存细目表[id=" + skeletonId + "]的审核结果失败，原因：" + e.getMessage(), e);
			return failedResult("提交细目表审核结果失败");
		}
	}
	
	@RequestMapping(value="/getAuditLogs")
	@ResponseBody
	public Map<String,Object> getAuditLogs(int skeletonId){
		try{
			Map<String,Object> resultMap = successResult("查询审核日志成功");
			resultMap.put("auditLogs",paperSkeletonSrv.getAuditLogs(skeletonId));
			return resultMap;
		}catch(Exception e){
			log.error("查询细目表[id=" + skeletonId + "]的审核日志失败，原因：" + e.getMessage(), e);
			return failedResult("查询审核日志失败");
		}
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public Map<String,Object> delete(int skeletonId){
		try{
			paperSkeletonSrv.deletePaperSkeletonById(skeletonId);
			return successResult("删除细目表成功");
		}catch(Exception e){
			log.error("删除细目表[id=" + skeletonId + "]失败，原因：" + e.getMessage(), e);
			return failedResult("删除细目表失败");
		}
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public Map<String,Object> savePaperskeleton(@RequestBody PaperSkeleton paperSkeleton,HttpSession session){
		try{
			User user = this.getCurUser(session);
			paperSkeleton.setCreatedBy(user.getId());
			paperSkeleton.setUpdatedBy(user.getId());
			paperSkeletonSrv.save(paperSkeleton,user);
			Map<String,Object> result = this.successResult("保存细目表成功");
			result.put("paperSkeleton", paperSkeleton);
			return result;
		}catch(Exception exp){
			log.error("保存细目表失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	
	@RequestMapping("/viewskeletondetail/{id}")
    public ModelAndView viewDetail(HttpSession session,@PathVariable Integer id) {
		User curUser = this.getCurUser(session);
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH + "skel");
		PaperSkeleton skel = paperSkeletonSrv.queryById(id);
		PaperTask paperTask = paperTaskService.getPaperTaskById(skel.getTaskId());
//		boolean canSkelEdit = curUser.getId().equals(paperTask.getCurDealer()) && (paperTask.getStatus().equals(Consts.PaperTaskStatus.TO_CREATE_SKEL) || paperTask.getStatus().equals(Consts.PaperTaskStatus.TO_AUDIT_SKEL));
		boolean canSkelEdit = curUser.getId().equals(paperTask.getCurDealer()) && (!paperTask.getStatus().equals(Consts.PaperTaskStatus.ARCHIVED));
		List<PaperSkeletonDetail> skeletonDetailArr = skel.getSkeletonDetailArr();
		Map<String,Integer> skeletonDetailMap = new HashMap<String, Integer>();
		for(PaperSkeletonDetail detail:skeletonDetailArr){
			skeletonDetailMap.put(detail.getChapterNo() + "|" + detail.getAbility() + "|" + detail.getQuesTypeNo() + "|" + detail.getEstimateDifficulty(), detail.getQuesNum());
		}
		Course course = skel.getCourse();
		Book book = skel.getBook();
	    List<QuestionType> questionTypes = skel.getQuesTypeArr();
	    canSkelEdit = canSkelEdit && (course.getSkelCfg() != null);
		
	    modelAndView.addObject("course", course);
	    modelAndView.addObject("book", book);
	    modelAndView.addObject("name", skel.getName());
	    modelAndView.addObject("bookId", book.getId());
	    modelAndView.addObject("courseId", course.getId());
	    modelAndView.addObject("courseCode", course.getCode());
	    modelAndView.addObject("questionTypes", questionTypes);
	    modelAndView.addObject("skel", skel);
	    modelAndView.addObject("skeletonDetailMap", skeletonDetailMap);
	    modelAndView.addObject("canSkelEdit", canSkelEdit);
	    modelAndView.addObject("task", paperTask);
	    modelAndView.addObject("hasPaper", (paperTask.getPagerConstruct() != null));
	    modelAndView.addObject("taskId", skel.getTaskId());
        return modelAndView;
    }
	
	@RequestMapping("/printView")
    public ModelAndView printView(HttpSession session,Integer id) {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH + "printView");
		PaperSkeleton skel = paperSkeletonSrv.queryById(id);
		Course course = skel.getCourse();
		Book book = skel.getBook();
	    List<QuestionType> questionTypes = skel.getQuesTypeArr();
		
	    modelAndView.addObject("course", course);
	    modelAndView.addObject("book", book);
	    modelAndView.addObject("name", skel.getName());
	    modelAndView.addObject("bookId", book.getId());
	    modelAndView.addObject("courseId", course.getId());
	    modelAndView.addObject("courseCode", course.getCode());
	    modelAndView.addObject("questionTypes", questionTypes);
	    modelAndView.addObject("skel", skel);
        return modelAndView;
    }
	
	@RequestMapping("/export/{id}")
	@ResponseBody
	public Map<String,Object> export(HttpSession session,@PathVariable Integer id) {
		try{
			Attachment att = paperSkeletonSrv.exportToExcel(id, this.getCurUser(session));
			Map<String,Object> resultMap = successResult("生成细目表Excel文件成功");
			resultMap.put("att", att);
			return resultMap;
		}catch(Exception e){
			log.error("生成细目表[id=" + id + "]Excel文件失败，原因：" + e.getMessage(), e);
			return failedResult("生成细目表Excel文件失败");
		}
    }
	
	@RequestMapping("/getSkelCfgInfo/{courseId}")
	@ResponseBody
	public Map<String,Object> getSkelCfgInfo(@PathVariable int courseId){
		try{
			SkelCfg skelCfg = paperSkeletonSrv.getSkelCfgByCourseId(courseId);
			if(skelCfg == null){
				skelCfg = new SkelCfg();
				skelCfg.setCourseId(courseId);
				skelCfg.setAbilityOffset(3.0);
				skelCfg.setEstimateDifficultyOffset(3.0);
			}
			Map<String,Object> result = this.successResult("获取细目表配置数据成功");
			result.put("skelCfg", skelCfg);
			return result;
		}catch(Exception exp){
			log.error("获取课程[courseId=" + courseId + "]对应的细目表配置数据失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping("/saveSkelCfg")
	@ResponseBody
	public Map<String,Object> saveSkelCfg(@RequestBody SkelCfg skelCfg){
		try{
			skelCfg = paperSkeletonSrv.saveSkelCfg(skelCfg);
			Map<String,Object> result = this.successResult("保存细目表配置数据成功");
			result.put("skelCfg", skelCfg);
			return result;
		}catch(Exception exp){
			log.error("保存细目表配置数据失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
}
