package com.qmth.qrzk.web.controller;

import java.io.InputStream;
import java.util.ArrayList;
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.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.CourseQueryParams;
import com.qmth.qrzk.repository.user.model.Book;
import com.qmth.qrzk.repository.user.model.Course;
import com.qmth.qrzk.repository.user.model.CourseBook;
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.BookServiceImpl;
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("/course")
public class CourseController extends BaseAjaxController {

	private static final Logger log = Logger.getLogger(CourseController.class);

	@Autowired
	private CourseServiceImpl courseService;

	@Autowired
	private BookServiceImpl bookServiceImpl;

	@Autowired
	private QuestionTypeServiceImpl questionTypeServiceImpl;
	
	@Autowired
	private AttachmentService attachmentService;

	private static final String BASE_JSP_PATH = "baseData/course/";

	private static String INCOURSE_STATUS_MAP = null;
	static {
		JSONArray array = new JSONArray();
		for (Map.Entry<Integer, String> entry : Consts.BookInCourseStatus.dicMap
				.entrySet()) {
			JSONObject object = new JSONObject();
			object.put("key", entry.getKey());
			object.put("text", entry.getValue());
			array.add(object);
		}
		INCOURSE_STATUS_MAP = array.toString();
	}

	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request, HttpSession session) {
		request.setAttribute("courseStatusDic", Consts.CourseStatus.dicMap);
		request.setAttribute("courseTypeDic", Consts.CourseType.dicMap);
		request.setAttribute("inCourseStatusMap", INCOURSE_STATUS_MAP);
		return new ModelAndView(BASE_JSP_PATH + "list");
	}

	@RequestMapping(value = "/queryCourses")
	@ResponseBody
	public Map<String, Object> queryCourses(@RequestBody CourseQueryParams params) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<Course> rows = courseService.queryCourses(params);
		result.put("rows", rows);
		result.put("total", params.getTotalNum());
		return result;
	}

	@RequestMapping(value = "/queryByCurrentUser")
	@ResponseBody
	public String queryByUserId(HttpServletRequest request) {

		User user = (User) request.getSession().getAttribute(
				WebConstants.WEB_SESSION_USER);
		List<Course> courses = courseService.findCoursesByUserId(user.getId());

		JSONArray array = new JSONArray();
		for (Course course : courses) {
			JSONObject object = new JSONObject();
			object.put("id", course.getId());
			object.put("code", course.getCode());
			object.put("name", course.getName());
			object.put("showName", course.getShowName());
			array.add(object);
		}
		return array.toString();
	}

	@RequestMapping(value = "/queryAllCourses")
	@ResponseBody
	public List<Course> queryAllCourses() {
		List<Course> courses = courseService.queryAllCourses();
		return courses;
	}

	@RequestMapping(value = "/save")
	@ResponseBody
	public Map<String, Object> save(HttpServletRequest request , @RequestBody Course course) {
		try {
			if (course.getId() != null) {
				courseService.updateCourse(course);
			} else {
				courseService.addCourse(course);
			}
			Map<String, Object> resultMap = this.successResult(null);
			resultMap.put("course", courseService.findById(course.getId()));
			return resultMap;
		} catch (Exception exp) {
			log.error("更新课程信息失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}

	@RequestMapping(value = "/selectedBooks/{courseId}")
	@ResponseBody
	public List<Book> selectedBooks(@PathVariable int courseId) {
		List<Book> courseBooks = bookServiceImpl.findBooksInCourse(courseId);
		return courseBooks;
	}

	@RequestMapping(value = "/saveLinkBooks/{courseId}")
	@ResponseBody
	public Map<String, Object> saveLinkBooks(HttpServletRequest request,
			@PathVariable int courseId,
			@RequestBody String[] links) {
		try {
			List<CourseBook> courseBooks = new ArrayList<CourseBook>();
			if (links != null) {
				for (String link : links) {
					CourseBook cb = new CourseBook();
					cb.setCourseId(courseId);
					cb.setBookId(Integer.parseInt(link.split("@")[0]));
					cb.setStatus(Integer.parseInt(link.split("@")[1]));
					courseBooks.add(cb);
				}
			}
			courseService.saveLinkBooks(courseId, courseBooks);
			return this.successResult(null);
		} catch (Exception exp) {
			log.error(
					"更新课程(id=" + courseId + ")关联的教材信息失败，原因:" + exp.getMessage(),
					exp);
			return this.failedResult(exp);
		}
	}

	@RequestMapping(value = "/getLinkSubject/{userId}")
	@ResponseBody
	public List<Course> getLinkSubject(@PathVariable int userId) {
		List<Course> list = courseService.findCoursesByUserId(userId);
		return list;
	}
	
	@RequestMapping(value = "/selectedQuestionTypes/{courseId}")
	@ResponseBody
	public List<QuestionType> selectedQuestionTypes(@PathVariable int courseId) {
		List<QuestionType> courseQuestionTypes = questionTypeServiceImpl.queryByCourseId(courseId);
		return courseQuestionTypes;
	}
	/**
	 * 导入课程信息,前面因为已经将文件导入保存到磁盘,并且在数据库中有存储,现在只需要把数据库物理路径获取到,然后读取解析 再存储
	 * 
	 * @param request
	 * @param response
	 * @param attId
	 *            附件表的id
	 */
	@RequestMapping(value = "/importCourse")
	@ResponseBody
	public void importCourse(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().readCourseBookExcel(stream,fileName);
			if (list != null && list.size() != 0) {
				// 验证excel所导入的课程是否在数据库中
				courseService.checkCourseCodes(list, object);
				if (!(object.containsKey("result") && object.get("result").equals("fail"))) {
					courseService.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 = "/delete/{id}")
	@ResponseBody
	public Map<String, Object> deleteCourse(@PathVariable int id){
		try{
			courseService.deleteCourse(id);
			return this.successResult("操作成功");
		}catch(Exception e){
			return this.failedResult("删除失败！");
		}
	}
	
	@RequestMapping(value = "/getById/{id}")
	@ResponseBody
	public Course getById(@PathVariable Integer id){
		return courseService.findById(id);
	}
}
