package com.cool.modules.weeklyreport.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.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.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.cool.modules.weeklyreport.entity.table.WeeklyReportEntityTableDef.WEEKLY_REPORT_ENTITY;
import com.cool.modules.user.entity.UserInfoEntity;
import com.cool.modules.user.mapper.UserInfoMapper;

/**
 * 管理端周报Controller
 */
@Slf4j
@Tag(name = "管理端周报管理", description = "管理端周报查询、统计等功能")
@CoolRestController(api = {"page", "list", "info"})
@RequiredArgsConstructor
public class AdminWeeklyReportController extends BaseController<WeeklyReportService, WeeklyReportEntity> {

    private final WeeklyReportService weeklyReportService;
    private final UserInfoMapper userInfoMapper;

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

        setPageOption(createOp()
            .keyWordLikeFields(WEEKLY_REPORT_ENTITY.USER_EDITED_CONTENT)
            .fieldEq(WEEKLY_REPORT_ENTITY.STATUS)
            // 移除默认的 USER_ID 精确筛选，避免未传参时隐式约束导致列表为空
            .queryWrapper(qw)
        );
    }

    @Operation(summary = "获取周报提交统计")
    @GetMapping("/statistics")
    public R getStatistics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {

        log.info("【周报统计】开始统计周报提交情况, startDate={}, endDate={}", startDate, endDate);

        try {
            QueryWrapper qw = QueryWrapper.create();

            // 添加时间范围筛选
            if (startDate != null && !startDate.isEmpty()) {
                qw.ge(WeeklyReportEntity::getWeekStartDate, LocalDate.parse(startDate));
            }
            if (endDate != null && !endDate.isEmpty()) {
                qw.le(WeeklyReportEntity::getWeekEndDate, LocalDate.parse(endDate));
            }

            // 总提交数
            long totalCount = weeklyReportService.count(qw);

            // 已提交数
            QueryWrapper submittedQw = qw.clone().eq(WeeklyReportEntity::getStatus, 1);
            long submittedCount = weeklyReportService.count(submittedQw);

            // 草稿数
            QueryWrapper draftQw = qw.clone().eq(WeeklyReportEntity::getStatus, 0);
            long draftCount = weeklyReportService.count(draftQw);

            JSONObject result = new JSONObject();
            result.set("totalCount", totalCount);
            result.set("submittedCount", submittedCount);
            result.set("draftCount", draftCount);

            log.info("【周报统计】统计成功, 总数={}, 已提交={}, 草稿={}",
                totalCount, submittedCount, draftCount);

            return R.ok(result);
        } catch (Exception e) {
            log.error("【周报统计】统计失败", e);
            return R.error("统计失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取未提交周报的人员列表", description = "根据周起始日统计未提交周报的人员")
    @GetMapping("/unsubmitted")
    public R getUnsubmittedUsers(@RequestParam(required = false) String weekStart) {
        try {
            LocalDate start;
            if (weekStart == null || weekStart.isEmpty()) {
                LocalDate today = LocalDate.now();
                start = today.minusDays((today.getDayOfWeek().getValue() + 6) % 7);
            } else {
                start = LocalDate.parse(weekStart);
            }
            LocalDate end = start.plusDays(6);

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

            List<WeeklyReportEntity> submitted = weeklyReportService.list(submittedQw);
            Set<Long> submittedUserIds = submitted.stream()
                .map(WeeklyReportEntity::getUserId)
                .filter(id -> id != null)
                .collect(Collectors.toSet());

            List<UserInfoEntity> allUsers = userInfoMapper.selectListByQuery(QueryWrapper.create());
            List<UserInfoEntity> unsubmittedUsers = allUsers.stream()
                .filter(u -> u.getId() != null && !submittedUserIds.contains(u.getId()))
                .collect(Collectors.toList());

            Map<String, Object> result = new HashMap<>();
            result.put("weekStart", start);
            result.put("weekEnd", end);
            result.put("unsubmittedCount", unsubmittedUsers.size());
            result.put("users", unsubmittedUsers);

            return R.ok(result);
        } catch (Exception e) {
            log.error("【周报统计】获取未提交周报人员失败", e);
            return R.error("获取未提交人员失败: " + e.getMessage());
        }
    }

    @Operation(summary = "导出周报（TODO）")
    @GetMapping("/export")
    public R export() {
        log.info("【周报导出】导出功能待实现");
        // TODO: 实现导出功能
        return R.error("导出功能待实现");
    }
}
