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

import cn.hutool.json.JSONObject;
import com.cool.core.base.BaseController;
import com.cool.core.request.R;
import com.cool.modules.monthlyreport.entity.MonthlyReportEntity;
import com.cool.modules.monthlyreport.service.MonthlyReportAiService;
import com.cool.modules.monthlyreport.service.MonthlyReportService;
import com.cool.modules.weeklyreport.entity.WeeklyReportEntity;
import com.cool.modules.weeklyreport.service.WeeklyReportService;
import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
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.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.Comparator;
import java.util.List;

/**
 * 用户端月报Controller
 */
@Slf4j
@Tag(name = "用户端月报管理", description = "用户端月报生成、提交与查询")
@RestController
@RequestMapping("/app/monthlyreport/report")
@RequiredArgsConstructor
public class AppMonthlyReportController extends BaseController<MonthlyReportService, MonthlyReportEntity> {

    private final MonthlyReportService monthlyReportService;
    private final MonthlyReportAiService monthlyReportAiService;
    private final WeeklyReportService weeklyReportService;

    @Override
    protected void init(HttpServletRequest request, JSONObject requestParams) {
        // APP侧暂不使用通用分页
    }

    @Operation(summary = "从本月已提交周报聚合并AI格式化")
    @PostMapping("/generateFromWeekly")
    public R generateFromWeekly(@RequestBody JSONObject data) {
        try {
            Long userId = data.getLong("userId");
            String month = data.getStr("month"); // yyyy-MM
            String templateKey = data.getStr("templateKey", "monthly_report_format");
            if (userId == null || month == null || month.isEmpty()) {
                return R.error("userId与month不能为空");
            }

            YearMonth ym = YearMonth.parse(month);
            LocalDate start = ym.atDay(1);
            LocalDate end = ym.atEndOfMonth();

            QueryWrapper qw = QueryWrapper.create()
                .eq(WeeklyReportEntity::getUserId, userId)
                .ge(WeeklyReportEntity::getWeekStartDate, start)
                .le(WeeklyReportEntity::getWeekEndDate, end)
                .eq(WeeklyReportEntity::getStatus, 1);

            List<WeeklyReportEntity> weeklies = weeklyReportService.list(qw);
            if (weeklies == null || weeklies.isEmpty()) {
                return R.error("本月没有已提交的周报");
            }

            weeklies.sort(Comparator.comparing(WeeklyReportEntity::getWeekStartDate));

            StringBuilder source = new StringBuilder();
            for (WeeklyReportEntity r : weeklies) {
                String content = r.getUserEditedContent();
                if (content == null || content.isEmpty()) {
                    content = r.getAiFormattedContent();
                }
                if (content == null || content.isEmpty()) {
                    content = r.getOriginalText();
                }
                if (content != null && !content.isEmpty()) {
                    source.append("# ")
                          .append(r.getWeekStartDate()).append(" ~ ").append(r.getWeekEndDate())
                          .append("\n")
                          .append(content)
                          .append("\n\n");
                }
            }

            if (source.length() == 0) {
                return R.error("本月周报内容为空，无法生成月报");
            }

            String formatted = monthlyReportAiService.formatMonthlyReport(
                source.toString(), templateKey, month
            );

            JSONObject result = new JSONObject();
            result.set("formattedContent", formatted);
            result.set("length", formatted != null ? formatted.length() : 0);
            result.set("sourceCount", weeklies.size());
            result.set("sourceContent", source.toString());
            return R.ok(result);
        } catch (Exception e) {
            log.error("【月报自动生成】失败", e);
            return R.error("月报自动生成失败: " + e.getMessage());
        }
    }

    @Operation(summary = "AI格式化月报")
    @PostMapping("/aiFormat")
    public R aiFormat(@RequestBody JSONObject data) {
        try {
            String originalText = data.getStr("originalText");
            String templateKey = data.getStr("templateKey", "monthly_report_format");
            String month = data.getStr("month");
            String formattedContent = monthlyReportAiService.formatMonthlyReport(originalText, templateKey, month);
            JSONObject result = new JSONObject();
            result.set("formattedContent", formattedContent);
            result.set("length", formattedContent != null ? formattedContent.length() : 0);
            return R.ok(result);
        } catch (Exception e) {
            log.error("【月报AI格式化】失败", e);
            return R.error("AI格式化失败: " + e.getMessage());
        }
    }

    @Operation(summary = "保存草稿")
    @PostMapping("/saveDraft")
    public R saveDraft(@RequestBody JSONObject data) {
        try {
            Long userId = data.getLong("userId");
            String month = data.getStr("month");
            if (userId == null || month == null || month.isEmpty()) {
                return R.error("userId与month不能为空");
            }

            QueryWrapper qw = QueryWrapper.create()
                .eq(MonthlyReportEntity::getUserId, userId)
                .eq(MonthlyReportEntity::getMonth, month);
            MonthlyReportEntity existing = monthlyReportService.getOne(qw);

            if (existing == null) {
                existing = new MonthlyReportEntity();
                existing.setUserId(userId);
                existing.setMonth(month);
            }

            existing.setOriginalText(data.getStr("originalText"));
            existing.setAiFormattedContent(data.getStr("aiFormattedContent"));
            existing.setUserEditedContent(data.getStr("userEditedContent"));
            existing.setInputType(data.getInt("inputType", 0));
            existing.setStatus(0);

            if (existing.getId() == null) {
                monthlyReportService.save(existing);
            } else {
                monthlyReportService.updateById(existing);
            }
            return R.ok(existing);
        } catch (Exception e) {
            log.error("【月报草稿】保存失败", e);
            return R.error("保存失败: " + e.getMessage());
        }
    }

    @Operation(summary = "提交月报")
    @PostMapping("/submit")
    public R submit(@RequestBody JSONObject data) {
        try {
            Long userId = data.getLong("userId");
            String month = data.getStr("month");
            if (userId == null || month == null || month.isEmpty()) {
                return R.error("userId与month不能为空");
            }

            QueryWrapper qw = QueryWrapper.create()
                .eq(MonthlyReportEntity::getUserId, userId)
                .eq(MonthlyReportEntity::getMonth, month);
            MonthlyReportEntity report = monthlyReportService.getOne(qw);
            if (report == null) {
                report = new MonthlyReportEntity();
                report.setUserId(userId);
                report.setMonth(month);
            }
            report.setOriginalText(data.getStr("originalText"));
            report.setAiFormattedContent(data.getStr("aiFormattedContent"));
            report.setUserEditedContent(data.getStr("userEditedContent"));
            report.setInputType(data.getInt("inputType", 0));
            report.setStatus(1);
            report.setSubmitTime(LocalDateTime.now());

            if (report.getId() == null) {
                monthlyReportService.save(report);
            } else {
                monthlyReportService.updateById(report);
            }
            return R.ok(report);
        } catch (Exception e) {
            log.error("【月报提交】失败", e);
            return R.error("提交失败: " + e.getMessage());
        }
    }

    @Operation(summary = "月报详情")
    @GetMapping("/detail")
    public R detail(@RequestParam Long id, @RequestParam(required = false) Long userId) {
        try {
            MonthlyReportEntity report = monthlyReportService.getById(id);
            return R.ok(report);
        } catch (Exception e) {
            log.error("【月报详情】失败", e);
            return R.error("获取详情失败: " + e.getMessage());
        }
    }

    @Operation(summary = "我的月报列表")
    @GetMapping("/myReports")
    public R myReports(
        @RequestParam Long userId,
        @RequestParam(required = false) Integer status,
        @RequestParam(required = false, defaultValue = "1") Integer page,
        @RequestParam(required = false, defaultValue = "20") Integer size
    ) {
        try {
            QueryWrapper qw = QueryWrapper.create()
                .eq(MonthlyReportEntity::getUserId, userId)
                .orderBy(MonthlyReportEntity::getMonth, false)
                .orderBy(MonthlyReportEntity::getCreateTime, false);
            if (status != null) {
                qw.eq(MonthlyReportEntity::getStatus, status);
            }

            // 简单分页：偏移量分页
            int offset = (Math.max(page, 1) - 1) * Math.max(size, 1);
            qw.limit(offset, Math.max(size, 1));
            List<MonthlyReportEntity> list = monthlyReportService.list(qw);
            return R.ok(list);
        } catch (Exception e) {
            log.error("【我的月报列表】失败", e);
            return R.error("加载失败: " + e.getMessage());
        }
    }
}

