package com.qmth.qrzk.repository.user.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qmth.qrzk.repository.common.base.BaseDao;
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.UserCourse;
import com.qmth.qrzk.repository.utils.General;

@Service
public class CourseServiceImpl {

	@Autowired
	private BaseDao dao;

	@Autowired
	private BookServiceImpl bookServiceImpl;
	
	public List<Course> queryCourses(CourseQueryParams params) {
		return dao.getPagerList("queryCourses", params);
	}

	public List<Course> queryAllCourses() {
		return dao.getList("queryCourses");
	}

	/**
	 * 判断list集合中的courseCode是否正确，是否在数据库中已存在
	 * 
	 * @param list
	 * @param object
	 * @return
	 */
	public void checkCourseCodes(List<ImportBean> list, JSONObject object) {
		for (int i = 0; i < list.size(); i++) {
			String code = list.get(i).getCourseCode();
			if(code.length() != 5 || !code.matches("\\d+")) {
				object.put("result", "fail");
				object.put("msg", General.null2String(object.get("msg")) + "第" + (i + 2) +"行的课程代码[" + code +"]必须是5位数字!<br/>");
			}else{
				Course course = dao.get("findByCode", code);
				if (course != null) {// 判断是否在数据库中存在 如果不等于空就说明该courseCode 存在数据库中
					object.put("result", "fail");
					object.put("msg", General.null2String(object.get("msg")) + "第" + (i + 2) +"行的课程[" + code + "]在系统中已存在！<br/>");
				}
			}
		}
	}

	public Course findById(int courseId) {
		return dao.getObject("findCourseById", courseId);
	}

	public void insertUserCourse(UserCourse userCourse) {
		dao.insert("insertUserCourse", userCourse);
	}

	public List<Course> findCoursesByUserId(int userId) {
		Map<Integer,Course> courseMap = new HashMap<Integer, Course>();
		List<Course> allCourse = new ArrayList<Course>();
		allCourse.addAll(findToAuditCoursesByUserId(userId));
		allCourse.addAll(findToInputCoursesByUserId(userId));
		allCourse.addAll(findToPaperCoursesByUserId(userId));
		allCourse.addAll(findCourseByUserId(userId));
		for(Course c:allCourse){
			courseMap.put(c.getId(), c);
		}
		return new ArrayList<Course>(courseMap.values());
	}
	
	public List<Course> findToAuditCoursesByUserId(int userId) {
		List<Integer> courseIds = dao.getList("getCurAuditCourseIdsByAuditorId", userId);
		List<Course> cList = new ArrayList<Course>();
		for(Integer courseId:courseIds){
			cList.add(findById(courseId));
		}
		return cList;
	}
	
	public List<Course> findToInputCoursesByUserId(int userId) {
		List<Integer> courseIds = dao.getList("getCurInputCourseIdsByInputerId", userId);
		List<Course> cList = new ArrayList<Course>();
		for(Integer courseId:courseIds){
			cList.add(findById(courseId));
		}
		return cList;
	}
	
	public List<Course> findToPaperCoursesByUserId(int userId) {
		List<Integer> courseIds = dao.getList("getCurPaperCourseIdsByInputerId", userId);
		List<Course> cList = new ArrayList<Course>();
		for(Integer courseId:courseIds){
			cList.add(findById(courseId));
		}
		return cList;
	}

	public void updateCourse(Course course) {
		Course courseTmp = dao.getObject("findByCode", course.getCode());
		if(courseTmp != null && !courseTmp.getId().equals(course.getId())){
			throw new RuntimeException("课程代码[" + course.getCode() + "]已存在");
		}
		dao.update("updateCourse", course);
	}

	public void addCourse(Course course) {
		Course courseTmp = dao.getObject("findByCode", course.getCode());
		if(courseTmp != null){
			throw new RuntimeException("课程代码[" + course.getCode() + "]已存在");
		}
		dao.insert("addCourse", course);
	}

	public void saveLinkBooks(int courseId, List<CourseBook> courseBooks) {
		dao.delete("delCourseBooksByCourseId", courseId);
		if (courseBooks != null && courseBooks.size() > 0) {
			dao.insert("addCourseBooks", courseBooks);
		}
	}
	
	public void addCourseLinkBook(List<CourseBook> courseBooks){
		dao.insert("addCourseBooks", courseBooks);
	}

	public void updateUserCourses(int userId, List<UserCourse> list) {
		dao.delete("delUserCourseByUserId", userId);
		if (list != null && list.size() > 0) {
			dao.insert("addUserCourses", list);
		}
	}
	
	/**
	 * 添加用户与课程关联关系，20151019 wubaizhi
	 * @param userId
	 * @param list
	 */
	public void addUserCourses(int userId, List<UserCourse> list) {
		if (list != null && list.size() > 0) {
			dao.insert("addUserCourses", list);
		}
	}
	/**
	 * 删除用户与课程关联关系 20151019 wubaizhi
	 * @param userCourse
	 */
	public void deleteUserCourses(UserCourse userCourse) {
		dao.insert("delUserCourse", userCourse);
	}
	/**
	 * 通过用户id，从用户与课程关联表中获取所有与之关联的课程
	 * @param userId
	 * @return
	 */
	public List<Course> findCourseByUserId(int userId){
		return dao.getList("findCourseByUserId", userId);
	}

	public void addUserCourses(List<UserCourse> list) {
		dao.insert("addUserCourses", list);
	}

	// public List<CourseBook> findCourseBooksByCourseId(String courseId){
	// return dao.getList("findCourseBooksByCourseId",courseId);
	// }

	public Course findByCode(String code) {
		return dao.getObject("findByCode", code);
	}
	
	public Course findCourseByQuesId(int quesId){
		Course course = dao.getObject("findCourseByQuesId", quesId);
		return course;
	}
	
	public void saveImportData(List<ImportBean> list){
		List<CourseBook> courseBooks=new ArrayList<CourseBook>();
		for (ImportBean courseBean : list) {
			// 新增课程
			Course course = new Course();
			course.setCode(courseBean.getCourseCode());
			course.setName(courseBean.getCourseName());
			course.setType(1);
			course.setStatus(1);
			addCourse(course);
			// 新增教材
			Book book = new Book();
			book.setName(courseBean.getBookName());
			book.setEditor(courseBean.getAuthor());
			book.setPress(courseBean.getPress());
			book.setVersion(courseBean.getEdition());
			bookServiceImpl.addBook(book);
			
			CourseBook cb=new CourseBook();
			cb.setBookId(book.getId());
			cb.setCourseId(course.getId());
			cb.setStatus(1);
			courseBooks.add(cb);
		}
		//新增课程教材关联关系
		addCourseLinkBook(courseBooks);
	}
	
	public void deleteCourse(int courseId){
		dao.delete("delCourseBooksByCourseId", courseId);
		dao.delete("deleteCourseQuestionTypeLink", courseId);
		dao.delete("deleteSkelCfgByCourseId", courseId);
		dao.delete("delCourseById", courseId);
	}
}
