package com.erp.report.export.controller;

import com.erp.common.core.model.ApiResponse;
import com.erp.report.export.dto.*;
import com.erp.report.export.service.ReportExportService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 报表导出控制器
 * 
 * 提供RESTful API进行数据导出操作
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/exports")
@RequiredArgsConstructor
public class ReportExportController {

    private final ReportExportService reportExportService;

    // ==================== 订单导出 ====================

    /**
     * POST /api/v1/exports/orders
     * 导出订单
     */
    @PostMapping("/orders")
    public ApiResponse<ExportResponse> exportOrders(@Valid @RequestBody OrderExportRequest request) {
        try {
            ExportResponse response = reportExportService.exportOrders(request);
            return ApiResponse.success("导出成功", response);
        } catch (Exception e) {
            log.error("导出订单失败", e);
            return ApiResponse.<ExportResponse>error("导出失败: " + e.getMessage());
        }
    }

    /**
     * POST /api/v1/exports/orders/async
     * 异步导出订单
     */
    @PostMapping("/orders/async")
    public ApiResponse<String> exportOrdersAsync(@Valid @RequestBody OrderExportRequest request) {
        reportExportService.exportOrdersAsync(request);
        return ApiResponse.success("异步导出任务已提交", null);
    }

    // ==================== 商品导出 ====================

    /**
     * POST /api/v1/exports/goods
     * 导出商品
     */
    @PostMapping("/goods")
    public ApiResponse<ExportResponse> exportGoods(@Valid @RequestBody GoodsExportRequest request) {
        try {
            ExportResponse response = reportExportService.exportGoods(request);
            return ApiResponse.success("导出成功", response);
        } catch (Exception e) {
            log.error("导出商品失败", e);
            return ApiResponse.<ExportResponse>error("导出失败: " + e.getMessage());
        }
    }

    /**
     * POST /api/v1/exports/goods/async
     * 异步导出商品
     */
    @PostMapping("/goods/async")
    public ApiResponse<String> exportGoodsAsync(@Valid @RequestBody GoodsExportRequest request) {
        reportExportService.exportGoodsAsync(request);
        return ApiResponse.success("异步导出任务已提交", null);
    }

    // ==================== 库存导出 ====================

    /**
     * POST /api/v1/exports/inventory
     * 导出库存
     */
    @PostMapping("/inventory")
    public ApiResponse<ExportResponse> exportInventory(@Valid @RequestBody InventoryExportRequest request) {
        try {
            ExportResponse response = reportExportService.exportInventory(request);
            return ApiResponse.success("导出成功", response);
        } catch (Exception e) {
            log.error("导出库存失败", e);
            return ApiResponse.<ExportResponse>error("导出失败: " + e.getMessage());
        }
    }

    /**
     * POST /api/v1/exports/inventory/async
     * 异步导出库存
     */
    @PostMapping("/inventory/async")
    public ApiResponse<String> exportInventoryAsync(@Valid @RequestBody InventoryExportRequest request) {
        reportExportService.exportInventoryAsync(request);
        return ApiResponse.success("异步导出任务已提交", null);
    }

    // ==================== 供应商导出 ====================

    /**
     * POST /api/v1/exports/suppliers
     * 导出供应商
     */
    @PostMapping("/suppliers")
    public ApiResponse<ExportResponse> exportSuppliers(@Valid @RequestBody SupplierExportRequest request) {
        try {
            ExportResponse response = reportExportService.exportSuppliers(request);
            return ApiResponse.success("导出成功", response);
        } catch (Exception e) {
            log.error("导出供应商失败", e);
            return ApiResponse.<ExportResponse>error("导出失败: " + e.getMessage());
        }
    }

    /**
     * POST /api/v1/exports/suppliers/async
     * 异步导出供应商
     */
    @PostMapping("/suppliers/async")
    public ApiResponse<String> exportSuppliersAsync(@Valid @RequestBody SupplierExportRequest request) {
        reportExportService.exportSuppliersAsync(request);
        return ApiResponse.success("异步导出任务已提交", null);
    }

    // ==================== 报表导出 ====================

    /**
     * POST /api/v1/exports/reports/stock
     * 导出库存报表
     */
    @PostMapping("/reports/stock")
    public ApiResponse<ExportResponse> exportStockReport(@Valid @RequestBody OrderExportRequest request) {
        try {
            ExportResponse response = reportExportService.exportStockReport(request);
            return ApiResponse.success("导出成功", response);
        } catch (Exception e) {
            log.error("导出库存报表失败", e);
            return ApiResponse.<ExportResponse>error("导出失败: " + e.getMessage());
        }
    }

    /**
     * POST /api/v1/exports/reports/sales
     * 导出销售报表
     */
    @PostMapping("/reports/sales")
    public ApiResponse<ExportResponse> exportSalesReport(@Valid @RequestBody OrderExportRequest request) {
        try {
            ExportResponse response = reportExportService.exportSalesReport(request);
            return ApiResponse.success("导出成功", response);
        } catch (Exception e) {
            log.error("导出销售报表失败", e);
            return ApiResponse.<ExportResponse>error("导出失败: " + e.getMessage());
        }
    }

    /**
     * POST /api/v1/exports/reports/orders
     * 导出订单报表
     */
    @PostMapping("/reports/orders")
    public ApiResponse<ExportResponse> exportOrderReport(@Valid @RequestBody OrderExportRequest request) {
        try {
            ExportResponse response = reportExportService.exportOrderReport(request);
            return ApiResponse.success("导出成功", response);
        } catch (Exception e) {
            log.error("导出订单报表失败", e);
            return ApiResponse.<ExportResponse>error("导出失败: " + e.getMessage());
        }
    }

    /**
     * POST /api/v1/exports/reports/purchases
     * 导出采购报表
     */
    @PostMapping("/reports/purchases")
    public ApiResponse<ExportResponse> exportPurchaseReport(@Valid @RequestBody OrderExportRequest request) {
        try {
            ExportResponse response = reportExportService.exportPurchaseReport(request);
            return ApiResponse.success("导出成功", response);
        } catch (Exception e) {
            log.error("导出采购报表失败", e);
            return ApiResponse.<ExportResponse>error("导出失败: " + e.getMessage());
        }
    }

    /**
     * POST /api/v1/exports/reports/finances
     * 导出资金报表
     */
    @PostMapping("/reports/finances")
    public ApiResponse<ExportResponse> exportFinanceReport(@Valid @RequestBody OrderExportRequest request) {
        try {
            ExportResponse response = reportExportService.exportFinanceReport(request);
            return ApiResponse.success("导出成功", response);
        } catch (Exception e) {
            log.error("导出资金报表失败", e);
            return ApiResponse.<ExportResponse>error("导出失败: " + e.getMessage());
        }
    }

    // ==================== 导出历史管理 ====================

    /**
     * GET /api/v1/exports
     * 获取导出历史记录列表
     */
    @GetMapping
    public ApiResponse<List<ExportHistoryResponse>> getExportHistory(
            @RequestParam Long tenantId,
            @RequestParam(required = false) ExportType type,
            @RequestParam(required = false) ExportStatus status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int pageSize) {
        
        List<ExportHistoryResponse> history = reportExportService.getExportHistory(
                tenantId, type, status, page, pageSize);
        return ApiResponse.success(history);
    }

    /**
     * GET /api/v1/exports/{id}
     * 获取导出记录详情
     */
    @GetMapping("/{id}")
    public ApiResponse<ExportHistoryResponse> getExportById(
            @PathVariable Long id,
            @RequestParam Long tenantId) {
        
        ExportHistoryResponse response = reportExportService.getExportById(id, tenantId);
        if (response == null) {
            return ApiResponse.notFound("记录不存在");
        }
        return ApiResponse.success(response);
    }

    /**
     * DELETE /api/v1/exports/{id}
     * 删除导出记录
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Boolean> deleteExport(
            @PathVariable Long id,
            @RequestParam Long tenantId) {
        
        boolean deleted = reportExportService.deleteExport(id, tenantId);
        if (deleted) {
            return ApiResponse.success("删除成功", true);
        }
        return ApiResponse.<Boolean>error("删除失败");
    }

    /**
     * GET /api/v1/exports/{id}/download
     * 下载导出文件
     */
    @GetMapping("/{id}/download")
    public ResponseEntity<byte[]> downloadExport(
            @PathVariable Long id,
            @RequestParam Long tenantId) throws IOException {
        
        ExportHistoryResponse export = reportExportService.getExportById(id, tenantId);
        if (export == null) {
            return ResponseEntity.notFound().build();
        }
        
        if (export.getStatus() != ExportStatus.COMPLETED) {
            return ResponseEntity.badRequest().build();
        }
        
        String filePath = "/data/exports/" + tenantId + "/" + export.getFilename() + export.getFormat().getExtension();
        Path path = Paths.get(filePath);
        
        if (!Files.exists(path)) {
            return ResponseEntity.notFound().build();
        }
        
        byte[] content = Files.readAllBytes(path);
        
        String filename = URLEncoder.encode(export.getFilename() + export.getFormat().getExtension(), 
                StandardCharsets.UTF_8.name());
        
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                .contentType(MediaType.parseMediaType(export.getFormat().getContentType()))
                .body(content);
    }

    // ==================== 定时任务管理 ====================

    /**
     * POST /api/v1/exports/scheduled
     * 创建定时导出任务
     */
    @PostMapping("/scheduled")
    public ApiResponse<String> createScheduledExport(
            @Valid @RequestBody BaseExportRequest request,
            @RequestParam String cronExpression) {
        
        String taskId = reportExportService.createScheduledExport(request, cronExpression);
        return ApiResponse.success("定时导出任务已创建", taskId);
    }

    /**
     * DELETE /api/v1/exports/scheduled/{taskId}
     * 取消定时导出任务
     */
    @DeleteMapping("/scheduled/{taskId}")
    public ApiResponse<Boolean> cancelScheduledExport(@PathVariable String taskId) {
        boolean cancelled = reportExportService.cancelScheduledExport(taskId);
        if (cancelled) {
            return ApiResponse.success("定时导出任务已取消", true);
        }
        return ApiResponse.<Boolean>error("取消失败，任务可能不存在");
    }

    /**
     * GET /api/v1/exports/scheduled
     * 获取租户的定时导出任务列表
     */
    @GetMapping("/scheduled")
    public ApiResponse<List<String>> getScheduledExports(@RequestParam Long tenantId) {
        List<String> tasks = reportExportService.getScheduledExports(tenantId);
        return ApiResponse.success(tasks);
    }
}
