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.*;
import com.miaxis.question.service.IQuestionCollectionService;
import com.miaxis.question.vo.QuestionColIdDateVo;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
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
     */
    @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()) && o.getDeviceType()==1).count();
        if (count > 0) {
            Response response = new Response(200,"该题目已收藏过");
            return response;
        }
        QuestionCollection questionCollection = new QuestionCollection();
        BeanUtils.copyProperties(questionCollectionDTO, questionCollection);
        questionCollection.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
        questionCollection.setDeviceType(1);
        return toResponse(questionCollectionService.save(questionCollection) ? 1 : 0);
    }

    @PostMapping("collections")
    @ApiOperation("合并本机和云端收藏")
    public Response<Integer> collections(@RequestBody QuestionCollectionYunDTO col) {
        //查询该用户已收藏的题目列表
        QuestionCollectionListDTO dto = new QuestionCollectionListDTO();
        dto.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
        List<QuestionCollection> dblist = questionCollectionService.selectQuestionCollectionList(dto);
        List<String> questionIdsStr = dblist.stream().map(o -> (o.getQuestionId()+","+o.getKm()+","+o.getDeviceType())).collect(Collectors.toList());

        List<QuestionCollection> qlist = new ArrayList<QuestionCollection>();
        for (QuestionColYunDTO colDTO : col.getCols()) {
            if (questionIdsStr.contains(colDTO.getId()+","+col.getKm()+","+"1")) {
                continue;
            }
            QuestionCollection questionCollection = new QuestionCollection();
            questionCollection.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
            questionCollection.setKm(col.getKm());
            questionCollection.setQuestionId(colDTO.getId());
            Timestamp crDate = new Timestamp(colDTO.getTimestamp());
            questionCollection.setCreateTime(crDate);
            questionCollection.setDeviceType(1);
            qlist.add(questionCollection);
        }
        if (qlist.isEmpty()) {
            Response response = new Response(200,"选中的题目已收藏！");
            return response;
        }
        return toResponse(questionCollectionService.saveBatch(qlist) ? 1 : 0);
    }


    @PostMapping("bakCollections")
    @ApiOperation("备份本机收藏到云端")
    public Response bakCollections(@RequestBody QuestionCollectionYunDTO col) {
        //首先删除云端数据
        Long userId = SecurityUtils.getLoginUser().getStudent().getId();
        QueryWrapper<QuestionCollection> queryWrapper = new QueryWrapper<QuestionCollection>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("km",col.getKm());
        queryWrapper.eq("device_type",1);
        questionCollectionService.remove(queryWrapper);

        //保存上传的收藏题
        List<QuestionCollection> qlist = new ArrayList<QuestionCollection>();
        for (QuestionColYunDTO colDTO : col.getCols()) {
            QuestionCollection questionCollection = new QuestionCollection();
            questionCollection.setUserId(userId);
            questionCollection.setKm(col.getKm());
            questionCollection.setQuestionId(colDTO.getId());
            Timestamp crDate = new Timestamp(colDTO.getTimestamp());
            questionCollection.setCreateTime(crDate);
            questionCollection.setDeviceType(1);
            qlist.add(questionCollection);
        }
        if (qlist.isEmpty()) {
            Response response = new Response(200,"请先收藏题目。");
            return response;
        }
        return toResponse(questionCollectionService.saveBatch(qlist) ? 1 : 0);
    }


    @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);
        queryWrapper.eq("device_type",1);
        questionCollectionService.remove(queryWrapper);
        return Response.success();
    }


    @DeleteMapping("/cancelAll")
    @ApiOperation("清空收藏")
    public  Response<Integer> removeAll(@RequestBody QuestionCollectionDelDTO questionCollectionDelDTO){
        Long userId = SecurityUtils.getLoginUser().getStudent().getId();
        QueryWrapper<QuestionCollection> queryWrapper = new QueryWrapper<QuestionCollection>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("km",questionCollectionDelDTO.getKm());
        queryWrapper.eq("device_type",1);
        questionCollectionService.remove(queryWrapper);
        return Response.success();
    }



    @GetMapping("/collectionByUser")
    @ApiOperation("恢复云端收藏到本机（根据用户获取收藏题）")
    public Response<List<QuestionColIdDateVo>> appCollectionByUser(@ModelAttribute QuestionCollectionListDTO dto){
        dto.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
        dto.setDeviceType(1);
        List<QuestionColIdDateVo> list = questionCollectionService.selectCollectionIdByUserId(dto);
        return Response.success(list);
    }

    @GetMapping("/collectionCountByUser")
    @ApiOperation("根据用户获取收藏题数")
    public Response<Integer> collectionCountByUser(@ModelAttribute QuestionCollectionListDTO dto){
        dto.setUserId(SecurityUtils.getLoginUser().getStudent().getId());
        dto.setDeviceType(1);
        Integer count = questionCollectionService.selectCollectionCountByUserId(dto);
        return Response.success(count);
    }



}
