package com.cool.modules.useradvice.controller.app;

import cn.hutool.json.JSONObject;
import com.cool.core.request.R;
import com.cool.modules.dailyreport.entity.DailyReportEntity;
import com.cool.modules.dailyreport.service.DailyReportAiService;
import com.cool.modules.dailyreport.service.DailyReportService;
import com.cool.modules.monthlyreport.entity.MonthlyReportEntity;
import com.cool.modules.monthlyreport.service.MonthlyReportService;
import com.cool.modules.weeklyreport.entity.WeeklyReportEntity;
import com.cool.modules.weeklyreport.service.WeeklyReportService;
import com.cool.modules.base.service.sys.BaseSysParamService;
import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.time.LocalDate;
import java.time.YearMonth;
import java.util.Comparator;
import java.util.List;

/**
 * 用户端工作建议（周/月）
 */
@Slf4j
@Tag(name = "用户端工作建议", description = "基于周/月聚合内容生成个人建议")
@RestController
@RequestMapping("/app/useradvice")
@RequiredArgsConstructor
public class AppUserAdviceController {

    private final WeeklyReportService weeklyReportService;
    private final MonthlyReportService monthlyReportService;
    private final DailyReportService dailyReportService;
    private final DailyReportAiService dailyReportAiService;
    private final BaseSysParamService baseSysParamService;

    @Operation(summary = "获取个人工作建议")
    @GetMapping("/advice")
    public R getAdvice(
            @RequestParam Long userId,
            @RequestParam String scope, // week | month
            @RequestParam String startDate // 支持 yyyy-MM 或 yyyy-MM-dd（本地时区）
    ) {
        try {
            String content = null;
            LocalDate start;
            LocalDate end;

            if ("week".equalsIgnoreCase(scope)) {
                // 周：要求 yyyy-MM-dd；若传 yyyy-MM 则当作该月第一天
                if (startDate != null && startDate.matches("^\\d{4}-\\d{2}$")) {
                    YearMonth ym = YearMonth.parse(startDate);
                    start = ym.atDay(1);
                } else {
                    start = LocalDate.parse(startDate);
                }
                end = start.plusDays(6);

                // 优先：当周已提交周报
                QueryWrapper wq = QueryWrapper.create()
                        .eq(WeeklyReportEntity::getUserId, userId)
                        .eq(WeeklyReportEntity::getWeekStartDate, start)
                        .eq(WeeklyReportEntity::getWeekEndDate, end)
                        .eq(WeeklyReportEntity::getStatus, 1);
                WeeklyReportEntity weekly = weeklyReportService.getOne(wq);
                if (weekly != null) {
                    content = pickContent(weekly.getUserEditedContent(), weekly.getAiFormattedContent(), weekly.getOriginalText());
                }

                // 回退：当周已提交日报聚合
                if (isBlank(content)) {
                    List<DailyReportEntity> list = dailyReportService.getUserReports(userId, start, end, 1);
                    StringBuilder sb = new StringBuilder();
                    list.stream()
                            .sorted(Comparator.comparing(DailyReportEntity::getReportDate))
                            .forEach(r -> {
                                String c = pickContent(r.getUserEditedContent(), r.getAiFormattedContent(), r.getOriginalText());
                                if (!isBlank(c)) {
                                    sb.append("- ").append(r.getReportDate()).append(": ")
                                            .append(c).append("\n");
                                }
                            });
                    content = sb.toString();
                }
            } else {
                // month：支持 yyyy-MM 或 yyyy-MM-dd
                YearMonth ym;
                if (startDate != null && startDate.matches("^\\d{4}-\\d{2}$")) {
                    ym = YearMonth.parse(startDate);
                } else {
                    start = LocalDate.parse(startDate);
                    ym = YearMonth.from(start);
                }
                LocalDate first = ym.atDay(1);
                LocalDate last = ym.atEndOfMonth();
                start = first;
                end = last;

                // 优先：当月已提交月报
                QueryWrapper mq = QueryWrapper.create()
                        .eq(MonthlyReportEntity::getUserId, userId)
                        .eq(MonthlyReportEntity::getMonth, ym.toString())
                        .eq(MonthlyReportEntity::getStatus, 1);
                MonthlyReportEntity monthly = monthlyReportService.getOne(mq);
                if (monthly != null) {
                    content = pickContent(monthly.getUserEditedContent(), monthly.getAiFormattedContent(), monthly.getOriginalText());
                }

                // 回退1：当月范围内的已提交周报聚合
                if (isBlank(content)) {
                    QueryWrapper wq = QueryWrapper.create()
                            .eq(WeeklyReportEntity::getUserId, userId)
                            .ge(WeeklyReportEntity::getWeekStartDate, first)
                            .le(WeeklyReportEntity::getWeekEndDate, last)
                            .eq(WeeklyReportEntity::getStatus, 1);
                    List<WeeklyReportEntity> weeks = weeklyReportService.list(wq);
                    StringBuilder sb = new StringBuilder();
                    weeks.stream()
                            .sorted(Comparator.comparing(WeeklyReportEntity::getWeekStartDate))
                            .forEach(r -> {
                                String c = pickContent(r.getUserEditedContent(), r.getAiFormattedContent(), r.getOriginalText());
                                if (!isBlank(c)) {
                                    sb.append("- ").append(r.getWeekStartDate()).append(" ~ ")
                                            .append(r.getWeekEndDate()).append(": ")
                                            .append(c).append("\n");
                                }
                            });
                    content = sb.toString();
                }

                // 回退2：当月范围内的已提交日报聚合
                if (isBlank(content)) {
                    List<DailyReportEntity> list = dailyReportService.getUserReports(userId, first, last, 1);
                    StringBuilder sb = new StringBuilder();
                    list.stream()
                            .sorted(Comparator.comparing(DailyReportEntity::getReportDate))
                            .forEach(r -> {
                                String c = pickContent(r.getUserEditedContent(), r.getAiFormattedContent(), r.getOriginalText());
                                if (!isBlank(c)) {
                                    sb.append("- ").append(r.getReportDate()).append(": ")
                                            .append(c).append("\n");
                                }
                            });
                    content = sb.toString();
                }
            }

            if (isBlank(content)) {
                String msg = "week".equalsIgnoreCase(scope)
                        ? "未查询到该周的可用内容，请核实后再尝试"
                        : "未查询到该月份的月报/周报/日报内容，请核实后再尝试";
                return R.error(msg);
            }

            String paramKey = "week".equalsIgnoreCase(scope)
                    ? "ai.user.advice.weekly" : "ai.user.advice.monthly";
            String defaultKey = "week".equalsIgnoreCase(scope)
                    ? "user_advice_weekly" : "user_advice_monthly";
            String configuredKey = baseSysParamService.dataByKey(paramKey);
            String templateKey = (configuredKey != null && !configuredKey.isBlank()) ? configuredKey : defaultKey;

            String advice = dailyReportAiService.generateAdvice(templateKey, content);

            JSONObject result = new JSONObject();
            result.set("scope", scope);
            result.set("startDate", start.toString());
            result.set("endDate", end.toString());
            result.set("adviceText", advice);
            return R.ok(result);
        } catch (Exception e) {
            log.error("【用户端个人建议】生成失败", e);
            return R.error("生成失败: " + e.getMessage());
        }
    }

    private static boolean isBlank(String s) {
        return s == null || s.trim().isEmpty();
    }

    private static String pickContent(String edited, String ai, String original) {
        if (!isBlank(edited)) return edited;
        if (!isBlank(ai)) return ai;
        return original;
    }
}
