package com.qxgmat.controller.admin;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.nuliji.tools.PageMessage;
import com.nuliji.tools.Response;
import com.nuliji.tools.ResponseHelp;
import com.nuliji.tools.Transform;
import com.nuliji.tools.exception.ParameterException;
import com.qxgmat.data.constants.enums.SettingKey;
import com.qxgmat.data.constants.enums.status.DirectionStatus;
import com.qxgmat.data.dao.entity.*;
import com.qxgmat.dto.admin.extend.ExercisePaperExtendDto;
import com.qxgmat.dto.admin.extend.QuestionExtendDto;
import com.qxgmat.dto.admin.extend.QuestionNoExtendDto;
import com.qxgmat.dto.admin.request.ExerciseStructDto;
import com.qxgmat.dto.admin.response.ExercisePaperListDto;
import com.qxgmat.dto.admin.response.ExerciseQuestionListDto;
import com.qxgmat.service.ExercisePaperService;
import com.qxgmat.service.inline.*;
import com.qxgmat.task.AsyncTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.List;

@RestController("AdminExerciseController")
@RequestMapping("/admin/exercise")
@Api(tags = "练习接口", description = "练习相关", produces = MediaType.APPLICATION_JSON_VALUE)
public class ExerciseController {
    @Autowired
    private ManagerLogService managerLogService;

    @Autowired
    private ExerciseStructService exerciseStructService;

    @Autowired
    private ExercisePaperService exercisePaperService;

    @Autowired
    private ExerciseQuestionService exerciseQuestionService;

    @Autowired
    private QuestionNoService questionNoService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private SettingService settingService;

    @Autowired
    private AsyncTask asyncTask;

    @RequestMapping(value = "/struct/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加练习层级", httpMethod = "POST")
    public Response<ExerciseStruct> add(@RequestBody @Validated ExerciseStructDto dto, HttpServletRequest request) {
        ExerciseStruct entity = Transform.dtoToEntity(dto);
        entity = exerciseStructService.add(entity);
        managerLogService.log(request);
        return ResponseHelp.success(entity);
    }

    @RequestMapping(value = "/struct/edit", method = RequestMethod.PUT)
    @ApiOperation(value = "编辑练习层级", httpMethod = "PUT")
    public Response<Boolean> edit(@RequestBody @Validated ExerciseStructDto dto, HttpServletRequest request) {
        ExerciseStruct entity = Transform.dtoToEntity(dto);
        entity = exerciseStructService.edit(entity);
        managerLogService.log(request);
        return ResponseHelp.success(true);
    }

    @RequestMapping(value = "/struct/delete", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除练习层级", httpMethod = "DELETE")
    public Response<Boolean> delete(@RequestParam int id, HttpServletRequest request) {
        managerLogService.log(request);
        return ResponseHelp.success(exerciseStructService.delete(id));
    }


    @RequestMapping(value = "/struct/all", method = RequestMethod.GET)
    @ApiOperation(value = "所有练习层级", httpMethod = "GET")
    public Response<List<ExerciseStruct>> all(HttpSession session) {
        List<ExerciseStruct> p = exerciseStructService.all();
        return ResponseHelp.success(p);
    }


    @RequestMapping(value = "/paper/list", method = RequestMethod.GET)
    @ApiOperation(value = "练习册列表", httpMethod = "GET")
    public Response<PageMessage<ExercisePaperListDto>> listPaper(
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "100") int size,
            @RequestParam(required = false, defaultValue = "") String keyword,
            HttpSession session) {
        Page<ExercisePaper> p = exercisePaperService.select(page, size, keyword);
        List<ExercisePaperListDto> pr = Transform.convert(p, ExercisePaperListDto.class);

        return ResponseHelp.success(pr, page, size, p.getTotal());
    }

    @RequestMapping(value = "/question/list", method = RequestMethod.GET)
    @ApiOperation(value = "练习册试题列表", httpMethod = "GET")
    public Response<PageMessage<ExerciseQuestionListDto>> listQuestion(
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "100") int size,
            @RequestParam(required = false) String type,
            @RequestParam(required = false, name = "struct_id") Integer structId,
            @RequestParam(required = false, name = "question_no_id") Integer questionNoId,
            @RequestParam(required = false, name="paper_id") Integer paperId,
            @RequestParam(required = false, name="place") String place,
            @RequestParam(required = false, name="difficult") String difficult,
            @RequestParam(required = false, name="start_time") String startTime,
            @RequestParam(required = false, name="end_time") String endTime,
            @RequestParam(required = false, defaultValue = "id") String order,
            @RequestParam(required = false, defaultValue = "desc") String direction,
            HttpSession session) {
        Page<ExercisePaperQuestion> p = exerciseQuestionService.listAdmin(page, size, type, structId, questionNoId, paperId, place, difficult, startTime, endTime, order, DirectionStatus.ValueOf(direction));
        List<ExerciseQuestionListDto> pr = Transform.convert(p, ExerciseQuestionListDto.class);

        // 绑定题目
        Collection questionIds = Transform.getIds(p, ExercisePaperQuestion.class, "questionId");
        List<Question> questionList = questionService.select(questionIds);
        Transform.combine(pr, questionList, ExerciseQuestionListDto.class, "questionId", "question", Question.class, "id", QuestionExtendDto.class);

        // 绑定题目编号
        Collection questionNoIds = Transform.getIds(p, ExercisePaperQuestion.class, "questionNoId");
        List<QuestionNo> questionNoList = questionNoService.select(questionNoIds);
        Transform.combine(pr, questionNoList, ExerciseQuestionListDto.class, "questionNoId", "questionNo", QuestionNo.class, "id", QuestionNoExtendDto.class);

        // 绑定练习册
        Collection paperIds = Transform.getIds(p, ExercisePaperQuestion.class, "paperId");
        List<ExercisePaper> paperList = exercisePaperService.select(paperIds);
        Transform.combine(pr, paperList, ExerciseQuestionListDto.class, "paperId", "paper", ExercisePaper.class, "id", ExercisePaperExtendDto.class);

        return ResponseHelp.success(pr, page, size, p.getTotal());
    }

    @RequestMapping(value = "/paper/auto", method = RequestMethod.POST)
    @ApiOperation(value = "自动组卷", httpMethod = "POST")
    public Response<Boolean> autoPaper(@RequestBody @Validated ExerciseStructDto dto, HttpServletRequest request) {
        // 判断当前组卷状态
        Setting setting = settingService.getByKey(SettingKey.EXERCISE_PAPER_STATUS);
        JSONObject status = setting.getValue();
        if (status.getInteger("process")<100){
            throw new ParameterException("组卷进行中，请稍后再试");
        }
        asyncTask.autoExercisePaper();

        return ResponseHelp.success(true);
    }

    @RequestMapping(value = "/paper/auto", method = RequestMethod.GET)
    @ApiOperation(value = "自动组卷状态", httpMethod = "GET")
    public Response<JSONObject> autoPaperStatus(HttpServletRequest request) {
        // 判断当前组卷状态
        Setting setting = settingService.getByKey(SettingKey.EXERCISE_PAPER_STATUS);
        JSONObject status = setting.getValue();

        return ResponseHelp.success(status);
    }
}
