package com.cool.modules.monthlyreport.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.monthlyreport.entity.MonthlyReportEntity;
import com.cool.modules.monthlyreport.service.MonthlyReportService;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import static com.cool.modules.monthlyreport.entity.table.MonthlyReportEntityTableDef.MONTHLY_REPORT_ENTITY;

/**
 * 管理端月报Controller
 */
@Slf4j
@Tag(name = "管理端月报管理", description = "管理端月报查询与统计")
@CoolRestController(api = {"page", "list", "info"})
@RequiredArgsConstructor
public class AdminMonthlyReportController extends BaseController<MonthlyReportService, MonthlyReportEntity> {

    private final MonthlyReportService monthlyReportService;

    @Override
    protected void init(HttpServletRequest request, JSONObject requestParams) {
        QueryWrapper qw = QueryWrapper.create()
            .orderBy(MONTHLY_REPORT_ENTITY.MONTH, false)
            .orderBy(MONTHLY_REPORT_ENTITY.CREATE_TIME, false);

        // 月份范围筛选（startMonth、endMonth，格式 yyyy-MM）
        if (requestParams != null) {
            String startMonth = requestParams.getStr("startMonth");
            String endMonth = requestParams.getStr("endMonth");
            if (startMonth != null && !startMonth.isEmpty()) {
                qw.ge(MonthlyReportEntity::getMonth, startMonth);
            }
            if (endMonth != null && !endMonth.isEmpty()) {
                qw.le(MonthlyReportEntity::getMonth, endMonth);
            }
        }

        setPageOption(createOp()
            .keyWordLikeFields(MONTHLY_REPORT_ENTITY.USER_EDITED_CONTENT)
            .fieldEq(MONTHLY_REPORT_ENTITY.STATUS)
            .queryWrapper(qw)
        );
    }

    @Operation(summary = "获取月报提交统计")
    @GetMapping("/statistics")
    public R getStatistics(
        @RequestParam(required = false) String startMonth,
        @RequestParam(required = false) String endMonth
    ) {
        try {
            QueryWrapper qw = QueryWrapper.create();
            if (startMonth != null && !startMonth.isEmpty()) {
                qw.ge(MonthlyReportEntity::getMonth, startMonth);
            }
            if (endMonth != null && !endMonth.isEmpty()) {
                qw.le(MonthlyReportEntity::getMonth, endMonth);
            }

            long totalCount = monthlyReportService.count(qw);
            long submitted = monthlyReportService.count(qw.clone().eq(MonthlyReportEntity::getStatus, 1));
            long draft = monthlyReportService.count(qw.clone().eq(MonthlyReportEntity::getStatus, 0));

            JSONObject result = new JSONObject();
            result.set("totalCount", totalCount);
            result.set("submittedCount", submitted);
            result.set("draftCount", draft);
            return R.ok(result);
        } catch (Exception e) {
            log.error("【月报统计】失败", e);
            return R.error("统计失败: " + e.getMessage());
        }
    }
}
