package com.qmth.qrzk.web.controller;

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

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

import org.apache.commons.lang.StringUtils;
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.servlet.ModelAndView;

import com.qmth.qrzk.repository.constants.WebConstants;
import com.qmth.qrzk.repository.learnCenter.model.LearnCenter;
import com.qmth.qrzk.repository.learnCenter.service.LearnCenterService;
import com.qmth.qrzk.repository.service.query.LearnCenterQueryParams;
import com.qmth.qrzk.repository.user.model.Attachment;
import com.qmth.qrzk.repository.user.model.Course;
import com.qmth.qrzk.repository.user.model.Role;
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.utils.Consts;

@Controller
@RequestMapping("/learnCenter")
public class LearnCenterController extends BaseAjaxController {
	private static final String BASE_JSP_PATH = "learnCenter/";
	
	private static final Logger log = Logger.getLogger(LearnCenterController.class);
	
	@Autowired
	private LearnCenterService learnCenterService;
	
	@Autowired
	private AttachmentService attachmentService;
	
	@Autowired
	private CourseServiceImpl courseService;
	
	@RequestMapping(value = "/list/{categoryCode}")
    public ModelAndView list(HttpServletRequest request, @PathVariable String categoryCode) {
		ModelAndView mov = new ModelAndView(BASE_JSP_PATH + "list");
		mov.addObject(categoryCode);
		return mov;
    }
	
	@RequestMapping(value = "/view/{categoryCode}")
    public ModelAndView view(HttpServletRequest request, @PathVariable String categoryCode) {
		ModelAndView mov = new ModelAndView(BASE_JSP_PATH + "view");
		if(null == categoryCode || "".equals(categoryCode)){
			mov.addObject("errorMsg", "查看的内容不存在，请联系管理员！");
		}else{
			LearnCenter lc = learnCenterService.getLearnCenterByCategoryCode(categoryCode);
			if(null == lc){
				mov.addObject("errorMsg", "查看的内容不存在，请联系管理员！");
			}else{
				String attachmentId = lc.getAttachmentId();
				if(attachmentId != null && attachmentId.length() > 0){
					List<Attachment> attachments = attachmentService.getAttachmentByIds(attachmentId.split(","));
					mov.addObject("attachments", attachments);
				}
				mov.addObject("learnCenter", lc);
			}
		}
        return mov;
    }
	
	@RequestMapping(value = "/updateHtmlContent")
	@ResponseBody
	public Map<String,Object> updateHtmlContent(@RequestBody LearnCenter learnCenter){
		try{
			learnCenterService.updateHtmlContent(learnCenter);
			Map<String,Object> result = this.successResult("学习中心文档保存成功");
			return result;
		}catch(Exception exp){
			log.error("学习中心文档保存失败:" + learnCenter.getId() + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value="/updateAttachment")
	@ResponseBody
	public Map<String,Object> updateAttachment(@RequestBody LearnCenter learnCenter){
		try{
			attachmentService.changeAttStatus(Integer.parseInt(learnCenter.getAttachmentId()), Consts.AttachmentStatus.USING);
			
			learnCenterService.updateAttachment(learnCenter);
			Map<String,Object> result = this.successResult("学习中心文档保存成功");
			return result;
		}catch(Exception exp){
			log.error("学习中心文档保存失败:" + learnCenter.getId() + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value="/queryLearnCenters")
	@ResponseBody
	public Map<String, Object> queryLearnCenters(HttpSession session, LearnCenterQueryParams params){
		Map<String,Object> result = new HashMap<String, Object>();
		params.setCurUserId(this.getCurUser(session).getId());
		
		List<LearnCenter> rows = learnCenterService.queryLearnCenters(params);
		result.put("rows", rows);
		result.put("total", params.getTotalNum());
		return result;
	}
	
	
	@RequestMapping(value="/queryByCode/{categoryCode}")
	@ResponseBody
	public Map<String, Object> queryByCode(HttpSession session, @PathVariable String categoryCode){
		LearnCenterQueryParams params = new LearnCenterQueryParams();
		params.setRows(9999);
		
		Map<String, Object> result = new HashMap<String, Object>();
		params.setCurUserId(this.getCurUser(session).getId());
		params.setCategoryCode(categoryCode);
		
		Role role = (Role)session.getAttribute(WebConstants.WEB_SESSION_ROLE);
		//当用户为学科秘书与命题教师时，只能查看部分课程的素材。
		if(role.getCode().equalsIgnoreCase(Consts.UserRoleCodes.NORMAL_USER)){
			User user = (User)session.getAttribute(WebConstants.WEB_SESSION_USER);
			//List<Course> userCourses = courseService.findCoursesByUserId(user.getId());
			//params.setCourses(userCourses);
			params.setUserId(user.getId());
			params.setIsDomesticConsumer(true);
		}
		
		List<LearnCenter> rows = learnCenterService.queryLearnCenters(params);
		result.put("rows", rows);
		result.put("total", params.getTotalNum());
		return result;
	}
	
	@RequestMapping(value="/uploadLearnCenter")
	@ResponseBody
	public Map<String,Object> uploadLearnCenter(@RequestBody LearnCenter learnCenter){
		try{
			attachmentService.changeAttStatus(Integer.parseInt(learnCenter.getAttachmentId()), Consts.AttachmentStatus.USING);
			
			learnCenterService.addLearnCenter(learnCenter);
			Map<String,Object> result = this.successResult("学习中心文档保存成功");
			return result;
		}catch(Exception exp){
			log.error("学习中心文档保存失败:" + learnCenter.getId() + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public Map<String,Object> delete(String ids, String attIds){
		try{
			if(StringUtils.isNotBlank(attIds) && !"null".equals(attIds)){
				String[] attIdArr = attIds.split(",");
				for(String attId : attIdArr){
					if(!"".equals(attId))
						attachmentService.changeAttStatus(Integer.parseInt(attId), Consts.AttachmentStatus.DELETEED);
				}
			}
			learnCenterService.delete(ids);
			Map<String,Object> result = this.successResult("学习中心文档删除成功");
			return result;
		}catch(Exception exp){
			return this.failedResult(exp);
		}
	}
}
