package jnpf.cultivate.controller.web.statistics;

import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.cultivate.service.CultivateIdentifyApplyService;
import jnpf.cultivate.service.FtbCultivateExamUserService;
import jnpf.cultivate.service.FtbCultivateStatisticsService;
import jnpf.model.cultivate.dto.statistics.FtbCultivateStatisticsDTO;
import jnpf.model.cultivate.resp.ExamStatisticsVo;
import jnpf.model.cultivate.vo.identify.IdentifyStatisticsVo;
import jnpf.model.cultivate.vo.statistics.FtbCultivateStatisticsVO;
import jnpf.model.cultivate.vo.statistics.NumberOfTrainingSessions;
import jnpf.permission.V2UserApi;
import jnpf.permission.dto.v2.user.QueryPageUserDTO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * web数据看板
 *
 * @Author:peng.hao
 * @create: 2023/12/2915:03
 */
@Slf4j
@RestController
@RequestMapping("/cultivate-statistics")
public class FtbCultivateStatisticsController {

    @Resource
    private FtbCultivateStatisticsService ftbCultivateStatisticsService;

    @Resource
    private FtbCultivateExamUserService examUserService;

    @Autowired
    private V2UserApi v2UserApi;

    @Resource
    private CultivateIdentifyApplyService applyService;

    /**
     * web 全局概览【顶部数据】
     *
     * @param dto 统计数据DTO对象
     * @return 受训学员统计数据结果ActionResult对象
     */
    @GetMapping("/getNumberOfTrainees")
    public ActionResult<NumberOfTrainingSessions> getNumberOfTraineesStatistics(FtbCultivateStatisticsDTO dto) {
        getUserList(dto);
        NumberOfTrainingSessions number = ftbCultivateStatisticsService.getNumberOfTraineesStatistics(dto);
        return ActionResult.success(number);
    }

    /**
     * 获取考试统计相关信息
     *
     * @param dto 统计数据DTO对象
     * @return 返回考试通过率的结果 ActionResult 对象
     */
    @GetMapping("/getExamStatistics")
    public ActionResult<ExamStatisticsVo> getExamStatistics(FtbCultivateStatisticsDTO dto) {
        return ActionResult.success(examUserService.statistics(dto));
    }

    /**
     * web 全局概览【热门课程】
     *
     * @param dto 统计数据DTO对象
     * @return 热门课程的ActionResult对象
     */
    @GetMapping("/getPopularCourses")
    public ActionResult<List<FtbCultivateStatisticsVO.PopularCourses>> getPopularCourses(FtbCultivateStatisticsDTO dto) {
        getUserList(dto);
        return ActionResult.success(ftbCultivateStatisticsService.getPopularCourses(dto));
    }

    /**
     * web 全局概览【学习人数和学习时长折线图统计】
     *
     * @param dto
     * @return
     */
    @GetMapping("/numberOfStudents")
    public ActionResult<List<FtbCultivateStatisticsVO.LineChartCumulativeLearners>> numberOfStudents(FtbCultivateStatisticsDTO dto) {
        getUserList(dto);
        List<FtbCultivateStatisticsVO.LineChartCumulativeLearners> popularCourses = ftbCultivateStatisticsService.numberOfStudentsLineGraph(dto);
        return ActionResult.success(popularCourses);
    }

    /**
     * 数据看板/统计（鉴定）
     *
     * @param req
     * @return {@link ActionResult}<{@link IdentifyStatisticsVo}>
     */
    @GetMapping(value = "/apply/statistics")
    public ActionResult<IdentifyStatisticsVo> getIdentifyStatistics(@Valid FtbCultivateStatisticsDTO req) {
        getUserList(req);
        if (CollectionUtils.isEmpty(req.getUserIds())) {
            return ActionResult.success(new IdentifyStatisticsVo());
        }
        return ActionResult.success(applyService.getIdentifyStatistics(req));
    }

    /**
     * web 全局概览 课程学习 成员排行
     *
     * @param dto         统计数据DTO对象
     * @param rankingType 排名类型，1学时，2考试，3鉴定，必传
     * @return 统计数据视图对象中的顶级成员结果
     */
    @GetMapping("/getTopMembers")
    public ActionResult<List<FtbCultivateStatisticsVO.TopMembers>> getTopMembers(FtbCultivateStatisticsDTO dto, Integer rankingType) {
        getUserList(dto);
        List<FtbCultivateStatisticsVO.TopMembers> result = ftbCultivateStatisticsService.getTopMembers(dto, rankingType);
        return ActionResult.success(result);
    }

    /**
     * 获取用户列表
     *
     * @param dto
     */
    private void getUserList(FtbCultivateStatisticsDTO dto) {
        // 如果组织ID为空，直接返回空列表
        if (StringUtils.isEmpty(dto.getOrgId())) {
            dto.setUserIds(Collections.emptyList());
            return;
        }

        // 构造查询条件
        QueryPageUserDTO req = new QueryPageUserDTO();
        req.setOrganizeIds(List.of(dto.getOrgId().split(",")));
        req.setIsPage(false);
        if (dto.getIsSelectNext() != null && dto.getIsSelectNext().equals(1)) {
            req.setHaveChildOrganizeId(true);
        } else {
            req.setHaveChildOrganizeId(false);
        }
        ActionResult<PageListVO<UserBoundVO>> listByLevel = v2UserApi.pagePost(req);
        List<String> userSubQueryList = listByLevel.getCode() == 200 ?
                listByLevel.getData().getList().stream().map(UserBoundVO::getId).collect(Collectors.toList())
                : new ArrayList<>();

        // 查询结果为空时，设置空列表
        dto.setUserIds(userSubQueryList);
    }


}
