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.QuestionCollection;
import com.miaxis.question.dto.QuestionCollectionDTO;
import com.miaxis.question.dto.QuestionCollectionListDTO;
import com.miaxis.question.service.IQuestionCollectionService;
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;

/**
 * 【collection】Controller
 *
 * @author miaxis
 * @date 2021-08-18
 */
@RestController
@RequestMapping(Constants.STUDENT_PREFIX+"/question/collection")
@Api(tags={"【H5-题目收藏】"})
public class QuestionCollectionController extends BaseController {
    @Autowired
    private IQuestionCollectionService questionCollectionService;

    /**
     * 查询collection列表
     */

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

    /**
     * 导出collection列表
     */
//    @PreAuthorize("@ss.hasPermi('question:collection:export')")
//    @Log(title = "collection", businessType = BusinessTypeEnum.EXPORT)
//    @GetMapping("/export")
//    @ApiOperation("导出collection列表Excel")
//    public Response<String> export(@ModelAttribute QuestionCollection questionCollection){
//        List<QuestionCollection> list = questionCollectionService.selectQuestionCollectionList(questionCollection);
//        ExcelUtil<QuestionCollection> util = new ExcelUtil<QuestionCollection>(QuestionCollection.class);
//        return util.exportExcel(list, "collection");
//    }

    /**
     * 获取collection详细信息
     */
//    @PreAuthorize("@ss.hasPermi('question:collection:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取collection详细信息")
    public Response<QuestionCollection> getInfo(
            @ApiParam(name = "id", value = "collection参数", required = true)
            @PathVariable("id") Long id
    ) {
        return Response.success(questionCollectionService.getById(id));
    }

    /**
     * 新增collection
     */
    @Log(title = "collection", businessType = BusinessTypeEnum.INSERT)
    @PostMapping
    @ApiOperation("新增collection")
    public Response<Integer> add(@RequestBody QuestionCollectionDTO questionCollectionDTO) {
        //查询该用户已收藏的题目列表
        QuestionCollectionListDTO dto = new QuestionCollectionListDTO();
        dto.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
        List<QuestionCollection> list = questionCollectionService.selectQuestionCollectionList(dto);
        long count = list.stream().filter(o -> questionCollectionDTO.getQuestionId().equals(o.getQuestionId()) && questionCollectionDTO.getKm().equals(o.getKm())).count();
        if (count > 0) {
            throw new CustomException("该题目已收藏过");
        }
        QuestionCollection questionCollection = new QuestionCollection();
        BeanUtils.copyProperties(questionCollectionDTO, questionCollection);
        questionCollection.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
        return toResponse(questionCollectionService.save(questionCollection) ? 1 : 0);
    }

    @PostMapping("collections")
    @ApiOperation("批量新增collection")
    public Response<Integer> collections(@RequestBody List<QuestionCollectionDTO> list) {
        //查询该用户已收藏的题目列表
        QuestionCollectionListDTO dto = new QuestionCollectionListDTO();
        dto.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
        List<QuestionCollection> dblist = questionCollectionService.selectQuestionCollectionList(dto);
        List<String> questionIds = dblist.stream().map(o -> (o.getQuestionId()+","+o.getKm())).collect(Collectors.toList());


        List<QuestionCollection> qlist = new ArrayList<QuestionCollection>();
        for (QuestionCollectionDTO questionCollectionDTO : list) {
            if (questionIds.contains(questionCollectionDTO.getQuestionId()+","+questionCollectionDTO.getKm())) {
                continue;
            }
            QuestionCollection questionCollection = new QuestionCollection();
            BeanUtils.copyProperties(questionCollectionDTO, questionCollection);
            questionCollection.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
            qlist.add(questionCollection);
        }
        if (qlist.isEmpty()) {
            throw new CustomException("选中的题目已收藏！");
        }
        return toResponse(questionCollectionService.saveBatch(qlist) ? 1 : 0);
    }


    /**
     * 修改collection
     */
//    @PreAuthorize("@ss.hasPermi('question:collection:edit')")
    @Log(title = "collection", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    @ApiOperation("修改collection")
    public Response<Integer> edit(@RequestBody QuestionCollectionDTO questionCollectionDTO) {
        QuestionCollection questionCollection = new QuestionCollection();
        BeanUtils.copyProperties(questionCollectionDTO, questionCollection);
        questionCollection.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
        return toResponse(questionCollectionService.updateById(questionCollection) ? 1 : 0);
    }

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


    @Log(title = "collectionQuestion", 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<QuestionCollection> queryWrapper = new QueryWrapper<QuestionCollection>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("question_id", questionId);
        questionCollectionService.remove(queryWrapper);
        return Response.success();

    }




}
