package com.nanri.aiimage.modules.split.controller;

import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.modules.split.model.dto.SplitRunRequest;
import com.nanri.aiimage.modules.split.model.vo.SplitHistoryVo;
import com.nanri.aiimage.modules.split.model.vo.SplitRunVo;
import com.nanri.aiimage.modules.split.service.SplitRunService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/split")
@Tag(name = "数据拆分", description = "按照旧 Python 桌面端规则执行数据拆分。桌面端交互不变，只将处理逻辑迁到 Java。")
public class SplitRunController {

    private final SplitRunService splitRunService;

    @PostMapping("/run")
    @Operation(
            summary = "执行数据拆分",
            description = """
                    根据上传文件、保留列、拆分模式和参数执行 Excel 拆分。

                    规则与旧 Python 桌面端保持一致：
                    - 表头做文本清洗并兼容历史脏串；
                    - 遇到“缩略图地址8”停止继续识别表头；
                    - 仅保留 selectedColumns 中指定的列；
                    - splitMode=rows_per_file 时按固定条数切分；
                    - splitMode=parts 时按总条数尽量均分；
                    - 输出文件命名遵循 原文件名_split_序号.xlsx；
                    - 本次拆分任务产生的所有 xlsx 会统一打成一个 zip 上传；
                    - 返回结果中 rowCount 表示该压缩包包含的数据总行数，entries 表示压缩包内文件摘要。
                    """)
    @ApiResponses({
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "执行成功，返回拆分结果统计", content = @Content(schema = @Schema(implementation = SplitRunVo.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "请求参数不合法或拆分模式错误"),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "执行数据拆分失败")
    })
    public ApiResponse<SplitRunVo> run(@Valid @RequestBody SplitRunRequest request) {
        return ApiResponse.success(splitRunService.run(request));
    }

    @GetMapping("/history")
    @Operation(summary = "查询数据拆分历史", description = "查询当前用户最近的数据拆分成功记录，用于页面右侧历史下载列表展示。")
    @ApiResponses({
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = SplitHistoryVo.class)))
    })
    public ApiResponse<SplitHistoryVo> history(
            @Parameter(name = "user_id", description = "当前登录用户 ID", required = true, in = ParameterIn.QUERY)
            @RequestParam("user_id") Long userId) {
        SplitHistoryVo vo = new SplitHistoryVo();
        vo.setItems(splitRunService.listHistory(userId));
        return ApiResponse.success(vo);
    }

    @DeleteMapping("/history/{resultId}")
    @Operation(summary = "删除数据拆分历史", description = "删除当前用户的一条数据拆分历史记录。")
    @ApiResponses({
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "结果记录不存在")
    })
    public ApiResponse<Void> deleteHistory(
            @Parameter(description = "数据拆分结果记录 ID", required = true) @PathVariable Long resultId,
            @Parameter(name = "user_id", description = "当前登录用户 ID", required = true, in = ParameterIn.QUERY)
            @RequestParam("user_id") Long userId) {
        splitRunService.deleteHistory(resultId, userId);
        return ApiResponse.success(null);
    }

    @GetMapping("/results/{resultId}/download")
    @Operation(summary = "下载数据拆分结果", description = "根据结果记录 ID 下载当前用户的拆分结果文件。")
    @ApiResponses({
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "返回结果文件流"),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "结果文件不存在")
    })
    public ResponseEntity<Resource> download(
            @Parameter(description = "数据拆分结果记录 ID", required = true) @PathVariable Long resultId,
            @Parameter(name = "user_id", description = "当前登录用户 ID", required = true, in = ParameterIn.QUERY)
            @RequestParam("user_id") Long userId) {
        Resource resource = splitRunService.getResultFile(resultId, userId);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment")
                .body(resource);
    }
}
