package com.qmth.qrzk.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
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 net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qmth.qrzk.repository.constants.WebConstants;
import com.qmth.qrzk.repository.service.query.QuestionTypeQueryParams;
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.CourseQuestionType;
import com.qmth.qrzk.repository.user.model.ImportBean;
import com.qmth.qrzk.repository.user.model.QuestionType;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.user.service.impl.AttachmentService;
import com.qmth.qrzk.repository.user.service.impl.CourseServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.QuestionTypeServiceImpl;
import com.qmth.qrzk.repository.utils.Consts;
import com.qmth.qrzk.repository.utils.General;
import com.qmth.qrzk.repositry.utils.excel.ExcelOperate;

@Controller
@RequestMapping("/questionType")
public class QuestionTypeController extends BaseAjaxController{
	private static final Logger log = Logger.getLogger(QuestionTypeController.class);
	
	
	@Autowired
	private QuestionTypeServiceImpl questionTypeService;
	
	@Autowired
	private CourseServiceImpl courseService;
	
	
	@Autowired
	private AttachmentService attachmentService;
	
	private static final String BASE_JSP_PATH = "baseData/questionType/";
	
	
    @RequestMapping(value = "/list")
    public ModelAndView list(HttpServletRequest request, HttpSession session) {
        return new ModelAndView(BASE_JSP_PATH + "list");
    }
    
	@RequestMapping(value="/queryQuestionTypes")
	@ResponseBody
	public Map<String, Object> queryQuestionTypes(@RequestBody QuestionTypeQueryParams params){
		Map<String,Object> result = new HashMap<String, Object>();
		List<QuestionType> questionTypes = questionTypeService.queryQuestionTypes(params);
		int total = questionTypeService.queryQuestionTypesCount(params);
		result.put("rows", questionTypes);
		result.put("total", total);
		return result;
	}
	
	@RequestMapping(value ="/queryByCourseId")
	@ResponseBody
	public Map<String,Object> queryByCourseId(HttpServletRequest request, String courseId,Integer chapterSize){
		JSONArray array=new JSONArray();
		Map<String,Object> result = new HashMap<String, Object>();
		if(courseId != null && !"".equals(courseId))
		{
			List<QuestionType> questionTypes = questionTypeService.queryByCourseId(Integer.parseInt(courseId));
			
			for(QuestionType questionType : questionTypes){
				JSONObject object=new JSONObject();
				object.put("id", questionType.getId());
				object.put("code", questionType.getCode());
				object.put("name", questionType.getName());
				array.add(object);
			}
		}
		result.put("rows", array);
		JSONArray footers=new JSONArray();
		JSONObject objOne=new JSONObject();
		objOne.put("name", "题量合计");
		objOne.put("questionTypeTotalCount", "0");
		objOne.put("questionTypeTotalScore", "0");
		footers.add(objOne);
		JSONObject objTwo=new JSONObject();
		objTwo.put("name", "分数合计");
		objTwo.put("questionTypeTotalCount", "0");
		objTwo.put("questionTypeTotalScore", "0");
		footers.add(objTwo);
		result.put("footer", footers);
		return result;
	}
	
	@RequestMapping("/selectQuestionTypesByCourseId/{courseId}")
	@ResponseBody
	public List<QuestionType> selectQuestionTypesByCourseId(@PathVariable int courseId){
		List<QuestionType> list=questionTypeService.queryByCourseId(courseId);
		return list;
	}
	
	@RequestMapping("/saveLinkQuestionType/{courseId}")
	@ResponseBody
	public Map<String,Object> saveLinkQuestionType(HttpServletRequest request,@PathVariable int courseId, @RequestBody String[] links){
		try{
			List<CourseQuestionType> ls=new ArrayList<CourseQuestionType>();
			if(links!=null){
				for(int i=0; i < links.length; i++){
					CourseQuestionType c=new CourseQuestionType();
					c.setCourseId(courseId);
					c.setQuestionTypeId(Integer.parseInt(links[i]));
					c.setSortNo(i);
					ls.add(c);
				}
			}
			questionTypeService.updateCourseQuestionTypes(courseId,ls);
			return this.successResult(null);
		}catch(Exception exp){
			log.error("更新课程(id=" + courseId + ")关联的教材信息失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping("/addQuestionType")
	@ResponseBody
	public Map<String,Object> addQuestionType(HttpServletRequest request,HttpSession session,QuestionType questionType){
		User user=(User) session.getAttribute(WebConstants.WEB_SESSION_USER);
		try{
			questionType.setCreateTime(new Date());
			questionType.setUpdatedTime(new Date());
			questionType.setCreateBy(user.getId());
			questionTypeService.addQuestionType(questionType);
		}catch(Exception exp){
			log.error("新增题型失败原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
		return this.successResult(null);
	}
	
	@RequestMapping("/editQuestionType")
	@ResponseBody
	public Map<String,Object> editQuestionType(HttpServletRequest request,HttpSession session,QuestionType questionType){
		User user=(User) session.getAttribute(WebConstants.WEB_SESSION_USER);
		try{
			questionType.setUpdatedTime(new Date());
			questionType.setUpdatedBy(user.getId());
			questionTypeService.updateQuestionType(questionType);
			
		}catch(Exception exp){
			log.error("新增题型失败原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
		return this.successResult(null);
	}
	
	/**
	 * 导入题型信息,前面因为已经将文件导入保存到磁盘,并且在数据库中有存储,现在只需要把数据库物理路径获取到,然后读取解析 再存储
	 * @param request
	 * @param response
	 * @param attId		附件表的id
	 */
	@RequestMapping(value="/importQuestionType")
	@ResponseBody
	public void importQuestionType(HttpServletRequest request,HttpServletResponse response){
		JSONObject object = new JSONObject();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
		InputStream stream = null;
		try{
			stream = file.getInputStream();
			String fileName = file.getOriginalFilename();
			fileName = new String(fileName.getBytes(), "utf-8");
			List<ImportBean> list=new ExcelOperate().readQuestionTypeExcel(stream, fileName);
			if(list!=null&&list.size()!=0){
				int j = 1;
				for(ImportBean bean:list){
					//课程代码为5位字符串
					if(bean.getCourseCode().length()!=5){
						object.put("result", "fail");
						object.put("lineNum", j);
						object.put("msg", "课程代码位数必须是5位!");
						break;
					}
					if(bean.getQuestionCode() != null){
						if(bean.getQuestionCode().length() > 6 || bean.getQuestionCode().length() < 6){
						object.put("result", "fail");
						object.put("lineNum", j);
						object.put("msg", "题型代码位数必须是6位!");
						break;
						}
					}
					Course course=courseService.findByCode(bean.getCourseCode());
					if(course==null){
						object.put("result", "fail");
						object.put("lineNum", j);
						object.put("msg", "导入的文件第"+j+"行的课程代码不存在!");
						break;
					}
					j++;
				}
				if (!(object.containsKey("result") && object.get("result").equals("fail"))) {
					questionTypeService.saveImportData(list);
					
					object.put("result", "success");
					object.put("successNum", list.size());
					object.put("msg", "导入成功!");
				}
			}else{
				object.put("result", "error");
				object.put("msg", "导入失败!请检查导入题型的excel的正确性 或者是否导入了空excel!");
			}
		}catch(Exception e){
			log.error("导入课程失败，原因：" + e.getMessage(),e);
		}finally{
			General.close(stream);
			this.outJsonString(response, object.toString());
		}
	}
	
	@RequestMapping(value ="/save")
	@ResponseBody
	public Map<String,Object> save(HttpServletRequest request,  @RequestBody QuestionType questionType){
		try{
			if(questionType.getId() != null){
				questionTypeService.updateQuestionType(questionType);
			}else{
				questionTypeService.addQuestionType(questionType);
			}
			return this.successResult(null);
		}catch(Exception exp){
			log.error("更新问题信息失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	@RequestMapping(value = "/delete/{id}")
	@ResponseBody
	public Map<String, Object> delete(@PathVariable int id){
		try{
			questionTypeService.delQuestionType(id);
			return this.successResult("操作成功");
		}catch(Exception e){
			return this.failedResult("删除失败！");
		}
	}
	
	@RequestMapping(value = "/queryById/{id}")
	@ResponseBody
	public QuestionType queryById(@PathVariable Integer id){
		return questionTypeService.queryById(id);
	}
}
