package com.miaxis.app.controller.h5;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miaxis.common.annotation.Log;
import com.miaxis.common.constant.Constants;
import com.miaxis.common.core.controller.BaseController;
import com.miaxis.common.core.domain.Response;
import com.miaxis.common.core.page.ResponsePageInfo;
import com.miaxis.common.enums.BusinessTypeEnum;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.SecurityUtils;
import com.miaxis.question.domain.QuestionWrong;
import com.miaxis.question.dto.QuestionWrongDTO;
import com.miaxis.question.dto.QuestionWrongListDTO;
import com.miaxis.question.service.IQuestionWrongService;
import io.swagger.annotations.*;
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.Arrays;
import java.util.List;
import java.util.stream.Collectors;

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

    /**
     * 查询wrong列表
     */
    @GetMapping("/list")
    @ApiOperation("查询wrong列表")
        @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "当前页码" ,dataType = "int", paramType = "query", required = false),
            @ApiImplicitParam(name = "pageSize",value = "每页数据量" , dataType = "int", paramType = "query", required = false),
    })
    public ResponsePageInfo<QuestionWrong> list(@ModelAttribute QuestionWrongListDTO dto){
        startPage();
        dto.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
        List<QuestionWrong> list = questionWrongService.selectQuestionWrongList(dto);
        return toResponsePageInfo(list);
    }



    /**
     * 获取wrong详细信息
     */
    @GetMapping(value = "/{id}")
    @ApiOperation("获取wrong详细信息")
    public Response<QuestionWrong> getInfo(
            @ApiParam(name = "id", value = "wrong参数", required = true)
            @PathVariable("id") Long id
    ){
        return Response.success(questionWrongService.getById(id));
    }

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

    @PostMapping("wrongs")
    @ApiOperation("批量新增wrongs")
    public Response<Integer> wrongs(@RequestBody List<QuestionWrongDTO> list){
        //查询该用户已收藏的题目列表
        QuestionWrongListDTO dto = new QuestionWrongListDTO();
        dto.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
        List<QuestionWrong> dblist = questionWrongService.selectQuestionWrongList(dto);
        List<String> questionIds = dblist.stream().map(o -> o.getQuestionId()+","+o.getKm()).collect(Collectors.toList());
        List<QuestionWrong> qlist = new ArrayList<QuestionWrong>();
        for (QuestionWrongDTO questionWrongDTO : list) {
            if (questionIds.contains(questionWrongDTO.getQuestionId()+","+questionWrongDTO.getKm())) {
                continue;
            }
            QuestionWrong questionWrong = new QuestionWrong();
            BeanUtils.copyProperties(questionWrongDTO, questionWrong);
            questionWrong.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
            qlist.add(questionWrong);
        }
        if (qlist.isEmpty()) {
            throw new CustomException("选中的错题都已收藏！");
        }
        return toResponse(questionWrongService.saveBatch(qlist) ? 1 : 0);
    }

    /**
     * 修改wrong
     */
    @Log(title = "wrong", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    @ApiOperation("修改wrong")
    public Response<Integer> edit(@RequestBody QuestionWrong questionWrong){
        return toResponse(questionWrongService.updateById(questionWrong) ? 1 : 0);
    }

    /**
     * 删除wrong
     */
    @Log(title = "wrong", businessType = BusinessTypeEnum.DELETE)
	@DeleteMapping("/{ids}")
    @ApiOperation("删除wrong")
    public Response<Integer> remove(
            @ApiParam(name = "ids", value = "wrongids参数", required = true)
            @PathVariable Long[] ids
    ){
        return toResponse(questionWrongService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


    @Log(title = "wrongQuestion", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/cancel/{questionId}")
    @ApiOperation("删除错题")
    public Response<Integer> remove(
            @ApiParam(name = "questionId", value = "问题id", required = true)
            @PathVariable String questionId
    ){
        Long userId = SecurityUtils.getLoginUser().getStudent().getId();
        QueryWrapper<QuestionWrong> queryWrapper= new QueryWrapper<QuestionWrong>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("question_id",questionId);
        questionWrongService.remove(queryWrapper);
        return Response.success();

    }
}
