package com.cool.modules.dailyreport.controller.admin;

import cn.hutool.json.JSONObject;
import com.cool.core.annotation.CoolRestController;
import com.cool.core.base.BaseController;
import com.cool.core.request.R;
import com.cool.modules.dailyreport.entity.DailyReportEntity;
import com.cool.modules.dailyreport.service.DailyReportService;
import com.cool.modules.weeklyreport.entity.WeeklyReportEntity;
import com.cool.modules.weeklyreport.service.WeeklyReportService;
import com.cool.modules.monthlyreport.entity.MonthlyReportEntity;
import com.cool.modules.monthlyreport.service.MonthlyReportService;
import com.cool.modules.dailyreport.service.DailyReportAiService;
import com.cool.modules.base.service.sys.BaseSysParamService;
import com.cool.modules.user.entity.UserInfoEntity;
import com.cool.modules.user.mapper.UserInfoMapper;
import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cool.modules.dailyreport.entity.table.DailyReportEntityTableDef.DAILY_REPORT_ENTITY;
import static com.cool.modules.user.entity.table.UserInfoEntityTableDef.USER_INFO_ENTITY;

/**
 * 管理端日报Controller
 */
@Slf4j
@Tag(name = "管理端日报", description = "管理端日报查看和统计")
@CoolRestController(api = {"page", "list", "info"})
@RequiredArgsConstructor
public class AdminReportController extends BaseController<DailyReportService, DailyReportEntity> {

    private final UserInfoMapper userInfoMapper;
    private final DailyReportAiService dailyReportAiService;
    private final BaseSysParamService baseSysParamService;
    private final WeeklyReportService weeklyReportService;
    private final MonthlyReportService monthlyReportService;

    @Override
    protected void init(HttpServletRequest request, JSONObject requestParams) {
        log.info("【管理端日报Controller】接收到请求参数: {}", requestParams);

        // 构建查询条件
        QueryWrapper qw = QueryWrapper.create()
                .orderBy(DAILY_REPORT_ENTITY.REPORT_DATE, false) // 按日期倒序
                .orderBy(DAILY_REPORT_ENTITY.CREATE_TIME, false); // 按创建时间倒序

        // 部门ID筛选（需要关联user_info表）
        if (requestParams.containsKey("deptId") && requestParams.get("deptId") != null) {
            Long deptId = requestParams.getLong("deptId");
            log.info("【管理端日报Controller】添加deptId筛选条件: {}", deptId);
            // 需要join user_info表来筛选部门
            qw.and(DAILY_REPORT_ENTITY.USER_ID.in(
                    QueryWrapper.create()
                            .select(USER_INFO_ENTITY.ID)
                            .from(USER_INFO_ENTITY)
                            .where(USER_INFO_ENTITY.DINGTALK_DEPT_ID.eq(deptId))
            ));
        }

        // 开始日期筛选
        if (requestParams.containsKey("startDate") && requestParams.get("startDate") != null) {
            String startDate = requestParams.getStr("startDate");
            log.info("【管理端日报Controller】添加startDate筛选条件: {}", startDate);
            qw.and(DAILY_REPORT_ENTITY.REPORT_DATE.ge(LocalDate.parse(startDate)));
        }

        // 结束日期筛选
        if (requestParams.containsKey("endDate") && requestParams.get("endDate") != null) {
            String endDate = requestParams.getStr("endDate");
            log.info("【管理端日报Controller】添加endDate筛选条件: {}", endDate);
            qw.and(DAILY_REPORT_ENTITY.REPORT_DATE.le(LocalDate.parse(endDate)));
        }

        setPageOption(createOp()
                .keyWordLikeFields(DAILY_REPORT_ENTITY.USER_EDITED_CONTENT) // 关键词模糊搜索
                .fieldEq(DAILY_REPORT_ENTITY.STATUS) // 状态等值筛选
                .queryWrapper(qw)
        );
    }

    @Operation(summary = "获取组织AI建议", description = "基于时间范围聚合内容生成组织层面的建议")
    @GetMapping("/insight")
    public R getOrgInsight(
            @Parameter(description = "范围：week 或 month，默认 week") @RequestParam(required = false, defaultValue = "week") String scope,
            @Parameter(description = "开始日期 yyyy-MM-dd（周一或任意日）") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期 yyyy-MM-dd（可选，未传按scope推导）") @RequestParam(required = false) String endDate
    ) {
        try {
            LocalDate start;
            LocalDate end;
            if (startDate == null || startDate.isEmpty()) {
                start = LocalDate.now();
            } else {
                start = LocalDate.parse(startDate);
            }
            if ("month".equalsIgnoreCase(scope)) {
                // 月范围：按当月起止
                LocalDate first = start.withDayOfMonth(1);
                LocalDate last = (endDate != null && !endDate.isEmpty()) ? LocalDate.parse(endDate) : first.plusMonths(1).minusDays(1);
                start = first;
                end = last;
            } else {
                // 周范围：起始至起始+6
                end = (endDate != null && !endDate.isEmpty()) ? LocalDate.parse(endDate) : start.plusDays(6);
            }

            StringBuilder sb = new StringBuilder();

            // 1) 月度优先：基于月报聚合内容
            if ("month".equalsIgnoreCase(scope)) {
                String monthKey = start.getYear() + "-" + String.format("%02d", start.getMonthValue());
                QueryWrapper mq = QueryWrapper.create()
                    .eq(MonthlyReportEntity::getMonth, monthKey)
                    .eq(MonthlyReportEntity::getStatus, 1)
                    .orderBy(MonthlyReportEntity::getSubmitTime, true);

                var monthlyList = monthlyReportService.list(mq);
                for (MonthlyReportEntity r : monthlyList) {
                    String content = r.getUserEditedContent();
                    if (content == null || content.isBlank()) content = r.getAiFormattedContent();
                    if (content == null || content.isBlank()) content = r.getOriginalText();
                    if (content != null && !content.isBlank()) {
                        sb.append("- ")
                          .append(r.getMonth()).append(": ")
                          .append(content)
                          .append("\n");
                    }
                }

                // 若按 month 字段未命中，则退化为 submitTime 区间匹配
                if (sb.length() == 0) {
                    QueryWrapper mq2 = QueryWrapper.create()
                        .ge(MonthlyReportEntity::getSubmitTime, start.atStartOfDay())
                        .le(MonthlyReportEntity::getSubmitTime, end.atTime(23, 59, 59))
                        .eq(MonthlyReportEntity::getStatus, 1)
                        .orderBy(MonthlyReportEntity::getSubmitTime, true);

                    var monthlyList2 = monthlyReportService.list(mq2);
                    for (MonthlyReportEntity r : monthlyList2) {
                        String content = r.getUserEditedContent();
                        if (content == null || content.isBlank()) content = r.getAiFormattedContent();
                        if (content == null || content.isBlank()) content = r.getOriginalText();
                        if (content != null && !content.isBlank()) {
                            sb.append("- ")
                              .append(r.getMonth()).append(": ")
                              .append(content)
                              .append("\n");
                        }
                    }
                }
            }

            // 2) 若为空：聚合日报
            if (sb.length() == 0) {
                QueryWrapper qw = QueryWrapper.create()
                        .ge(DailyReportEntity::getReportDate, start)
                        .le(DailyReportEntity::getReportDate, end)
                        .eq(DailyReportEntity::getStatus, 1)
                        .orderBy(DailyReportEntity::getReportDate, true);

                List<DailyReportEntity> reports = this.service.list(qw);
                for (DailyReportEntity r : reports) {
                    String content = r.getUserEditedContent();
                    if (content == null || content.isBlank()) {
                        content = r.getAiFormattedContent();
                    }
                    if (content == null || content.isBlank()) {
                        content = r.getOriginalText();
                    }
                    if (content != null && !content.isBlank()) {
                        sb.append("- ")
                          .append(r.getReportDate()).append(": ")
                          .append(content)
                          .append("\n");
                    }
                }
            }

            // 3) 若仍为空，且为月度范围：回退基于周报的聚合
            if (sb.length() == 0 && "month".equalsIgnoreCase(scope)) {
                QueryWrapper wq = QueryWrapper.create()
                    .ge(WeeklyReportEntity::getWeekStartDate, start)
                    .le(WeeklyReportEntity::getWeekEndDate, end)
                    .eq(WeeklyReportEntity::getStatus, 1)
                    .orderBy(WeeklyReportEntity::getWeekStartDate, true);

                List<WeeklyReportEntity> weeklyList = weeklyReportService.list(wq);
                for (WeeklyReportEntity r : weeklyList) {
                    String content = r.getUserEditedContent();
                    if (content == null || content.isBlank()) content = r.getAiFormattedContent();
                    if (content == null || content.isBlank()) content = r.getOriginalText();
                    if (content != null && !content.isBlank()) {
                        sb.append("- ")
                          .append(r.getWeekStartDate()).append(" ~ ").append(r.getWeekEndDate()).append(": ")
                          .append(content)
                          .append("\n");
                    }
                }
            }

            // 若聚合内容为空，直接返回更友好的提示
            if (sb.length() == 0) {
                String msg = "month".equalsIgnoreCase(scope)
                    ? "未查询到该月份的月报数据，请核实后再尝试"
                    : "未查询到该周期的数据，请核实后再尝试";
                return R.error(msg);
            }

            String defaultKey = "month".equalsIgnoreCase(scope) ? "org_insight_monthly" : "org_insight_weekly";
            String paramKey = "month".equalsIgnoreCase(scope) ? "ai.insight.template.monthly" : "ai.insight.template.weekly";
            String configuredKey = baseSysParamService.dataByKey(paramKey);
            String templateKey = (configuredKey != null && !configuredKey.isBlank()) ? configuredKey : defaultKey;
            String insight = dailyReportAiService.generateAdvice(templateKey, sb.toString());

            JSONObject result = new JSONObject();
            result.set("scope", scope);
            result.set("startDate", start.toString());
            result.set("endDate", end.toString());
            result.set("insightText", insight);
            return R.ok(result);
        } catch (Exception e) {
            log.error("【管理端日报Controller】获取组织AI建议失败", e);
            return R.error("获取组织AI建议失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取统计信息", description = "获取日报提交统计信息")
    @GetMapping("/statistics")
    public R getStatistics(
            @Parameter(description = "开始日期 yyyy-MM-dd") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期 yyyy-MM-dd") @RequestParam(required = false) String endDate
    ) {
        log.info("【管理端日报Controller】获取统计信息, startDate: {}, endDate: {}", startDate, endDate);

        try {
            // 解析日期
            LocalDate start = startDate != null ? LocalDate.parse(startDate) : LocalDate.now().minusDays(7);
            LocalDate end = endDate != null ? LocalDate.parse(endDate) : LocalDate.now();

            // 获取统计信息
            Map<String, Object> statistics = this.service.getStatistics(start, end);

            log.info("【管理端日报Controller】统计信息获取成功: {}", statistics);
            return R.ok(statistics);

        } catch (Exception e) {
            log.error("【管理端日报Controller】获取统计信息失败", e);
            return R.error("获取统计信息失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取未提交人员列表", description = "获取指定日期未提交日报的人员列表")
    @GetMapping("/unsubmitted")
    public R getUnsubmittedUsers(
            @Parameter(description = "日报日期 yyyy-MM-dd") @RequestParam(required = false) String reportDate
    ) {
        log.info("【管理端日报Controller】获取未提交人员列表, reportDate: {}", reportDate);

        try {
            // 解析日期（默认今天）
            LocalDate date = reportDate != null ? LocalDate.parse(reportDate) : LocalDate.now();

            // 获取未提交的用户ID列表
            List<Long> unsubmittedUserIds = this.service.getUnsubmittedUserIds(date);

            // 查询用户详细信息
            List<UserInfoEntity> users = new ArrayList<>();
            if (!unsubmittedUserIds.isEmpty()) {
                QueryWrapper qw = QueryWrapper.create()
                        .where(USER_INFO_ENTITY.ID.in(unsubmittedUserIds));
                users = userInfoMapper.selectListByQuery(qw);
            }

            log.info("【管理端日报Controller】未提交人员数量: {}", users.size());

            Map<String, Object> result = new HashMap<>();
            result.put("date", date);
            result.put("unsubmittedCount", users.size());
            result.put("users", users);

            return R.ok(result);

        } catch (Exception e) {
            log.error("【管理端日报Controller】获取未提交人员列表失败", e);
            return R.error("获取未提交人员列表失败: " + e.getMessage());
        }
    }

    @Operation(summary = "按部门统计提交情况", description = "统计各部门的日报提交率")
    @GetMapping("/departmentStatistics")
    public R getDepartmentStatistics(
            @Parameter(description = "开始日期 yyyy-MM-dd") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期 yyyy-MM-dd") @RequestParam(required = false) String endDate
    ) {
        log.info("【管理端日报Controller】按部门统计提交情况, startDate: {}, endDate: {}", startDate, endDate);

        try {
            // 解析日期
            LocalDate start = startDate != null ? LocalDate.parse(startDate) : LocalDate.now().minusDays(7);
            LocalDate end = endDate != null ? LocalDate.parse(endDate) : LocalDate.now();

            // TODO: 实现按部门统计的详细逻辑
            // 这里需要查询每个部门的人数、提交数量等信息
            // 由于涉及复杂的统计查询，建议在Service层实现

            Map<String, Object> result = new HashMap<>();
            result.put("message", "功能开发中，待实现");
            result.put("startDate", start);
            result.put("endDate", end);

            return R.ok(result);

        } catch (Exception e) {
            log.error("【管理端日报Controller】按部门统计失败", e);
            return R.error("按部门统计失败: " + e.getMessage());
        }
    }

    @Operation(summary = "导出日报", description = "导出日报数据为Excel格式")
    @GetMapping("/export")
    public R export(
            @Parameter(description = "用户ID") @RequestParam(required = false) Long userId,
            @Parameter(description = "开始日期 yyyy-MM-dd") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期 yyyy-MM-dd") @RequestParam(required = false) String endDate,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status
    ) {
        log.info("【管理端日报Controller】导出日报, userId: {}, startDate: {}, endDate: {}, status: {}",
                userId, startDate, endDate, status);

        try {
            // TODO: 实现导出功能
            // 1. 根据条件查询日报数据
            // 2. 使用 EasyExcel 或 POI 生成 Excel 文件
            // 3. 返回文件下载响应

            Map<String, Object> result = new HashMap<>();
            result.put("message", "功能开发中，待实现");

            return R.ok(result);

        } catch (Exception e) {
            log.error("【管理端日报Controller】导出日报失败", e);
            return R.error("导出失败: " + e.getMessage());
        }
    }
}
