package com.nbport.zgwl.contractlaunch.service;

import cn.hutool.core.util.StrUtil;
import com.nbport.zgwl.contractlaunch.dto.ContractLaunchFileDto;
import com.nbport.zgwl.contractlaunch.mapper.ContractLaunchMapper;
import com.nbport.zgwl.contractpush.service.DataCollectionPushService;
import com.nbport.zgwl.exception.ServiceException;
import com.nbport.zgwl.service.LocalFileService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ContractLaunchLegalFileBridgeService {

    private final DataCollectionPushService dataCollectionPushService;
    private final LocalFileService localFileService;
    private final ContractLaunchMapper contractLaunchMapper;

    public String ensureLegalFilePath(ContractLaunchFileDto fileDto) {
        if (fileDto == null) {
            return null;
        }
        String cachedLegalPath = StrUtil.trim(fileDto.getLegalFileUrl());
        if (StrUtil.isNotBlank(cachedLegalPath)) {
            return cachedLegalPath;
        }
        String filePath = StrUtil.trim(fileDto.getFilePath());
        if (StrUtil.isBlank(filePath)) {
            return null;
        }
        if (isLegalRemotePath(filePath)) {
            return filePath;
        }
        byte[] bytes = localFileService.readFileBytes(filePath);
        Map<String, Object> uploadResult = dataCollectionPushService.upload(bytes, resolveFileName(fileDto), null);
        String legalPath = extractUploadedPath(uploadResult);
        if (StrUtil.isBlank(legalPath)) {
            throw new ServiceException("法务附件上传成功但未返回文件路径");
        }
        fileDto.setLegalFileUrl(legalPath);
        if (fileDto.getId() != null) {
            contractLaunchMapper.updateFileLegalUrl(fileDto.getId(), legalPath, "system");
        }
        return legalPath;
    }

    public Map<String, Object> buildSettlementPayload(ContractLaunchFileDto fileDto) {
        String legalPath = ensureLegalFilePath(fileDto);
        if (StrUtil.isBlank(legalPath)) {
            return null;
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("fileName", resolveFileName(fileDto));
        map.put("filePath", legalPath);
        map.put("fileSize", fileDto.getFileSize());
        map.put("fileType", resolveSuffix(fileDto));
        return map;
    }

    public Map<String, Object> buildCollectionPayload(ContractLaunchFileDto fileDto) {
        String legalPath = ensureLegalFilePath(fileDto);
        if (StrUtil.isBlank(legalPath)) {
            return null;
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("size", fileDto.getFileSize() == null ? "" : String.valueOf(fileDto.getFileSize()));
        map.put("name", resolveFileName(fileDto));
        map.put("suffix", resolveSuffix(fileDto));
        map.put("path", legalPath);
        return map;
    }

    private String resolveFileName(ContractLaunchFileDto fileDto) {
        String fileName = StrUtil.trim(fileDto.getFileName());
        if (StrUtil.isNotBlank(fileName)) {
            return fileName;
        }
        throw new ServiceException("附件文件名不能为空");
    }

    private String resolveSuffix(ContractLaunchFileDto fileDto) {
        String fileType = StrUtil.trim(fileDto.getFileType());
        if (StrUtil.isNotBlank(fileType)) {
            return fileType.startsWith(".") ? fileType.substring(1) : fileType;
        }
        String fileName = resolveFileName(fileDto);
        int index = fileName.lastIndexOf('.');
        return index >= 0 && index < fileName.length() - 1 ? fileName.substring(index + 1) : "";
    }

    private boolean isLegalRemotePath(String filePath) {
        return filePath.startsWith("/cj/")
                || filePath.startsWith("http://")
                || filePath.startsWith("https://");
    }

    @SuppressWarnings("unchecked")
    private String extractUploadedPath(Map<String, Object> uploadResult) {
        if (uploadResult == null || uploadResult.isEmpty()) {
            return null;
        }
        Object directData = uploadResult.get("data");
        if (directData instanceof String && StrUtil.isNotBlank((String) directData)) {
            return (String) directData;
        }
        if (directData instanceof Map) {
            Object nested = ((Map<String, Object>) directData).get("data");
            if (nested instanceof String && StrUtil.isNotBlank((String) nested)) {
                return (String) nested;
            }
            Object path = ((Map<String, Object>) directData).get("path");
            if (path instanceof String && StrUtil.isNotBlank((String) path)) {
                return (String) path;
            }
        }
        Object result = uploadResult.get("result");
        if (result instanceof String && StrUtil.isNotBlank((String) result)) {
            return (String) result;
        }
        return null;
    }
}
