package com.gxwebsoft.hjm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.hjm.entity.HjmChoices;
import com.gxwebsoft.hjm.mapper.HjmQuestionsMapper;
import com.gxwebsoft.hjm.service.HjmChoicesService;
import com.gxwebsoft.hjm.service.HjmQuestionsService;
import com.gxwebsoft.hjm.entity.HjmQuestions;
import com.gxwebsoft.hjm.param.HjmQuestionsParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 黄家明_题目Service实现
 *
 * @author 科技小王子
 * @since 2025-06-02 12:59:49
 */
@Service
public class HjmQuestionsServiceImpl extends ServiceImpl<HjmQuestionsMapper, HjmQuestions> implements HjmQuestionsService {
  @Resource
  private HjmChoicesService hjmChoicesService;

  @Override
  public PageResult<HjmQuestions> pageRel(HjmQuestionsParam param) {
    PageParam<HjmQuestions, HjmQuestionsParam> page = new PageParam<>(param);
    page.setDefaultOrder("sort_number asc, create_time desc");
    List<HjmQuestions> list = baseMapper.selectPageRel(page, param);
    final Set<Integer> collectByIds = list.stream().map(HjmQuestions::getId).collect(Collectors.toSet());
    final List<HjmChoices> choices = hjmChoicesService.list(new LambdaQueryWrapper<HjmChoices>().in(HjmChoices::getQuestionId, collectByIds));
    final Map<Integer, List<HjmChoices>> collectByQuestionId = choices.stream().collect(Collectors.groupingBy(HjmChoices::getQuestionId));
    list.forEach(item -> {
      final List<HjmChoices> choicesList = collectByQuestionId.get(item.getId());
      item.setChoicesList(choicesList);
    });
    return new PageResult<>(list, page.getTotal());
  }

  @Override
  public List<HjmQuestions> listRel(HjmQuestionsParam param) {
    List<HjmQuestions> list = baseMapper.selectListRel(param);
    // 排序
    PageParam<HjmQuestions, HjmQuestionsParam> page = new PageParam<>();
    page.setDefaultOrder("sort_number asc, create_time desc");
    return page.sortRecords(list);
  }

  @Override
  public HjmQuestions getByIdRel(Integer id) {
    HjmQuestionsParam param = new HjmQuestionsParam();
    param.setId(id);
    return param.getOne(baseMapper.selectListRel(param));
  }

}
