package com.qxgmat.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.nuliji.tools.Response;
import com.nuliji.tools.ResponseHelp;
import com.nuliji.tools.Transform;
import com.nuliji.tools.exception.AuthException;
import com.qxgmat.data.constants.enums.SettingKey;
import com.qxgmat.data.constants.enums.logic.SentenceLogic;
import com.qxgmat.data.constants.enums.module.PaperModule;
import com.qxgmat.data.dao.entity.*;
import com.qxgmat.data.relation.entity.UserReportRelation;
import com.qxgmat.dto.extend.QuestionExtendDto;
import com.qxgmat.dto.extend.SentenceQuestionBaseExtendDto;
import com.qxgmat.dto.extend.SentenceQuestionDetailExtendDto;
import com.qxgmat.dto.request.*;
import com.qxgmat.dto.response.*;
import com.qxgmat.help.ShiroHelp;
import com.qxgmat.service.SentencePaperService;
import com.qxgmat.service.UserCollectQuestionService;
import com.qxgmat.service.UsersService;
import com.qxgmat.service.extend.QuestionFlowService;
import com.qxgmat.service.inline.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/sentence")
@Api(tags = "长难句", description = "长难句接口")
public class SentenceController
{
    @Autowired
    private ShiroHelp shiroHelp;

    @Autowired
    private SentenceArticleService sentenceArticleService;

    @Autowired
    private SentenceQuestionService sentenceQuestionService;

    @Autowired
    private SentencePaperService sentencePaperService;

    @Autowired
    private SentenceCodeService sentenceCodeService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private SettingService settingService;

    @Autowired
    private UsersService usersService;

    @Autowired
    private UserSentenceProcessService userSentenceProcessService;

    @Autowired
    private UserCollectQuestionService userCollectQuestionService;

    @Autowired
    private QuestionFlowService questionFlowService;

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ApiOperation(value = "所有长难句信息", httpMethod = "GET")
    public Response<JSONObject> sentenceInfo(HttpSession session) {
        Setting entity = settingService.getByKey(SettingKey.SENTENCE);
        JSONObject value = entity.getValue();

        // 用户code状态
        User user = (User) shiroHelp.getLoginUser();
        SentenceCode code = sentenceCodeService.isActive(user.getId());
        if (code != null){
            value.put("code", code.getCode());
        }
        // 查询用户进度
        List<UserSentenceProcess> processList = userSentenceProcessService.listTotal(user.getId());
        Map process = Transform.getMap(processList,UserSentenceProcess.class, "chapter", "process");
        value.put("process", process);

        return ResponseHelp.success(value);
    }

    @RequestMapping(value = "/active", method = RequestMethod.PUT)
    @ApiOperation(value = "激活长难句", httpMethod = "PUT")
    public Response<Boolean> active(@RequestBody @Validated UserSentenceCodeDto dto) {
        UserSentenceProcess entity = Transform.dtoToEntity(dto);
        User user = (User) shiroHelp.getLoginUser();
        if (user == null) throw new AuthException("需要登录");

        if (sentenceCodeService.isActive(user.getId()) == null){
            sentenceCodeService.active(user.getId(), dto.getCode());
        }

        return ResponseHelp.success(true);
    }

    @RequestMapping(value = "/article/list", method = RequestMethod.GET)
    @ApiOperation(value = "长难句文章列表", httpMethod = "GET")
    public Response<List<UserSentenceArticleDto>> listArticle(
            @RequestParam(required = true) Integer chapter,
            HttpSession session) {
        User user = (User) shiroHelp.getLoginUser();

        // 查询用户code
        if (user != null && sentenceCodeService.isActive(user.getId()) != null){
            List<SentenceArticle> p = sentenceArticleService.listByChapter(chapter);
            List<UserSentenceArticleDto> pr = Transform.convert(p, UserSentenceArticleDto.class);

            // 查询文章进度
            List<UserSentenceProcess> processList = userSentenceProcessService.listByChapter(user.getId(), chapter);
            Map process = Transform.getMap(processList,UserSentenceProcess.class, "part", "process");
            Transform.combine(pr, process, UserSentenceArticleDto.class, "part", "process");
            return ResponseHelp.success(pr);
        } else {
            List<SentenceArticle> p = sentenceArticleService.listByTrail();
            List<UserSentenceArticleDto> pr = Transform.convert(p, UserSentenceArticleDto.class);

            if (user != null){
                // 查询文章进度
                List<UserSentenceProcess> processList = userSentenceProcessService.listAllByTrail(user.getId());
                Map process = Transform.getMap(processList,UserSentenceProcess.class, "part", "process");
                Transform.combine(pr, process, UserSentenceArticleDto.class, "part", "process");
            }

            return ResponseHelp.success(pr);
        }
    }

    @RequestMapping(value = "/article/process", method = RequestMethod.PUT)
    @ApiOperation(value = "更新长难句文章进度", httpMethod = "PUT")
    public Response<Boolean> articleProcess(@RequestBody @Validated UserSentenceProcessDto dto) {
        UserSentenceProcess entity = Transform.dtoToEntity(dto);
        User user = (User) shiroHelp.getLoginUser();
        if (user == null) throw new AuthException("需要登录");

        // 获取本章节的最大part数
        Integer max = sentenceArticleService.maxPart(dto.getChapter());

        userSentenceProcessService.updateProcess(user.getId(), dto.getChapter(), dto.getPart(), dto.getProcess(), max);
        return ResponseHelp.success(true);
    }

    @RequestMapping(value = "/paper/list", method = RequestMethod.GET)
    @ApiOperation(value = "长难句组卷列表", httpMethod = "GET")
    public Response<List<UserSentencePaperDto>> listPaper(
            HttpSession session) {
        User user = (User) shiroHelp.getLoginUser();
        // 查询用户code
        if (user != null && sentenceCodeService.isActive(user.getId()) != null){
            List<SentencePaper> p = sentencePaperService.listByLogic(SentenceLogic.NO);
            List<UserSentencePaperDto> pr = Transform.convert(p, UserSentencePaperDto.class);

            return ResponseHelp.success(pr);
        } else {
            List<SentencePaper> p = sentencePaperService.listByLogic(SentenceLogic.TRAIL);
            List<UserSentencePaperDto> pr = Transform.convert(p, UserSentencePaperDto.class);

            return ResponseHelp.success(pr);
        }
    }

    @RequestMapping(value = "/question/detail", method = RequestMethod.GET)
    @ApiOperation(value = "获取题目详情", notes = "获取题目详情", httpMethod = "GET")
    public Response<UserSentenceQuestionDetailDto> detail(
            @RequestParam(required = false) String questionNoId
    )  {
        User user = (User) shiroHelp.getLoginUser();
        return ResponseHelp.success(null);
    }

    @RequestMapping(value = "/paper/start", method = RequestMethod.POST)
    @ApiOperation(value = "开始做题", notes = "提交考试设置", httpMethod = "POST")
    public Response<UserReportDto> start(@RequestBody @Validated SentenceStartDto dto)  {
        User user = (User) shiroHelp.getLoginUser();
        JSONObject setting = new JSONObject();
        UserReportRelation report = questionFlowService.start(user.getId(), PaperModule.SENTENCE, dto.getPaperId(), setting);

        UserReportDto userReportDto = Transform.convert(report, UserReportDto.class);

        return ResponseHelp.success(userReportDto);
    }


    @RequestMapping(value = "/paper/continue", method = RequestMethod.POST)
    @ApiOperation(value = "继续做题", notes = "获取报告信息", httpMethod = "POST")
    public Response<UserReportDto> continueReport(@RequestBody @Validated ReportContinueDto dto)  {
        User user = (User) shiroHelp.getLoginUser();
        UserReportRelation report = questionFlowService.continueReport(user.getId(), dto.getUserReportId());

        UserReportDto userReportDto = Transform.convert(report, UserReportDto.class);

        return ResponseHelp.success(userReportDto);
    }

    @RequestMapping(value = "/paper/next", method = RequestMethod.POST)
    @ApiOperation(value = "获取下一题", notes = "获取下一题", httpMethod = "POST")
    public Response<UserSentenceQuestionBaseDto> next(@RequestBody @Validated ReportNextDto dto)  {
        User user = (User) shiroHelp.getLoginUser();

        UserQuestion userQuestion = questionFlowService.next(user.getId(), dto.getUserReportId());

        UserSentenceQuestionBaseDto baseDto = Transform.convert(userQuestion, UserSentenceQuestionBaseDto.class);

        // 绑定question
        baseDto.setQuestion(Transform.convert(questionService.get(userQuestion.getQuestionId()), QuestionExtendDto.class));

        // 绑定sentenceQuestion
        baseDto.setSentence(Transform.convert(sentenceQuestionService.get(userQuestion.getQuestionNoId()), SentenceQuestionBaseExtendDto.class));

        // 绑定collect
        baseDto.setCollect(userCollectQuestionService.getByUserAndQuestion(user.getId(), userQuestion.getQuestionId()) != null);

        return ResponseHelp.success(null);
    }

    @RequestMapping(value = "/paper/submit", method = RequestMethod.POST)
    @ApiOperation(value = "提交题目答案", notes = "提交题目", httpMethod = "POST")
    public Response<Boolean> submit(@RequestBody @Validated QuestionSubmitDto dto)  {
        User user = (User) shiroHelp.getLoginUser();
        Boolean result = questionFlowService.submit(user.getId(), dto.getUserQuestionId(), dto.getTime(), dto.getAnswer());
        return ResponseHelp.success(result);
    }

    @RequestMapping(value = "/paper/finish", method = RequestMethod.POST)
    @ApiOperation(value = "完成考试", notes = "完成考试", httpMethod = "POST")
    public Response<Boolean> finish(@RequestBody @Validated ReportFinishDto dto)  {
        User user = (User) shiroHelp.getLoginUser();

        Boolean result = questionFlowService.finish(user.getId(), dto.getUserReportId());
        return ResponseHelp.success(result);
    }

    @RequestMapping(value = "/paper/restart", method = RequestMethod.POST)
    @ApiOperation(value = "重置考试", notes = "重置考试", httpMethod = "POST")
    public Response<Boolean> restart(@RequestBody @Validated PaperRestartDto dto)  {
        User user = (User) shiroHelp.getLoginUser();

        questionFlowService.restart(dto.getUserPaperId(), user.getId());

        return ResponseHelp.success(true);
    }
}
