package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.LbDailyUserTrade;
import com.rj.entity.LbDailyUserTradeReport;
import com.rj.service.ILbDailyUserTradeReportService;
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.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 当天用户交易报表 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/api/lbDailyUserTradeReport")
@Tag(name = "当天用户交易报表", description = "当天用户交易报表相关接口")
public class LbDailyUserTradeReportController {

    @Autowired
    private ILbDailyUserTradeReportService lbDailyUserTradeReportService;

    @PostMapping("/add")
    @Operation(summary = "新增报表记录", description = "新增当天用户交易报表记录")
    public ResponseEntity<Map<String, Object>> add(@RequestBody LbDailyUserTradeReport tradeReport) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (tradeReport.getId() == null || tradeReport.getId().trim().isEmpty()) {
                tradeReport.setId(UUID.randomUUID().toString());
            }
            if (tradeReport.getYestodayBuyAmt() == null) {
                tradeReport.setYestodayBuyAmt(BigDecimal.ZERO);
            }
            if (tradeReport.getDailySellAmt() == null) {
                tradeReport.setDailySellAmt(BigDecimal.ZERO);
            }
            if (tradeReport.getDailyBuyAmt() == null) {
                tradeReport.setDailyBuyAmt(BigDecimal.ZERO);
            }
            if (tradeReport.getServiceAmt() == null) {
                tradeReport.setServiceAmt(BigDecimal.ZERO);
            }
            if (tradeReport.getDikouAmt() == null) {
                tradeReport.setDikouAmt(BigDecimal.ZERO);
            }
            if (tradeReport.getDiffAmt() == null) {
                tradeReport.setDiffAmt(BigDecimal.ZERO);
            }
            tradeReport.setActualReceiptsPayments(tradeReport.getDiffAmt().subtract(tradeReport.getServiceAmt()));
            if (tradeReport.getReportDate() == null) {
                tradeReport.setReportDate(LocalDateTime.now());
            }
            tradeReport.setCreatedAt(LocalDateTime.now());
            tradeReport.setUpdatedAt(LocalDateTime.now());

            boolean success = lbDailyUserTradeReportService.save(tradeReport);
            if (success) {
                result.put("success", true);
                result.put("message", "新增成功");
                result.put("data", tradeReport);
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "新增失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "新增异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询", description = "根据ID查询当天用户交易报表记录")
    public ResponseEntity<Map<String, Object>> getById(
            @Parameter(description = "主键ID", required = true) @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            LbDailyUserTradeReport data = lbDailyUserTradeReportService.getById(id);
            if (data == null) {
                result.put("success", false);
                result.put("message", "记录不存在");
                return ResponseEntity.badRequest().body(result);
            }
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", data);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/list")
    @Operation(summary = "分页条件查询", description = "分页查询当天用户交易报表记录")
    public ResponseEntity<Map<String, Object>> list(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "用户ID") @RequestParam(required = false) String userId,
            @Parameter(description = "数据类型") @RequestParam(required = false) String dataType,
            @Parameter(description = "昵称（模糊查询）") @RequestParam(required = false) String nickname,
            @Parameter(description = "报表开始时间，格式：yyyy-MM-dd HH:mm:ss")
            @RequestParam(required = false) String reportStartTime,
            @Parameter(description = "报表结束时间，格式：yyyy-MM-dd HH:mm:ss")
            @RequestParam(required = false) String reportEndTime,
            @Parameter(description = "创建开始时间，格式：yyyy-MM-dd HH:mm:ss")
            @RequestParam(required = false) String createdStartTime,
            @Parameter(description = "创建结束时间，格式：yyyy-MM-dd HH:mm:ss")
            @RequestParam(required = false) String createdEndTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<LbDailyUserTradeReport> queryWrapper = new LambdaQueryWrapper<>();
            if (tenantId != null && !tenantId.trim().isEmpty()) {
                queryWrapper.eq(LbDailyUserTradeReport::getTenantId, tenantId.trim());
            }
            if (userId != null && !userId.trim().isEmpty()) {
                queryWrapper.eq(LbDailyUserTradeReport::getUserId, userId.trim());
            }
            if (dataType != null && !dataType.trim().isEmpty()) {
                queryWrapper.eq(LbDailyUserTradeReport::getDataType, dataType.trim());
            }
            if (nickname != null && !nickname.trim().isEmpty()) {
                queryWrapper.like(LbDailyUserTradeReport::getNickname, nickname.trim());
            }

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (reportStartTime != null && !reportStartTime.trim().isEmpty()) {
                try {
                    queryWrapper.ge(LbDailyUserTradeReport::getReportDate, LocalDateTime.parse(reportStartTime.trim(), formatter));
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "报表开始时间格式错误，请使用 yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            if (reportEndTime != null && !reportEndTime.trim().isEmpty()) {
                try {
                    queryWrapper.le(LbDailyUserTradeReport::getReportDate, LocalDateTime.parse(reportEndTime.trim(), formatter));
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "报表结束时间格式错误，请使用 yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            if (createdStartTime != null && !createdStartTime.trim().isEmpty()) {
                try {
                    queryWrapper.ge(LbDailyUserTradeReport::getCreatedAt, LocalDateTime.parse(createdStartTime.trim(), formatter));
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "创建开始时间格式错误，请使用 yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            if (createdEndTime != null && !createdEndTime.trim().isEmpty()) {
                try {
                    queryWrapper.le(LbDailyUserTradeReport::getCreatedAt, LocalDateTime.parse(createdEndTime.trim(), formatter));
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "创建结束时间格式错误，请使用 yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }

            queryWrapper.orderByDesc(LbDailyUserTradeReport::getDiffAmt)
                    .orderByDesc(LbDailyUserTradeReport::getCreatedAt);
            Page<LbDailyUserTradeReport> page = lbDailyUserTradeReportService.page(new Page<>(current, size), queryWrapper);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", page.getRecords());
            result.put("total", page.getTotal());
            result.put("current", page.getCurrent());
            result.put("size", page.getSize());
            result.put("pages", page.getPages());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/list/daily-user-trade/by-user-id-and-date-range")
    @Operation(summary = "按用户ID和日期范围分页查询交易明细", description = "根据开始日期、结束日期和用户ID，从lb_daily_user_trade分页查询交易数据")
    public ResponseEntity<Map<String, Object>> listDailyUserTradeByUserIdAndDateRange(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "开始日期，格式：yyyy-MM-dd", required = true) @RequestParam String startDate,
            @Parameter(description = "结束日期，格式：yyyy-MM-dd", required = true) @RequestParam String endDate,
            @Parameter(description = "用户ID", required = true) @RequestParam String userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (userId == null || userId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "userId不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            if (startDate == null || startDate.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "startDate不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            if (endDate == null || endDate.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "endDate不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            LocalDate parsedStartDate;
            LocalDate parsedEndDate;
            try {
                parsedStartDate = LocalDate.parse(startDate.trim());
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "startDate格式错误，请使用 yyyy-MM-dd");
                return ResponseEntity.badRequest().body(result);
            }
            try {
                parsedEndDate = LocalDate.parse(endDate.trim());
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "endDate格式错误，请使用 yyyy-MM-dd");
                return ResponseEntity.badRequest().body(result);
            }
            if (parsedEndDate.isBefore(parsedStartDate)) {
                result.put("success", false);
                result.put("message", "endDate不能早于startDate");
                return ResponseEntity.badRequest().body(result);
            }

            Page<LbDailyUserTrade> page = lbDailyUserTradeReportService.pageDailyUserTradeByUserIdAndDateRange(
                    parsedStartDate, parsedEndDate, userId.trim(), current, size);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", page.getRecords());
            result.put("total", page.getTotal());
            result.put("current", page.getCurrent());
            result.put("size", page.getSize());
            result.put("pages", page.getPages());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/list/daily-user-trade/by-parent-id-of-user-and-date-range")
    @Operation(summary = "按用户ID和日期范围分页查询父节点的交易明细",
            description = "根据用户ID查询lb_department_user的parent_id，再按user_id=parent_id从lb_daily_user_trade分页查询指定日期范围交易数据")
    public ResponseEntity<Map<String, Object>> listDailyUserTradeByParentIdOfUserAndDateRange(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "开始日期，格式：yyyy-MM-dd", required = true) @RequestParam String startDate,
            @Parameter(description = "结束日期，格式：yyyy-MM-dd", required = true) @RequestParam String endDate,
            @Parameter(description = "用户ID", required = true) @RequestParam String userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (userId == null || userId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "userId不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            if (startDate == null || startDate.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "startDate不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            if (endDate == null || endDate.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "endDate不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            LocalDate parsedStartDate;
            LocalDate parsedEndDate;
            try {
                parsedStartDate = LocalDate.parse(startDate.trim());
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "startDate格式错误，请使用 yyyy-MM-dd");
                return ResponseEntity.badRequest().body(result);
            }
            try {
                parsedEndDate = LocalDate.parse(endDate.trim());
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "endDate格式错误，请使用 yyyy-MM-dd");
                return ResponseEntity.badRequest().body(result);
            }
            if (parsedEndDate.isBefore(parsedStartDate)) {
                result.put("success", false);
                result.put("message", "endDate不能早于startDate");
                return ResponseEntity.badRequest().body(result);
            }

            Page<LbDailyUserTrade> page = lbDailyUserTradeReportService.pageDailyUserTradeByParentIdOfUserAndDateRange(
                    parsedStartDate, parsedEndDate, userId.trim(), current, size);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", page.getRecords());
            result.put("total", page.getTotal());
            result.put("current", page.getCurrent());
            result.put("size", page.getSize());
            result.put("pages", page.getPages());
            return ResponseEntity.ok(result);
        } catch (IllegalArgumentException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @PutMapping("/update")
    @Operation(summary = "修改报表记录", description = "根据ID修改当天用户交易报表记录")
    public ResponseEntity<Map<String, Object>> update(@RequestBody LbDailyUserTradeReport tradeReport) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (tradeReport.getId() == null || tradeReport.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            tradeReport.setUpdatedAt(LocalDateTime.now());
            boolean success = lbDailyUserTradeReportService.updateById(tradeReport);
            if (success) {
                result.put("success", true);
                result.put("message", "修改成功");
                result.put("data", tradeReport);
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "修改失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "修改异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除报表记录", description = "根据ID删除当天用户交易报表记录")
    public ResponseEntity<Map<String, Object>> delete(
            @Parameter(description = "主键ID", required = true) @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = lbDailyUserTradeReportService.removeById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "删除成功");
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "删除失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @DeleteMapping("/delete/by-date-and-tenant")
    @Operation(summary = "按日期和租户删除报表", description = "根据报表日期和租户ID删除当天用户交易报表记录")
    public ResponseEntity<Map<String, Object>> deleteByDateAndTenant(
            @Parameter(description = "报表日期，格式：yyyy-MM-dd", required = true)
            @RequestParam String reportDate,
            @Parameter(description = "租户ID", required = true)
            @RequestParam String tenantId) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (tenantId == null || tenantId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "tenantId不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            if (reportDate == null || reportDate.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "reportDate不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            LocalDate parsedReportDate;
            try {
                parsedReportDate = LocalDate.parse(reportDate.trim());
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "报表日期格式错误，请使用 yyyy-MM-dd");
                return ResponseEntity.badRequest().body(result);
            }

            LocalDateTime start = parsedReportDate.atStartOfDay();
            LocalDateTime end = parsedReportDate.plusDays(1).atStartOfDay();

            LambdaQueryWrapper<LbDailyUserTradeReport> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LbDailyUserTradeReport::getTenantId, tenantId.trim())
                    .ge(LbDailyUserTradeReport::getReportDate, start)
                    .lt(LbDailyUserTradeReport::getReportDate, end);

            long deleteCount = lbDailyUserTradeReportService.count(queryWrapper);
            if (deleteCount == 0) {
                result.put("success", true);
                result.put("message", "未匹配到可删除记录");
                result.put("deleteCount", 0);
                return ResponseEntity.ok(result);
            }

            boolean success = lbDailyUserTradeReportService.remove(queryWrapper);
            if (success) {
                result.put("success", true);
                result.put("message", "删除成功");
                result.put("deleteCount", deleteCount);
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "删除失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/list/yestoday-buy-positive-and-daily-sell-zero")
    @Operation(summary = "按日期范围查询昨日买入大于0且当日卖出为0的报表", description = "根据开始日期、结束日期和租户ID查询 reportDate 范围内 yestodayBuyAmt > 0 且 dailySellAmt = 0 的记录")
    public ResponseEntity<Map<String, Object>> listByDateRangeWithBuyPositiveAndSellZero(
            @Parameter(description = "开始日期，格式：yyyy-MM-dd", required = true)
            @RequestParam String startDate,
            @Parameter(description = "结束日期，格式：yyyy-MM-dd", required = true)
            @RequestParam String endDate,
            @Parameter(description = "租户ID", required = true)
            @RequestParam String tenantId) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (tenantId == null || tenantId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "tenantId不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            if (startDate == null || startDate.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "startDate不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            if (endDate == null || endDate.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "endDate不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            LocalDate parsedStartDate;
            LocalDate parsedEndDate;
            try {
                parsedStartDate = LocalDate.parse(startDate.trim());
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "startDate格式错误，请使用 yyyy-MM-dd");
                return ResponseEntity.badRequest().body(result);
            }
            try {
                parsedEndDate = LocalDate.parse(endDate.trim());
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "endDate格式错误，请使用 yyyy-MM-dd");
                return ResponseEntity.badRequest().body(result);
            }

            if (parsedEndDate.isBefore(parsedStartDate)) {
                result.put("success", false);
                result.put("message", "endDate不能早于startDate");
                return ResponseEntity.badRequest().body(result);
            }

            LocalDateTime start = parsedStartDate.atStartOfDay();
            LocalDateTime end = parsedEndDate.atTime(23, 59, 59);

            LambdaQueryWrapper<LbDailyUserTradeReport> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LbDailyUserTradeReport::getTenantId, tenantId.trim())
                    .ge(LbDailyUserTradeReport::getReportDate, start)
                    .le(LbDailyUserTradeReport::getReportDate, end)
                    .gt(LbDailyUserTradeReport::getYestodayBuyAmt, BigDecimal.ZERO)
                    .eq(LbDailyUserTradeReport::getDailySellAmt, BigDecimal.ZERO)
                    .orderByDesc(LbDailyUserTradeReport::getReportDate)
                    .orderByDesc(LbDailyUserTradeReport::getCreatedAt);

            List<LbDailyUserTradeReport> rows = lbDailyUserTradeReportService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", rows);
            result.put("total", rows.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/stats/user-trade-with-team/by-date-range-and-tenant")
    @Operation(summary = "按日期范围统计本人及递归下级交易金额", description = "先查 lb_daily_user_trade_report（日期+租户，排除 report_sum）圈定 user_id；再查 lb_department_user（同租户）用 parent_id（父 user_id）建上下级；对 yestoday_buy_amt、daily_sell_amt、daily_buy_amt、diff_amt 分别汇总 own*/team*/total*（team 为递归下级、不含本人）。仅返回报表范围内有数据的用户。")
    public ResponseEntity<Map<String, Object>> statsUserTradeWithTeamByDateRangeAndTenant(
            @Parameter(description = "开始日期，格式：yyyy-MM-dd", required = true)
            @RequestParam String startDate,
            @Parameter(description = "结束日期，格式：yyyy-MM-dd", required = true)
            @RequestParam String endDate,
            @Parameter(description = "租户ID", required = true)
            @RequestParam String tenantId) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (tenantId == null || tenantId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "tenantId不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            if (startDate == null || startDate.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "startDate不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            if (endDate == null || endDate.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "endDate不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            LocalDate parsedStartDate;
            LocalDate parsedEndDate;
            try {
                parsedStartDate = LocalDate.parse(startDate.trim());
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "startDate格式错误，请使用 yyyy-MM-dd");
                return ResponseEntity.badRequest().body(result);
            }
            try {
                parsedEndDate = LocalDate.parse(endDate.trim());
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "endDate格式错误，请使用 yyyy-MM-dd");
                return ResponseEntity.badRequest().body(result);
            }

            Map<String, Object> serviceResult = lbDailyUserTradeReportService
                    .listUserTradeAmountWithTeamByDateRangeAndTenant(parsedStartDate, parsedEndDate, tenantId.trim());
            Boolean success = (Boolean) serviceResult.get("success");
            if (Boolean.FALSE.equals(success)) {
                return ResponseEntity.badRequest().body(serviceResult);
            }
            return ResponseEntity.ok(serviceResult);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "统计异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @PostMapping("/calculate-report-sum/by-date-and-tenant")
    @Operation(summary = "按日期和租户汇总报表", description = "根据报表日期和租户ID汇总报表字段并新增一条 report_sum 记录")
    public ResponseEntity<Map<String, Object>> calculateReportSumByDateAndTenant(
            @Parameter(description = "报表日期，格式：yyyy-MM-dd", required = true)
            @RequestParam String reportDate,
            @Parameter(description = "租户ID", required = true)
            @RequestParam String tenantId) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (tenantId == null || tenantId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "tenantId不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            if (reportDate == null || reportDate.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "reportDate不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            LocalDate parsedReportDate;
            try {
                parsedReportDate = LocalDate.parse(reportDate.trim());
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "报表日期格式错误，请使用 yyyy-MM-dd");
                return ResponseEntity.badRequest().body(result);
            }

            Map<String, Object> serviceResult = lbDailyUserTradeReportService
                    .calculateReportSumByDateAndTenant(parsedReportDate, tenantId.trim());
            Boolean success = (Boolean) serviceResult.get("success");
            if (Boolean.TRUE.equals(success)) {
                return ResponseEntity.ok(serviceResult);
            }
            return ResponseEntity.badRequest().body(serviceResult);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "汇总异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/export/by-date-and-tenant")
    @Operation(summary = "按日期和租户导出报表Excel", description = "导出 reportDate 指定日期、tenantId 指定租户的报表数据到 Excel")
    public void exportByDateAndTenant(
            @Parameter(description = "报表日期，格式：yyyy-MM-dd", required = true)
            @RequestParam String reportDate,
            @Parameter(description = "租户ID", required = true)
            @RequestParam String tenantId,
            HttpServletResponse response) {
        lbDailyUserTradeReportService.exportByDateAndTenant(reportDate, tenantId, response);
    }
}
