package com.sundot.airport.web.controller.daily;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.exam.domain.DailyTask;
import com.sundot.airport.exam.dto.DeptProfileDTO;
import com.sundot.airport.exam.dto.DeptProfileQueryDTO;
import com.sundot.airport.exam.mapper.DailyTaskMapper;
import com.sundot.airport.exam.service.IDeptProfileService;
import com.sundot.airport.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
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;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <b>功能名：</b>DeptProfileController<br>
 * <b>说明：</b> 组织画像Controller <br>
 * <b>著作权：</b> Copyright (C) 2025 SUNDOT CORPORATION<br>
 * <b>修改履历：
 *
 * @author Claude
 */
@Api(tags = "组织画像")
@RestController
@RequestMapping("/exam/daily/dept-profile")
public class DeptProfileController extends BaseController {

    @Autowired
    private IDeptProfileService deptProfileService;

    @Autowired
    private DailyTaskMapper dailyTaskMapper;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取组织画像
     */
    @ApiOperation("获取组织画像")
    @GetMapping
    public AjaxResult getDeptProfile(
            @ApiParam(value = "部门ID", required = true)
            @RequestParam Long deptId,

            @ApiParam(value = "开始日期", required = false, example = "2025-01-01")
            @RequestParam(required = false) String startDate,

            @ApiParam(value = "结束日期", required = false, example = "2025-01-31")
            @RequestParam(required = false) String endDate) {

        // 如果没有传日期范围,则默认为91天
        if (startDate == null || endDate == null) {
            java.time.LocalDate today = java.time.LocalDate.now();
            endDate = today.toString();
            startDate = today.minusDays(91).toString();
        }

        DeptProfileQueryDTO query = new DeptProfileQueryDTO();
        query.setDeptId(deptId);
        query.setStartDate(startDate);
        query.setEndDate(endDate);

        DeptProfileDTO profile = deptProfileService.getDeptProfile(query);

        return success(profile);
    }

    /**
     * 获取部门每日抽问抽答完成率
     * 统计该部门及其所有下级部门成员的抽问抽答完成率
     * 例如：传入科级ID，统计该科级下所有班组成员的完成率
     */
    @ApiOperation("获取部门每日抽问抽答完成率")
    @GetMapping("/daily-completion-rate")
    public AjaxResult getDailyCompletionRate(
            @ApiParam(value = "部门ID（可以是科级ID、班组ID等）", required = true)
            @RequestParam Long deptId,

            @ApiParam(value = "开始日期", required = false, example = "2025-01-01")
            @RequestParam(required = false) String startDate,

            @ApiParam(value = "结束日期", required = false, example = "2025-01-31")
            @RequestParam(required = false) String endDate) {

        try {
            // 如果没有传日期范围,则默认为91天
            if (startDate == null || endDate == null) {
                LocalDate today = LocalDate.now();
                endDate = today.toString();
                startDate = today.minusDays(91).toString();
            }

            // 获取该部门及所有下级部门的ID列表（例如：科级 -> 所有班组）
            List<Long> deptIds = getAllSubDeptIds(deptId);
            logger.info("查询部门ID={} 的下级部门，共找到 {} 个部门: {}", deptId, deptIds.size(), deptIds);

            if (deptIds.isEmpty()) {
                return success(new ArrayList<>());
            }

            // 转换日期
            LocalDate start = LocalDate.parse(startDate);
            LocalDate end = LocalDate.parse(endDate);

            // 构建日期范围的Map，存储每一天的完成率
            Map<String, Map<String, Object>> dailyStats = new LinkedHashMap<>();

            // 初始化每一天的数据
            LocalDate currentDate = start;
            while (!currentDate.isAfter(end)) {
                String dateStr = currentDate.toString();
                Map<String, Object> dayData = new HashMap<>();
                dayData.put("date", dateStr);
                dayData.put("completionRate", BigDecimal.ZERO);
                dayData.put("totalTasks", 0);
                dayData.put("completedTasks", 0);
                dailyStats.put(dateStr, dayData);
                currentDate = currentDate.plusDays(1);
            }

            // 查询该时间段内所有任务
            LambdaQueryWrapper<DailyTask> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(DailyTask::getDtDeptId, deptIds);
            wrapper.ge(DailyTask::getDtBusinessDate, Date.valueOf(startDate));
            wrapper.le(DailyTask::getDtBusinessDate, Date.valueOf(endDate));
            wrapper.eq(DailyTask::getDelStatus, 0);

            List<DailyTask> tasks = dailyTaskMapper.selectList(wrapper);
            logger.info("查询到 {} 条任务记录", tasks.size());

            // 按日期分组统计（使用SimpleDateFormat格式化日期）
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Map<String, List<DailyTask>> tasksByDate = tasks.stream()
                    .collect(Collectors.groupingBy(task -> sdf.format(task.getDtBusinessDate())));

            // 计算每一天的完成率
            for (Map.Entry<String, List<DailyTask>> entry : tasksByDate.entrySet()) {
                String dateStr = entry.getKey();
                List<DailyTask> dayTasks = entry.getValue();

                int totalTasks = dayTasks.size();
                long completedTasks = dayTasks.stream()
                        .filter(task -> "COMPLETED".equals(task.getDtStatus()))
                        .count();

                BigDecimal completionRate = BigDecimal.ZERO;
                if (totalTasks > 0) {
                    completionRate = new BigDecimal(completedTasks)
                            .multiply(new BigDecimal(100))
                            .divide(new BigDecimal(totalTasks), 2, RoundingMode.HALF_UP);
                }

                if (dailyStats.containsKey(dateStr)) {
                    Map<String, Object> dayData = dailyStats.get(dateStr);
                    dayData.put("completionRate", completionRate);
                    dayData.put("totalTasks", totalTasks);
                    dayData.put("completedTasks", completedTasks);
                }
            }

            // 转换为数组返回
            List<Map<String, Object>> result = new ArrayList<>(dailyStats.values());

            return success(result);
        } catch (Exception e) {
            logger.error("获取部门每日完成率失败", e);
            return error("获取部门每日完成率失败：" + e.getMessage());
        }
    }

    /**
     * 获取指定部门及其所有下级部门的ID列表
     * 根据sys_dept表的层级关系递归查找
     * 例如：传入科级ID，返回该科级ID及其所有下级班组ID
     */
    private List<Long> getAllSubDeptIds(Long deptId) {
        List<Long> result = new ArrayList<>();
        result.add(deptId); // 包含自己

        // 查询直接下级部门
        SysDept queryDept = new SysDept();
        queryDept.setParentId(deptId);
        List<SysDept> subDepts = deptService.selectDeptInfoAll(queryDept);

        // 递归查询所有下级部门
        for (SysDept subDept : subDepts) {
            if ("0".equals(subDept.getDelFlag())) { // 只包含未删除的部门
                result.addAll(getAllSubDeptIds(subDept.getDeptId()));
            }
        }

        return result;
    }
}
