package com.ruoyi.lsfx.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.lsfx.client.LsfxAnalysisClient;
import com.ruoyi.lsfx.constants.LsfxConstants;
import com.ruoyi.lsfx.domain.request.DeleteFilesRequest;
import com.ruoyi.lsfx.domain.request.FetchInnerFlowRequest;
import com.ruoyi.lsfx.domain.request.GetBankStatementRequest;
import com.ruoyi.lsfx.domain.request.GetFileUploadStatusRequest;
import com.ruoyi.lsfx.domain.request.GetTokenRequest;
import com.ruoyi.lsfx.domain.response.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

/**
 * 流水分析平台接口测试控制器
 */
@Tag(name = "流水分析平台接口测试", description = "用于测试流水分析平台的7个接口")
@Anonymous
@RestController
@RequestMapping("/lsfx/test")
public class LsfxTestController {

    @Resource
    private LsfxAnalysisClient lsfxAnalysisClient;

    @Operation(summary = "获取Token", description = "创建项目并获取访问Token")
    @PostMapping("/getToken")
    public AjaxResult getToken(@RequestBody GetTokenRequest request) {
        // 参数校验
        if (StringUtils.isBlank(request.getProjectNo())) {
            return AjaxResult.error("参数不完整：projectNo为必填");
        }
        if (StringUtils.isBlank(request.getEntityName())) {
            return AjaxResult.error("参数不完整：entityName为必填");
        }

        // 必填字段设置默认值
        if (StringUtils.isBlank(request.getUserId())) {
            request.setUserId(LsfxConstants.DEFAULT_USER_ID);
        }
        if (StringUtils.isBlank(request.getUserName())) {
            request.setUserName(LsfxConstants.DEFAULT_USER_NAME);
        }
        if (StringUtils.isBlank(request.getOrgCode())) {
            request.setOrgCode(LsfxConstants.DEFAULT_ORG_CODE);
        }
        if (StringUtils.isBlank(request.getDepartmentCode())) {
            request.setDepartmentCode(LsfxConstants.DEFAULT_DEPARTMENT_CODE);
        }

        GetTokenResponse response = lsfxAnalysisClient.getToken(request);
        return AjaxResult.success(response);
    }

    @Operation(summary = "上传流水文件", description = "上传银行流水文件到流水分析平台")
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(
        @Parameter(description = "项目ID") @RequestParam Integer groupId,
        @Parameter(description = "流水文件") @RequestParam("file") MultipartFile file
    ) {
        // 参数校验
        if (groupId == null || groupId <= 0) {
            return AjaxResult.error("参数不完整：groupId为必填且大于0");
        }
        if (file == null || file.isEmpty()) {
            return AjaxResult.error("参数不完整：文件不能为空");
        }
        if (file.getSize() > 10 * 1024 * 1024) { // 10MB限制
            return AjaxResult.error("文件大小超过限制：最大10MB");
        }

        // 将 MultipartFile 转换为 File
        Path tempFile = null;
        try {
            // 创建临时文件
            tempFile = Files.createTempFile("upload_", "_" + file.getOriginalFilename());
            Files.copy(file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);

            File convertedFile = tempFile.toFile();
            UploadFileResponse response = lsfxAnalysisClient.uploadFile(groupId, convertedFile);
            return AjaxResult.success(response);
        } catch (IOException e) {
            return AjaxResult.error("文件转换失败：" + e.getMessage());
        } finally {
            // 删除临时文件
            if (tempFile != null) {
                try {
                    Files.deleteIfExists(tempFile);
                } catch (IOException e) {
                    // 忽略删除失败
                }
            }
        }
    }

    @Operation(summary = "拉取行内流水", description = "从数仓拉取行内流水数据")
    @PostMapping("/fetchInnerFlow")
    public AjaxResult fetchInnerFlow(@RequestBody FetchInnerFlowRequest request) {
        // 参数校验
        if (request.getGroupId() == null || request.getGroupId() <= 0) {
            return AjaxResult.error("参数不完整：groupId为必填且大于0");
        }
        if (StringUtils.isEmpty(request.getCustomerNo())) {
            return AjaxResult.error("参数不完整：customerNo为必填");
        }
        if (request.getRequestDateId() == null) {
            return AjaxResult.error("参数不完整：requestDateId为必填");
        }
        if (request.getDataStartDateId() == null) {
            return AjaxResult.error("参数不完整：dataStartDateId为必填");
        }
        if (request.getDataEndDateId() == null) {
            return AjaxResult.error("参数不完整：dataEndDateId为必填");
        }
        if (request.getDataStartDateId() > request.getDataEndDateId()) {
            return AjaxResult.error("参数错误：开始日期不能大于结束日期");
        }

        // 设置dataChannelCode默认值
        if (StringUtils.isEmpty(request.getDataChannelCode())) {
            request.setDataChannelCode(LsfxConstants.DEFAULT_DATA_CHANNEL_CODE);
        }

        FetchInnerFlowResponse response = lsfxAnalysisClient.fetchInnerFlow(request);
        return AjaxResult.success(response);
    }

    @Operation(summary = "检查文件解析状态", description = "轮询检查上传文件的解析状态")
    @PostMapping("/checkParseStatus")
    public AjaxResult checkParseStatus(
        @Parameter(description = "项目ID") @RequestParam Integer groupId,
        @Parameter(description = "文件ID列表") @RequestParam String inprogressList
    ) {
        // 参数校验
        if (groupId == null || groupId <= 0) {
            return AjaxResult.error("参数不完整：groupId为必填且大于0");
        }
        if (StringUtils.isEmpty(inprogressList)) {
            return AjaxResult.error("参数不完整：inprogressList为必填");
        }

        CheckParseStatusResponse response = lsfxAnalysisClient.checkParseStatus(groupId, inprogressList);
        return AjaxResult.success(response);
    }

    @Operation(summary = "获取银行流水列表(新版)",
               description = "分页获取指定文件的银行流水数据，需要提供logId参数")
    @PostMapping("/getBankStatement")
    public AjaxResult getBankStatement(@RequestBody GetBankStatementRequest request) {
        // 参数校验
        if (request.getGroupId() == null) {
            return AjaxResult.error("参数不完整：groupId为必填");
        }
        if (request.getLogId() == null) {
            return AjaxResult.error("参数不完整：logId为必填(文件ID)");
        }
        if (request.getPageNow() == null || request.getPageNow() < 1) {
            return AjaxResult.error("参数不完整：pageNow为必填且大于0");
        }
        if (request.getPageSize() == null || request.getPageSize() < 1) {
            return AjaxResult.error("参数不完整：pageSize为必填且大于0");
        }

        GetBankStatementResponse response = lsfxAnalysisClient.getBankStatement(request);
        return AjaxResult.success(response);
    }

    @Operation(summary = "获取单个文件上传状态",
               description = "获取文件解析后的主体名称和账号等信息。status=-5且uploadStatusDesc='data.wait.confirm.newaccount'表示解析成功")
    @GetMapping("/getFileUploadStatus")
    public AjaxResult getFileUploadStatus(
        @Parameter(description = "项目ID") @RequestParam Integer groupId,
        @Parameter(description = "文件ID(可选,不传则查询所有)") @RequestParam(required = false) Integer logId
    ) {
        // 参数校验
        if (groupId == null || groupId <= 0) {
            return AjaxResult.error("参数不完整：groupId为必填且大于0");
        }

        GetFileUploadStatusRequest request = new GetFileUploadStatusRequest();
        request.setGroupId(groupId);
        request.setLogId(logId);

        GetFileUploadStatusResponse response = lsfxAnalysisClient.getFileUploadStatus(request);
        return AjaxResult.success(response);
    }

    @Operation(summary = "删除文件",
               description = "删除解析失败或不需要的流水文件")
    @PostMapping("/deleteFiles")
    public AjaxResult deleteFiles(@RequestBody DeleteFilesRequest request) {
        // 参数校验
        if (request.getGroupId() == null || request.getGroupId() <= 0) {
            return AjaxResult.error("参数不完整：groupId为必填且大于0");
        }
        if (request.getLogIds() == null || request.getLogIds().length == 0) {
            return AjaxResult.error("参数不完整：logIds为必填且不能为空");
        }
        if (request.getUserId() == null) {
            return AjaxResult.error("参数不完整：userId为必填");
        }

        DeleteFilesResponse response = lsfxAnalysisClient.deleteFiles(request);
        return AjaxResult.success(response);
    }
}
