package com.erp.dataimport.controller;

import com.erp.common.core.model.ApiResponse;
import com.erp.dataimport.dto.*;
import com.erp.dataimport.service.DataImportService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 数据导入导出控制器
 */
@Slf4j
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class DataImportController {

    private final DataImportService dataImportService;

    /**
     * 上传并导入文件（异步）
     */
    @PostMapping("/import/async")
    public ResponseEntity<ApiResponse<ImportResultResponse>> importFileAsync(
            @RequestParam("file") MultipartFile file,
            @RequestParam("taskName") String taskName,
            @RequestParam("bizType") String bizType,
            @RequestParam(value = "skipDuplicate", defaultValue = "false") Boolean skipDuplicate,
            @RequestParam(value = "updateExisting", defaultValue = "false") Boolean updateExisting,
            @RequestParam("tenantId") Long tenantId,
            @RequestParam("creatorId") Long creatorId,
            @RequestParam(value = "creatorName", defaultValue = "") String creatorName) {
        
        log.info("异步导入文件: taskName={}, bizType={}, fileName={}", taskName, bizType, file.getOriginalFilename());
        
        ImportFileRequest request = new ImportFileRequest();
        request.setTaskName(taskName);
        request.setBizType(bizType);
        request.setSkipDuplicate(skipDuplicate);
        request.setUpdateExisting(updateExisting);
        request.setTenantId(tenantId);
        request.setCreatorId(creatorId);
        request.setCreatorName(creatorName);
        
        dataImportService.importFile(file, request);
        return ResponseEntity.ok(ApiResponse.success("文件上传成功，正在后台处理", null));
    }

    /**
     * 上传并导入文件（同步）
     */
    @PostMapping("/import")
    public ResponseEntity<ApiResponse<ImportResultResponse>> importFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("taskName") String taskName,
            @RequestParam("bizType") String bizType,
            @RequestParam(value = "skipDuplicate", defaultValue = "false") Boolean skipDuplicate,
            @RequestParam(value = "updateExisting", defaultValue = "false") Boolean updateExisting,
            @RequestParam("tenantId") Long tenantId,
            @RequestParam("creatorId") Long creatorId,
            @RequestParam(value = "creatorName", defaultValue = "") String creatorName) {
        
        log.info("同步导入文件: taskName={}, bizType={}, fileName={}", taskName, bizType, file.getOriginalFilename());
        
        ImportFileRequest request = new ImportFileRequest();
        request.setTaskName(taskName);
        request.setBizType(bizType);
        request.setSkipDuplicate(skipDuplicate);
        request.setUpdateExisting(updateExisting);
        request.setTenantId(tenantId);
        request.setCreatorId(creatorId);
        request.setCreatorName(creatorName);
        
        ImportResultResponse result = dataImportService.importFileSync(file, request);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 获取导入任务列表
     */
    @GetMapping("/import/tasks")
    public ResponseEntity<ApiResponse<ImportTaskPageResponse>> listImportTasks(
            @RequestParam(required = false) String bizType,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "15") Integer limit,
            @RequestParam("tenantId") Long tenantId) {
        
        log.info("查询导入任务列表: bizType={}, status={}, page={}, limit={}", bizType, status, page, limit);
        
        ImportTaskListRequest request = new ImportTaskListRequest();
        request.setBizType(bizType);
        request.setStatus(status);
        request.setKeyword(keyword);
        request.setPage(page);
        request.setLimit(limit);
        
        ImportTaskPageResponse response = dataImportService.listImportTasks(request);
        return ResponseEntity.ok(ApiResponse.success(response));
    }

    /**
     * 获取导入任务详情
     */
    @GetMapping("/import/tasks/{taskId}")
    public ResponseEntity<ApiResponse<ImportTaskDTO>> getImportTask(
            @PathVariable Long taskId,
            @RequestParam("tenantId") Long tenantId) {
        
        log.info("查询导入任务详情: taskId={}", taskId);
        ImportTaskDTO task = dataImportService.getImportTask(taskId, tenantId);
        return ResponseEntity.ok(ApiResponse.success(task));
    }

    /**
     * 获取导入结果
     */
    @GetMapping("/import/tasks/{taskId}/result")
    public ResponseEntity<ApiResponse<ImportResultResponse>> getImportResult(
            @PathVariable Long taskId,
            @RequestParam("tenantId") Long tenantId) {
        
        log.info("获取导入结果: taskId={}", taskId);
        ImportResultResponse result = dataImportService.getImportResult(taskId, tenantId);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 获取导入失败记录
     */
    @GetMapping("/import/tasks/{taskId}/fail-records")
    public ResponseEntity<ApiResponse<ImportRecordPageResponse>> listImportFailRecords(
            @PathVariable Long taskId,
            @RequestParam(required = false) String result,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "15") Integer limit) {
        
        log.info("查询导入失败记录: taskId={}", taskId);
        
        ImportRecordListRequest request = new ImportRecordListRequest();
        request.setTaskId(taskId);
        request.setResult(result);
        request.setPage(page);
        request.setLimit(limit);
        
        ImportRecordPageResponse response = dataImportService.listImportFailRecords(request);
        return ResponseEntity.ok(ApiResponse.success(response));
    }

    /**
     * 下载错误报告
     */
    @GetMapping("/import/tasks/{taskId}/error-report")
    public void downloadErrorReport(
            @PathVariable Long taskId,
            @RequestParam("tenantId") Long tenantId,
            HttpServletResponse response) throws IOException {
        
        log.info("下载错误报告: taskId={}", taskId);
        
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("错误报告_" + taskId, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        
        dataImportService.downloadErrorReport(taskId, tenantId, response.getOutputStream());
    }

    /**
     * 删除导入任务
     */
    @DeleteMapping("/import/tasks/{taskId}")
    public ResponseEntity<ApiResponse<Void>> deleteImportTask(
            @PathVariable Long taskId,
            @RequestParam("tenantId") Long tenantId) {
        
        log.info("删除导入任务: taskId={}", taskId);
        dataImportService.deleteImportTask(taskId, tenantId);
        return ResponseEntity.ok(ApiResponse.<Void>success("删除成功", null));
    }

    /**
     * 生成导入模板
     */
    @GetMapping("/import/templates/{bizType}/download")
    public void downloadTemplate(
            @PathVariable String bizType,
            @RequestParam("tenantId") Long tenantId,
            HttpServletResponse response) throws IOException {
        
        log.info("下载导入模板: bizType={}", bizType);
        
        String fileName = bizType + "_import_template.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName);
        
        dataImportService.generateTemplate(bizType, tenantId, response.getOutputStream());
    }

    /**
     * 创建自定义模板
     */
    @PostMapping("/import/templates")
    public ResponseEntity<ApiResponse<ImportTemplateDTO>> createTemplate(
            @Valid @RequestBody CreateTemplateRequest request) {
        
        log.info("创建导入模板: templateName={}, bizType={}", request.getTemplateName(), request.getBizType());
        ImportTemplateDTO template = dataImportService.createTemplate(request);
        return ResponseEntity.ok(ApiResponse.success("创建成功", template));
    }

    /**
     * 获取模板列表
     */
    @GetMapping("/import/templates")
    public ResponseEntity<ApiResponse<List<ImportTemplateDTO>>> listTemplates(
            @RequestParam(required = false) String bizType,
            @RequestParam("tenantId") Long tenantId) {
        
        log.info("查询模板列表: bizType={}", bizType);
        List<ImportTemplateDTO> templates = dataImportService.listTemplates(bizType, tenantId);
        return ResponseEntity.ok(ApiResponse.success(templates));
    }

    /**
     * 删除模板
     */
    @DeleteMapping("/import/templates/{templateId}")
    public ResponseEntity<ApiResponse<Void>> deleteTemplate(
            @PathVariable Long templateId,
            @RequestParam("tenantId") Long tenantId) {
        
        log.info("删除模板: templateId={}", templateId);
        dataImportService.deleteTemplate(templateId, tenantId);
        return ResponseEntity.ok(ApiResponse.<Void>success("删除成功", null));
    }

    /**
     * 导出数据为CSV
     */
    @GetMapping("/export/csv/{bizType}")
    public void exportToCsv(
            @PathVariable String bizType,
            @RequestParam("columns") List<String> columns,
            HttpServletResponse response) throws IOException {
        
        log.info("导出CSV: bizType={}, columns={}", bizType, columns);
        
        response.setContentType("text/csv;charset=UTF-8");
        String fileName = bizType + "_export.csv";
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName);
        
        // 这里应该从具体业务服务获取数据，目前返回空
        dataImportService.exportToCsv(bizType, columns, java.util.Collections.emptyList(), response.getOutputStream());
    }

    /**
     * 导出数据为Excel
     */
    @GetMapping("/export/excel/{bizType}")
    public void exportToExcel(
            @PathVariable String bizType,
            @RequestParam("headers") List<String> headers,
            HttpServletResponse response) throws IOException {
        
        log.info("导出Excel: bizType={}, headers={}", bizType, headers);
        
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = bizType + "_export.xlsx";
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName);
        
        // 这里应该从具体业务服务获取数据，目前返回空
        dataImportService.exportToExcel(bizType, headers, java.util.Collections.emptyList(), response.getOutputStream());
    }

    /**
     * 获取支持的业务类型
     */
    @GetMapping("/import/biz-types")
    public ResponseEntity<ApiResponse<List<String>>> getSupportedBizTypes() {
        List<String> bizTypes = dataImportService.getSupportedBizTypes();
        return ResponseEntity.ok(ApiResponse.success(bizTypes));
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("Data Import Export Service is healthy");
    }
}
