package com.ynfy.buss.exam.repository.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ynfy.buss.exam.question.dto.QuestionDTO;
import com.ynfy.buss.exam.question.enums.QuestionType;
import com.ynfy.buss.exam.question.service.IQuestionService;
import com.ynfy.buss.exam.repository.entity.Repository;
import com.ynfy.buss.exam.repository.service.IRepositoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: repository
 * @Author: jeecg-boot
 * @Date: 2023-02-22
 * @Version: V1.0
 */
@Api(tags = "题库")
@RestController
@RequestMapping("/repository")
@Slf4j
public class RepositoryController extends JeecgController<Repository, IRepositoryService> {
    @Autowired
    private IRepositoryService repositoryService;

    @Autowired
    private IQuestionService questionService;

    /**
     * 列表查询
     *
     * @return
     */
    @GetMapping(value = "/listAll")
    public Result<List<Repository>> listAll(Repository repository) {
        QueryWrapper<Repository> queryWrapper = QueryGenerator.initQueryWrapper(repository, null);
        List<Repository> list = repositoryService.list(queryWrapper);
        return Result.OK(list);
    }

    /**
     * 分页列表查询
     *
     * @param repository
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "题库-分页列表查询", notes = "题库-分页列表查询")
    @GetMapping(value = "/list")
    //@RequiresPermissions("repository:list")
    public Result<IPage<Repository>> queryPageList(Repository repository,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        QueryWrapper<Repository> queryWrapper = QueryGenerator.initQueryWrapper(repository, req.getParameterMap());
        Page<Repository> page = new Page<Repository>(pageNo, pageSize);
        IPage<Repository> pageList = repositoryService.page(page, queryWrapper);
        List<Repository> list = pageList.getRecords();
        if (!CollectionUtils.isEmpty(list)) {
            List<String> idList = list.stream().map(Repository::getId).collect(Collectors.toList());
            List<QuestionDTO> questionDTOList = questionService.countQuestionType(idList);
            Map<String, List<QuestionDTO>> map = questionDTOList.stream().collect(Collectors
                    .groupingBy(QuestionDTO::getRepositoryId, Collectors.toList()));
            list.forEach(l -> {
                List<QuestionDTO> dtoList = map.get(l.getId());
                if (!CollectionUtils.isEmpty(dtoList)) {
                    l.setNum(dtoList.stream().mapToInt(QuestionDTO::getNum).sum());
                    StringBuilder str = new StringBuilder();
                    int index = 0;
                    for (QuestionDTO dto : dtoList) {
                        str.append(QuestionType.getByCode(dto.getType()).getValue()).append(dto.getNum()).append("题");
                        if (index < dtoList.size() - 1) {
                            str.append("，");
                        }
                        index++;
                    }
                    l.setQuestionRemark(str.toString());
                }
            });
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param repository
     * @return
     */
    @AutoLog(value = "题库-添加")
    @ApiOperation(value = "题库-添加", notes = "题库-添加")
    @RequiresPermissions("repository:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Repository repository) {
        repositoryService.save(repository);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param repository
     * @return
     */
    @AutoLog(value = "题库-编辑")
    @ApiOperation(value = "题库-编辑", notes = "题库-编辑")
    @RequiresPermissions("repository:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody Repository repository) {
        repositoryService.updateById(repository);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "题库-通过id删除")
    @ApiOperation(value = "题库-通过id删除", notes = "题库-通过id删除")
    @RequiresPermissions("repository:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        repositoryService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "题库-批量删除")
    @ApiOperation(value = "题库-批量删除", notes = "题库-批量删除")
    @RequiresPermissions("repository:delete")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.repositoryService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "题库-通过id查询", notes = "题库-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Repository> queryById(@RequestParam(name = "id", required = true) String id) {
        Repository repository = repositoryService.getById(id);
        if (repository == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(repository);
    }

    /**
     * 计算指定题库的题目题型数量
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "计算指定题库的题目题型数量", notes = "计算指定题库的题目题型数量")
    @GetMapping(value = "/getById")
    public Result<Repository> getById(@RequestParam String id) {
        Repository repository = repositoryService.getById(id);
        repository.setQuestionDTOList(questionService.countQuestionNumByType(id));
        return Result.OK(repository);
    }
}
