package cn.com.qmth.examcloud.core.questions.api.controller;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
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.RestController;

import com.google.gson.Gson;

import cn.com.qmth.examcloud.api.commons.enums.DataRuleType;
import cn.com.qmth.examcloud.api.commons.security.bean.User;
import cn.com.qmth.examcloud.api.commons.security.bean.UserDataRule;
import cn.com.qmth.examcloud.commons.exception.StatusException;
import cn.com.qmth.examcloud.core.questions.base.Model;
import cn.com.qmth.examcloud.core.questions.dao.QuesRepo;
import cn.com.qmth.examcloud.core.questions.dao.entity.Question;
import cn.com.qmth.examcloud.core.questions.dao.entity.QuestionSearchCondition;
import cn.com.qmth.examcloud.core.questions.service.PaperDetailUnitService;
import cn.com.qmth.examcloud.core.questions.service.QuesService;
import cn.com.qmth.examcloud.core.questions.service.RandomPaperQuestionService;
import cn.com.qmth.examcloud.core.questions.service.util.PaperUtil;
import cn.com.qmth.examcloud.web.security.DataRule;
import cn.com.qmth.examcloud.web.support.ControllerSupport;
import io.swagger.annotations.ApiOperation;

/**
 * Created by songyue on 16/12/28.
 */
@RestController
@RequestMapping("${api_cqb}/")
public class QuesController extends ControllerSupport {

	@Autowired
	QuesService quesService;

	@Autowired
	QuesRepo quesRepo;

	@Autowired
	Gson gson;

	@Autowired
	private PaperDetailUnitService paperDetailUnitService;
	
	@Autowired
	private RandomPaperQuestionService randomPaperQuestionService;
	
	/**
	 * 获取试题
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "获取试题", notes = "获取试题")
	@GetMapping(value = "/question/{id}")
	public ResponseEntity<Object> getQuesById(@PathVariable String id) {
		Question ques = cn.com.qmth.examcloud.core.questions.base.Model.of(quesRepo.findById(id));
		quesService.formatQues(ques);
		return new ResponseEntity<>(ques, HttpStatus.OK);
	}

	/**
	 * 分页查询试题
	 *
	 * @return
	 */
	@DataRule(type = DataRuleType.COURSE)
	@ApiOperation(value = "分页查询试题", notes = "分页查询试题")
	@GetMapping(value = "/question/{curPage}/{pageSize}")
	public ResponseEntity<Object> getAllQuestion(@ModelAttribute QuestionSearchCondition searchCondition,
			@PathVariable int curPage, @PathVariable int pageSize) {
		User user = getAccessUser();
		UserDataRule ud = getUserDataRule(DataRuleType.COURSE);
		searchCondition.setOrgId(user.getRootOrgId().toString());
		return new ResponseEntity<>(quesService.findAll(searchCondition, curPage, pageSize, ud), HttpStatus.OK);
	}

	/**
	 * 更新试题信息
	 *
	 * @param
	 * @return
	 */
	@ApiOperation(value = "更新试题", notes = "更新试题")
	@PutMapping(value = "/question")
	public ResponseEntity<Object> updateQuestion(@RequestBody Question question) {
		Question old = Model.of(quesRepo.findById(question.getId()));
		if(paperDetailUnitService.paperInUse(question.getId())) {
        	PaperUtil.checkUpdate(question, old,"试卷已调用,");
        }
        if(randomPaperQuestionService.existQuestion(question.getId())) {
        	PaperUtil.checkUpdateOption(question, old,"小题已被抽题模板使用,");
        }
		quesService.saveQues(question);

		// 清除缓存
		paperDetailUnitService.clearQuestionCache(question.getId());

		return new ResponseEntity<>(HttpStatus.OK);
	}

	/**
	 * 新增试题
	 *
	 * @param question
	 * @return
	 */
	@ApiOperation(value = "新增试题", notes = "新增试题")
	@PostMapping(value = "/question")
	public ResponseEntity<Object> addQuestion(@RequestBody Question question) {
		ResponseEntity<Object> ret = new ResponseEntity<>(quesService.saveQues(question), HttpStatus.CREATED);
		return ret;
	}

	/**
	 * 删除试题
	 *
	 * @param id
	 * @return
	 */
	/*
	 * @ApiOperation(value = "删除试题", notes = "删除试题")
	 * 
	 * @DeleteMapping(value = "/question/{id}") public ResponseEntity<Object>
	 * removeQuestion(@PathVariable String id) { quesRepo.deleteById(id);
	 * 
	 * // 清除缓存 paperDetailUnitService.clearQuestionCache(id);
	 * 
	 * return new ResponseEntity<>(HttpStatus.OK); }
	 */

	/**
	 * 删除套题子题
	 *
	 * @param id
	 * @return
	 */
	/*
	 * @ApiOperation(value = "删除套题子题", notes = "删除套题子题")
	 * 
	 * @PutMapping(value = "/question/{id}/{number}") public ResponseEntity<Object>
	 * removeQuestion(@PathVariable String id, @PathVariable String number) {
	 * Question question =
	 * cn.com.qmth.examcloud.core.questions.base.Model.of(quesRepo.findById(id));
	 * List<Question> subQuestions = question.getSubQuestions();
	 * subQuestions.remove(Integer.parseInt(number)); quesRepo.save(question);
	 * 
	 * //清除缓存 paperDetailUnitService.clearQuestionCache(id);
	 * 
	 * return new ResponseEntity<>(question, HttpStatus.OK); }
	 */

	@ApiOperation(value = "查询题目数量", notes = "查询题目数量")
	@GetMapping(value = "/question/count")
	public ResponseEntity<Object> getQuesCount(@ModelAttribute QuestionSearchCondition searchCondition) {
		User user = getAccessUser();
		searchCondition.setOrgId(user.getRootOrgId().toString());
		long count = quesService.findQuesCount(searchCondition);
		return new ResponseEntity<>(count, HttpStatus.OK);
	}

	@ApiOperation(value = "根据试卷ids更新试题属性", notes = "根据试卷ids更新试题属性")
	@PutMapping(value = "/question/updatePro/paperIds")
	public void updateProByPapers(@RequestParam String ids, @RequestParam(required = false) Double difficultyDegree,
			@RequestParam(required = false) Boolean publicity) {
		if (difficultyDegree == null && publicity == null) {
			throw new StatusException("10001", "难度和公开度不能都为空");
		}
		User user = getAccessUser();
		List<String> paperList = Stream.of(ids.split(",")).collect(Collectors.toList());
		quesService.updateProByPapers(paperList, difficultyDegree, publicity, user);
	}

	@ApiOperation(value = "根据课程代码更新试题属性", notes = "根据课程代码更新试题属性")
	@PutMapping(value = "/question/updatePro/courseCode/{courseCode}/{difficultyDegree}/{publicity}/{orgId}")
	public ResponseEntity<Object> updateProByCourse(@PathVariable String courseCode,
			@PathVariable Double difficultyDegree, @PathVariable Boolean publicity, @PathVariable String orgId) {
		quesService.updateProByCourse(courseCode, difficultyDegree, publicity, orgId);
		return new ResponseEntity<>(HttpStatus.OK);
	}

}