package com.miaxis.pc.controller.question;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miaxis.common.core.controller.BaseController;
import com.miaxis.common.core.domain.Response;
import com.miaxis.common.utils.SecurityUtils;
import com.miaxis.question.domain.QuestionWrong;
import com.miaxis.question.dto.*;
import com.miaxis.question.service.IQuestionWrongService;
import com.miaxis.question.vo.QuestionWrongIdDateVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 【wrong】Controller
 *
 * @author miaxis
 * @date 2021-08-19
 */
@RestController
@RequestMapping("/question/wrong")
@Api(tags={"【PC-错题】"})
public class PcQuestionWrongController extends BaseController {
    @Autowired
    private IQuestionWrongService questionWrongService;


    /**
     * 新增wrong
     */
    @PostMapping
    @ApiOperation("新增wrong")
    public Response<Integer> add(@RequestBody QuestionWrongDTO questionWrongDTO) {
        //查询该用户已收藏的题目列表
        QuestionWrongListDTO dto = new QuestionWrongListDTO();
        dto.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        List<QuestionWrong> list = questionWrongService.selectQuestionWrongList(dto);
        long count = list.stream().filter(o -> questionWrongDTO.getQuestionId().equals(o.getQuestionId()) && questionWrongDTO.getKm().equals(o.getKm()) && o.getDeviceType()==2 ).count();
        if (count > 0) {
            //throw new CustomException("该错已加入错题集");
            Response response = new Response(200, "该错已加入错题集");
            return response;
        }
        QuestionWrong questionWrong = new QuestionWrong();
        BeanUtils.copyProperties(questionWrongDTO, questionWrong);
        questionWrong.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        questionWrong.setDeviceType(2);
        return toResponse(questionWrongService.save(questionWrong) ? 1 : 0);
    }

    @PostMapping("wrongs")
    @ApiOperation("合并本机和云端错题")
    public Response<Integer> wrongs(@RequestBody QuestionWrongYunDTO wrong) {
        //查询该用户已收藏的题目列表
        QuestionWrongListDTO dto = new QuestionWrongListDTO();
        dto.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        List<QuestionWrong> dblist = questionWrongService.selectQuestionWrongList(dto);
        List<String> questionIdsStr = dblist.stream().map(o -> o.getQuestionId() + "," + o.getKm() + "," + o.getDeviceType()).collect(Collectors.toList());

        List<QuestionWrong> qlist = new ArrayList<QuestionWrong>();
        for (QuestionWgYunDTO wgYunDTO : wrong.getWrongs()) {
            if (questionIdsStr.contains(wgYunDTO.getId() + "," + wrong.getKm() + "," + "2")) {
                continue;
            }
            QuestionWrong questionWrong = new QuestionWrong();
            questionWrong.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
            questionWrong.setKm(wrong.getKm());
            questionWrong.setQuestionId(wgYunDTO.getId());
            questionWrong.setDeviceType(2);
            Date crDate = new Date(wgYunDTO.getTimestamp());
            questionWrong.setCreateTime(crDate);
            qlist.add(questionWrong);
        }
        if (qlist.isEmpty()) {
            Response response = new Response(200, "选中的错题都已添加！");
            return response;
        }
        return toResponse(questionWrongService.saveBatch(qlist) ? 1 : 0);
    }


    @PostMapping("bakWrongs")
    @ApiOperation("备份本机错题到云端")
    public Response bakWrongs(@RequestBody QuestionWrongYunDTO wrong) {
        //首先删除云端数据
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        QueryWrapper<QuestionWrong> queryWrapper = new QueryWrapper<QuestionWrong>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("km", wrong.getKm());
        queryWrapper.eq("device_type", 2);
        questionWrongService.remove(queryWrapper);

        //保存上传的错题
        List<QuestionWrong> qlist = new ArrayList<QuestionWrong>();
        for (QuestionWgYunDTO wgYunDTO : wrong.getWrongs()) {
            QuestionWrong questionWrong = new QuestionWrong();
            questionWrong.setUserId(userId);
            questionWrong.setKm(wrong.getKm());
            questionWrong.setQuestionId(wgYunDTO.getId());
            questionWrong.setDeviceType(2);
            Date crDate = new Date(wgYunDTO.getTimestamp());
            questionWrong.setCreateTime(crDate);
            qlist.add(questionWrong);
        }
        if (qlist.isEmpty()) {
            Response response = new Response(200, "该错已加入错题集(无须提示给用户)");
            return response;
        }
        return toResponse(questionWrongService.saveBatch(qlist) ? 1 : 0);
    }


    @DeleteMapping("/cancel/{questionId}")
    @ApiOperation("删除错题")
    public Response<Integer> remove(
            @ApiParam(name = "questionId", value = "问题id", required = true)
            @PathVariable Long questionId
    ) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        QueryWrapper<QuestionWrong> queryWrapper = new QueryWrapper<QuestionWrong>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("question_id", questionId);
        queryWrapper.eq("device_type",2);
        questionWrongService.remove(queryWrapper);
        return Response.success();

    }

    @DeleteMapping("/cancelAll")
    @ApiOperation("清空错题")
    public Response<Integer> removeAll(@RequestBody QuestionWrongDelDTO questionWrongDelDTO) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        QueryWrapper<QuestionWrong> queryWrapper = new QueryWrapper<QuestionWrong>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("km", questionWrongDelDTO.getKm());
        queryWrapper.eq("device_type",2);
        questionWrongService.remove(queryWrapper);
        return Response.success();
    }


    @GetMapping("/wrongByUser")
    @ApiOperation("恢复云端错题到本机（根据用户获取错题）")
    public Response<List<QuestionWrongIdDateVo>> appWrongByUser(@ModelAttribute QuestionWrongListDTO dto) {
        dto.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        dto.setDeviceType(2);
        List<QuestionWrongIdDateVo> list = questionWrongService.selectWrongIdByUserId(dto);
        return Response.success(list);
    }


    @GetMapping("/wrongCountByUser")
    @ApiOperation("根据用户获取错题数")
    public Response<Integer> wrongCountByUser(@ModelAttribute QuestionWrongListDTO dto) {
        dto.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        dto.setDeviceType(2);
        Integer count = questionWrongService.selectWrongCountByUserId(dto);
        return Response.success(count);
    }


}
