package org.dromara.main.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.main.domain.MainExamEvaluation;
import org.dromara.main.domain.MainPostApply;
import org.dromara.main.mapper.MainExamEvaluationMapper;
import org.dromara.main.mapper.MainPostApplyMapper;
import org.dromara.system.domain.SysDept;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 仪表盘统计控制器
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/main/dashboard")
public class MainDashboardController {

    private final MainPostApplyMapper mainPostApplyMapper;
    private final MainExamEvaluationMapper mainExamEvaluationMapper;
    private final SysUserMapper sysUserMapper;
    private final SysDeptMapper sysDeptMapper;

    /**
     * 岗位管理近日发布数量报表 (近7日)
     */
    @GetMapping("/postRecentStats")
    public R<List<Map<String, Object>>> postRecentStats() {
        DateTime startDate = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -6));
        
        List<MainPostApply> postApplies = mainPostApplyMapper.selectList(new LambdaQueryWrapper<MainPostApply>()
            .ge(MainPostApply::getCreateTime, startDate));

        // 按日期分组统计
        Map<String, Long> grouped = postApplies.stream()
            .filter(item -> item.getCreateTime() != null)
            .collect(Collectors.groupingBy(
                item -> DateUtil.format(item.getCreateTime(), "MM-dd"),
                Collectors.counting()
            ));

        // 补全近7天每一天的数据
        List<Map<String, Object>> result = new ArrayList<>();
        for (int i = -6; i <= 0; i++) {
            DateTime date = DateUtil.offsetDay(new Date(), i);
            String dateStr = DateUtil.format(date, "MM-dd");
            long count = grouped.getOrDefault(dateStr, 0L);
            result.add(MapUtil.builder(new HashMap<String, Object>())
                .put("date", dateStr)
                .put("count", count)
                .build());
        }

        return R.ok(result);
    }

    /**
     * 测评管理总发布数量报表
     */
    @GetMapping("/evaluationTotalStats")
    public R<Long> evaluationTotalStats() {
        long count = mainExamEvaluationMapper.selectCount(new LambdaQueryWrapper<MainExamEvaluation>());
        return R.ok(count);
    }

    /**
     * 当前租户的公司员工人数统计
     */
    @GetMapping("/companyStats")
    public R<Long> companyStats() {
        // 由于存在多租户插件和数据权限拦截器，直接查询 count 即可得到当前租户、当前数据权限下的人员数
        Long count = sysUserMapper.selectCount(new LambdaQueryWrapper<SysUser>());
        return R.ok(count);
    }

    /**
     * 当前租户的真实部门数量统计（排除顶级公司节点）
     */
    @GetMapping("/deptStats")
    public R<Long> deptStats() {
        Long count = sysDeptMapper.selectCount(new LambdaQueryWrapper<SysDept>()
            .ne(SysDept::getParentId, 0L));
        return R.ok(count);
    }

    /**
     * 昨日加入公司(新增用户)人数统计
     */
    @GetMapping("/userYesterdayStats")
    public R<Long> userYesterdayStats() {
        DateTime yesterdayStart = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1));
        DateTime yesterdayEnd = DateUtil.endOfDay(DateUtil.offsetDay(new Date(), -1));
        Long count = sysUserMapper.selectCount(new LambdaQueryWrapper<SysUser>()
            .ge(SysUser::getCreateTime, yesterdayStart)
            .le(SysUser::getCreateTime, yesterdayEnd));
        return R.ok(count);
    }
}
