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

import cn.com.qmth.examcloud.api.commons.security.bean.User;
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.QuesService;
import cn.com.qmth.examcloud.web.support.ControllerSupport;
import com.google.gson.Gson;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

import static cn.com.qmth.examcloud.core.questions.service.cache.Constants.CACHE_PREFIX_QUESTION;

/**
 * Created by songyue on 16/12/28.
 */
@RestController
@RequestMapping("${api_cqb}/")
public class QuesController extends ControllerSupport {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    QuesService quesService;

    @Autowired
    QuesRepo quesRepo;

    @Autowired
    Gson gson;

    /**
     * 获取试题
     *
     * @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<Object>(ques, HttpStatus.OK);
    }

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

    /**
     * 更新试题信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "更新试题", notes = "更新试题")
    @PutMapping(value = "/question")
    public ResponseEntity<Object> updateQuestion(@RequestBody Question question) {
        quesService.saveQues(question);

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

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

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

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

        //清除缓存
        this.clearQuestionCache(id);

        return new ResponseEntity<Object>(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));
        return new ResponseEntity<Object>(quesRepo.save(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<Object>(count, HttpStatus.OK);
    }

    @ApiOperation(value = "根据试卷ids更新试题属性", notes = "根据试卷ids更新试题属性")
    @PutMapping(value = "/question/updatePro/paperIds/{ids}/{difficultyDegree}/{publicity}")
    public ResponseEntity<Object> updateProByPapers(@PathVariable String ids,
                                                    @PathVariable Double difficultyDegree,
                                                    @PathVariable Boolean publicity) {
        User user = getAccessUser();
        List<String> paperList = Stream.of(ids.split(",")).collect(Collectors.toList());
        quesService.updateProByPapers(paperList, difficultyDegree, publicity, user);
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    @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<Object>(HttpStatus.OK);
    }

    private void clearQuestionCache(String questionId) {
        //清理与当前试题相关的缓存
        final String patternKey = CACHE_PREFIX_QUESTION + "*" + questionId;
        Set<String> keys = redisTemplate.keys(patternKey);
        if (CollectionUtils.isNotEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }

}