package shop.alien.storeplatform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreOperationalStatisticsHistory;
import shop.alien.entity.store.vo.StoreOperationalStatisticsComparisonVo;
import shop.alien.entity.store.vo.StoreOperationalStatisticsVo;
import shop.alien.storeplatform.service.PlatformStoreOperationalStatisticsService;

import java.util.ArrayList;
import java.util.List;

/**
 * 商家经营数据统计Controller
 *
 * @author system
 * @version 1.0
 * @date 2026/01/05
 */
@Slf4j
@Api(tags = {"商家经营数据统计"})
@CrossOrigin
@RestController
@RequestMapping("/platform/operational/statistics")
@RequiredArgsConstructor
public class PlatformStoreOperationalStatisticsController {
    private final PlatformStoreOperationalStatisticsService platformStoreOperationalStatisticsService;

    @GetMapping("/getPlatformStatistics")
    public R<StoreOperationalStatisticsVo> getPlatformStatistics(
            @RequestParam("storeId") Integer storeId,
            @RequestParam("startTime") String startTime,
            @RequestParam("endTime") String endTime) {
        log.info("StoreOperationalStatisticsController.getStatistics - storeId={}, startTime={}, endTime={}", storeId, startTime, endTime);
        try {
            StoreOperationalStatisticsVo statistics = platformStoreOperationalStatisticsService.getPlatformStatisticsInTrackFormat(storeId, startTime, endTime);
            return R.data(statistics);
        } catch (Exception e) {
            log.error("获取商家经营统计数据失败 - storeId={}, startTime={}, endTime={}, error={}",
                    storeId, startTime, endTime, e.getMessage(), e);
            return R.fail("获取统计数据失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取商家经营统计数据对比")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "storeId",
                    value = "店铺ID",
                    dataType = "Integer",
                    paramType = "query",
                    required = true
            ),
            @ApiImplicitParam(
                    name = "currentStartTime",
                    value = "当期开始时间（格式：yyyy-MM-dd）",
                    dataType = "String",
                    paramType = "query",
                    required = true
            ),
            @ApiImplicitParam(
                    name = "currentEndTime",
                    value = "当期结束时间（格式：yyyy-MM-dd）",
                    dataType = "String",
                    paramType = "query",
                    required = true
            ),
            @ApiImplicitParam(
                    name = "previousStartTime",
                    value = "上期开始时间（格式：yyyy-MM-dd）",
                    dataType = "String",
                    paramType = "query",
                    required = true
            ),
            @ApiImplicitParam(
                    name = "previousEndTime",
                    value = "上期结束时间（格式：yyyy-MM-dd）",
                    dataType = "String",
                    paramType = "query",
                    required = true
            )
    })
    @GetMapping("/getPlatformStatisticsComparison")
    public R<StoreOperationalStatisticsComparisonVo> getPlatformStatisticsComparison(
            @RequestParam("storeId") Integer storeId,
            @RequestParam("currentStartTime") String currentStartTime,
            @RequestParam("currentEndTime") String currentEndTime,
            @RequestParam("previousStartTime") String previousStartTime,
            @RequestParam("previousEndTime") String previousEndTime) {
        log.info("StoreOperationalStatisticsController.getStatisticsComparison - storeId={}, currentStartTime={}, currentEndTime={}, previousStartTime={}, previousEndTime={}",
                storeId, currentStartTime, currentEndTime, previousStartTime, previousEndTime);
        StoreOperationalStatisticsComparisonVo comparison = platformStoreOperationalStatisticsService.getPlatformStatisticsComparison(
                storeId, currentStartTime, currentEndTime, previousStartTime, previousEndTime);
        return R.data(comparison);
    }

    @ApiOperation("根据ID查询历史统计记录详情")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "id",
                    value = "历史记录ID",
                    dataType = "Integer",
                    paramType = "query",
                    required = true
            )
    })
    @GetMapping("/history/platformDetail")
    public R<StoreOperationalStatisticsHistory> getPlatformHistoryById(@RequestParam("id") Integer id) {
        log.info("StoreOperationalStatisticsController.getPlatformHistoryById - id={}", id);
        try {
            if (id == null || id <= 0) {
                return R.fail("ID不能为空且必须大于0");
            }

            StoreOperationalStatisticsHistory history = platformStoreOperationalStatisticsService.getPlatformHistoryById(id);
            return R.data(history);
        } catch (Exception e) {
            log.error("查询历史统计记录详情失败 - id={}, error={}", id, e.getMessage(), e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }

    @ApiOperation("查询历史统计记录列表（分页）")
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "storeId",
                    value = "店铺ID",
                    dataType = "Integer",
                    paramType = "query",
                    required = true
            ),
            @ApiImplicitParam(
                    name = "page",
                    value = "页数（默认1）",
                    dataType = "int",
                    paramType = "query"
            ),
            @ApiImplicitParam(
                    name = "size",
                    value = "页容（默认10）",
                    dataType = "int",
                    paramType = "query"
            ),
            @ApiImplicitParam(
                    name = "created_time",
                    value = "查询日期（yyyy-MM-dd），可为空；传入时仅返回 query_time 为该日期的记录",
                    dataType = "String",
                    paramType = "query"
            )
    })
    @GetMapping("/history/platformList")
    public R<IPage<StoreOperationalStatisticsHistory>> getHistoryList(
            @RequestParam("storeId") Integer storeId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(value = "created_time", required = false) String createdTime) {
        log.info("StoreOperationalStatisticsController.getHistoryList - storeId={}, page={}, size={}, created_time={}", storeId, page, size, createdTime);
        try {
            int pageNum = page > 0 ? page : 1;
            int pageSize = size > 0 ? size : 10;
            IPage<StoreOperationalStatisticsHistory> historyPage = platformStoreOperationalStatisticsService.getPlatformHistoryList(storeId, pageNum, pageSize, createdTime);
            return R.data(historyPage);
        } catch (Exception e) {
            log.error("查询历史统计记录列表失败 - storeId={}, page={}, size={}, error={}", storeId, page, size, e.getMessage(), e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }


    @ApiOperation("批量删除历史统计记录")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "ids",
                    value = "历史记录ID列表（逗号分隔）",
                    dataType = "String",
                    paramType = "query",
                    required = true,
                    example = "1,2,3"
            )
    })
    @DeleteMapping("/history/batchPlatformDelete")
    public R<String> batchPlatformDeleteHistory(@RequestParam("ids") String ids) {
        log.info("StoreOperationalStatisticsController.batchDeleteHistory - ids={}", ids);
        try {
            if (ids == null || ids.trim().isEmpty()) {
                return R.fail("ID列表不能为空");
            }

            // 解析ID列表
            String[] idArray = ids.split(",");
            List<Integer> idList = new ArrayList<>();
            for (String idStr : idArray) {
                try {
                    int id = Integer.parseInt(idStr.trim());
                    if (id > 0) {
                        idList.add(id);
                    }
                } catch (NumberFormatException e) {
                    log.warn("无效的ID格式: {}", idStr);
                }
            }

            if (idList.isEmpty()) {
                return R.fail("没有有效的ID");
            }

            boolean result = platformStoreOperationalStatisticsService.batchPlatformDeleteHistory(idList);
            if (result) {
                return R.success("批量删除成功");
            } else {
                return R.fail("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除历史统计记录失败 - ids={}, error={}", ids, e.getMessage(), e);
            return R.fail("批量删除失败: " + e.getMessage());
        }
    }

    @ApiOperation("根据历史记录ID生成统计数据对比PDF报告并上传到OSS")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "storeId",
                    value = "店铺ID",
                    dataType = "Integer",
                    paramType = "query",
                    required = true
            ),
            @ApiImplicitParam(
                    name = "historyId",
                    value = "历史记录ID（从 store_operational_statistics_history 表取 statistics_data 解析为对比数据）",
                    dataType = "Integer",
                    paramType = "query",
                    required = true
            )
    })
    @GetMapping("/generateStatisticsComparisonPdfByHistoryId")
    public R<String> generateStatisticsComparisonPdfByHistoryId(
            @RequestParam("storeId") Integer storeId,
            @RequestParam("historyId") Integer historyId) {
        log.info("StoreOperationalStatisticsController.generateStatisticsComparisonPdfByHistoryId - storeId={}, historyId={}", storeId, historyId);
        try {
            String pdfUrl = platformStoreOperationalStatisticsService.generateStatisticsComparisonPdfByHistoryId(storeId, historyId);
            return R.data(pdfUrl);
        } catch (Exception e) {
            log.error("根据历史记录生成统计数据对比PDF失败 - storeId={}, historyId={}, error={}", storeId, historyId, e.getMessage(), e);
            return R.fail("生成PDF报告失败: " + e.getMessage());
        }
    }

}
