package com.yida.data.user.controller.in;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.user.EduStudentApply;
import com.yida.data.user.service.EduStudentApplyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "交易-学生应用关系(不鉴权)")
@RequiredArgsConstructor
@RequestMapping("/in/transaction/studentApply")
@RestController
public class InEduStudentApplyController {

    private final EduStudentApplyService eduStudentApplyService;
    private final RedisService redisService;

    @ApiOperation("查询学生的应用编码列表")
    @GetMapping("/listApply")
    public ResultBean<Map<Long, List<String>>> listApplyCode(@RequestParam("studentIds") Long[] studentIds) {
        List<EduStudentApply> applyCodeList = eduStudentApplyService.list(Wrappers.lambdaQuery(new EduStudentApply())
            .in(EduStudentApply::getStudentId, studentIds)
            .ge(EduStudentApply::getEndTime, LocalDateTime.now())
            .le(EduStudentApply::getStartTime, LocalDateTime.now()));
        Map<Long, List<String>> res = new HashMap<>();
        if (CollUtil.isNotEmpty(applyCodeList)) {
            Map<Long, List<EduStudentApply>> collect = applyCodeList.stream()
                .collect(Collectors.groupingBy(EduStudentApply::getStudentId));
            for (Map.Entry<Long, List<EduStudentApply>> entry : collect.entrySet()) {
                List<String> applyCode = entry.getValue().stream().map(x -> x.getApplyCode()).distinct()
                    .collect(Collectors.toList());
                res.put(entry.getKey(), applyCode);
                redisService.hset(CachePrefixConstant.STUDENT_APPLY, entry.getKey().toString(), applyCode);
            }
        }
        return ResultBean.buildSuccess(res);
    }

}
