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.service.ILbDailyUserTradeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

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

    @Autowired
    private ILbDailyUserTradeService lbDailyUserTradeService;

    @PostMapping("/add")
    @Operation(summary = "新增交易记录", description = "新增当天用户交易记录")
    public ResponseEntity<Map<String, Object>> addLbDailyUserTrade(
            @Parameter(description = "当天用户交易信息", required = true)
            @RequestBody LbDailyUserTrade lbDailyUserTrade) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (lbDailyUserTrade.getId() == null || lbDailyUserTrade.getId().trim().isEmpty()) {
                lbDailyUserTrade.setId(UUID.randomUUID().toString());
            }
            if (lbDailyUserTrade.getDailySellAmt() == null) {
                lbDailyUserTrade.setDailySellAmt(BigDecimal.ZERO);
            }
            if (lbDailyUserTrade.getDailyBuyAmt() == null) {
                lbDailyUserTrade.setDailyBuyAmt(BigDecimal.ZERO);
            }
            if (lbDailyUserTrade.getDiffAmt() == null) {
                lbDailyUserTrade.setDiffAmt(lbDailyUserTrade.getDailySellAmt().subtract(lbDailyUserTrade.getDailyBuyAmt()));
            }
            if (lbDailyUserTrade.getReportDate() == null) {
                lbDailyUserTrade.setReportDate(LocalDate.now());
            }
            lbDailyUserTrade.setCreatedAt(LocalDateTime.now());
            lbDailyUserTrade.setUpdatedAt(LocalDateTime.now());

            boolean success = lbDailyUserTradeService.save(lbDailyUserTrade);
            if (success) {
                result.put("success", true);
                result.put("message", "新增成功");
                result.put("data", lbDailyUserTrade);
                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 {
            LbDailyUserTrade data = lbDailyUserTradeService.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 nickname,
            @Parameter(description = "推广人ID")
            @RequestParam(required = false) String promoterId,
            @Parameter(description = "推广人（模糊查询）")
            @RequestParam(required = false) String promoterName,
            @Parameter(description = "报表日期，格式：yyyy-MM-dd")
            @RequestParam(required = false) String reportDate,
            @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<LbDailyUserTrade> queryWrapper = new LambdaQueryWrapper<>();
            if (tenantId != null && !tenantId.trim().isEmpty()) {
                queryWrapper.eq(LbDailyUserTrade::getTenantId, tenantId);
            }
            if (userId != null && !userId.trim().isEmpty()) {
                queryWrapper.eq(LbDailyUserTrade::getUserId, userId);
            }
            if (nickname != null && !nickname.trim().isEmpty()) {
                queryWrapper.like(LbDailyUserTrade::getNickname, nickname);
            }
            if (promoterId != null && !promoterId.trim().isEmpty()) {
                queryWrapper.eq(LbDailyUserTrade::getPromoterId, promoterId);
            }
            if (promoterName != null && !promoterName.trim().isEmpty()) {
                queryWrapper.like(LbDailyUserTrade::getPromoterName, promoterName);
            }
            if (reportDate != null && !reportDate.trim().isEmpty()) {
                try {
                    queryWrapper.eq(LbDailyUserTrade::getReportDate, LocalDate.parse(reportDate));
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "报表日期格式错误，请使用 yyyy-MM-dd");
                    return ResponseEntity.badRequest().body(result);
                }
            }

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (createdStartTime != null && !createdStartTime.trim().isEmpty()) {
                try {
                    queryWrapper.ge(LbDailyUserTrade::getCreatedAt, LocalDateTime.parse(createdStartTime, 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(LbDailyUserTrade::getCreatedAt, LocalDateTime.parse(createdEndTime, formatter));
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "创建结束时间格式错误，请使用 yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }

            queryWrapper.orderByDesc(LbDailyUserTrade::getCreatedAt);
            Page<LbDailyUserTrade> page = lbDailyUserTradeService.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);
        }
    }

    @PutMapping("/update")
    @Operation(summary = "修改交易记录", description = "根据ID修改当天用户交易记录")
    public ResponseEntity<Map<String, Object>> update(
            @Parameter(description = "当天用户交易信息", required = true)
            @RequestBody LbDailyUserTrade lbDailyUserTrade) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (lbDailyUserTrade.getId() == null || lbDailyUserTrade.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            if (lbDailyUserTrade.getDailySellAmt() != null && lbDailyUserTrade.getDailyBuyAmt() != null) {
                lbDailyUserTrade.setDiffAmt(lbDailyUserTrade.getDailySellAmt().subtract(lbDailyUserTrade.getDailyBuyAmt()));
            }
            lbDailyUserTrade.setUpdatedAt(LocalDateTime.now());
            boolean success = lbDailyUserTradeService.updateById(lbDailyUserTrade);
            if (success) {
                result.put("success", true);
                result.put("message", "修改成功");
                result.put("data", lbDailyUserTrade);
                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 = lbDailyUserTradeService.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);
            }

            LambdaQueryWrapper<LbDailyUserTrade> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LbDailyUserTrade::getReportDate, parsedReportDate);

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

            boolean success = lbDailyUserTradeService.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);
        }
    }

    @PostMapping("/calculate-report/by-date-and-tenant")
    @Operation(summary = "按日期和租户计算报表", description = "根据报表日期和租户ID计算当天交易报表并写入 lb_daily_user_trade_report")
    public ResponseEntity<Map<String, Object>> calculateReportByDateAndTenant(
            @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 = lbDailyUserTradeService.calculateDailyTradeReport(parsedReportDate, tenantId);
            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);
        }
    }

    @PostMapping("/import")
    @Operation(summary = "导入交易记录", description = "按Excel模板导入当天用户交易记录")
    public ResponseEntity<Map<String, Object>> importExcel(
            @Parameter(description = "Excel文件", required = true)
            @RequestParam("file") MultipartFile file,
            @Parameter(description = "默认报表日期，格式：yyyy-MM-dd；当Excel行里无报表日期时生效")
            @RequestParam(required = false) String defaultReportDate,
            @Parameter(description = "租户ID（必填，导入时写入每行记录）", required = true)
            @RequestParam String tenantId) {
        try {
            Map<String, Object> result = lbDailyUserTradeService.importFromExcel(file, defaultReportDate, tenantId);
            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return ResponseEntity.ok(result);
            }
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "导入异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
