package com.emoon.tongue.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.emoon.tongue.service.ISaveFileService;
import com.emoon.tongue.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class SaveFileServiceImpl implements ISaveFileService {

    /**
     * 文件落盘服务地址（对应 curl: /service4/api/file/download）
     */
    @Value("${tongue.file-download.url:http://61.178.77.37:8100/service4/api/file/download}")
    private String fileDownloadUrl;

    @Override
    public String uploadFilePath(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return null;
        }

        String originalFilename = file.getOriginalFilename();
        String fileName = sanitizeFileName(originalFilename);
        if (StrUtil.isBlank(fileName)) {
            // 给个兜底文件名，避免对端校验失败
            fileName = "upload.bin";
        }

        try {
            byte[] bytes = file.getBytes();
            String base64 = Base64.getEncoder().encodeToString(bytes);

            Map<String, Object> req = new HashMap<>();
            req.put("content", base64);
            req.put("fileName", fileName);

            String respStr = HttpUtils.sendHttpPostByJson(fileDownloadUrl, JSONUtil.toJsonStr(req));
            if (StrUtil.isBlank(respStr)) {
                log.warn("文件落盘服务返回空响应, url={}, fileName={}", fileDownloadUrl, fileName);
                return null;
            }

            JSONObject resp = JSONUtil.parseObj(respStr);
            Integer code = resp.getInt("code");
            if (code == null || code != 0) {
                log.warn("文件落盘服务返回失败, url={}, fileName={}, resp={}", fileDownloadUrl, fileName, respStr);
                return null;
            }

            JSONObject data = resp.getJSONObject("data");
            String filePath = data == null ? null : data.getStr("filePath");
            if (StrUtil.isBlank(filePath)) {
                log.warn("文件落盘服务缺少data.filePath, url={}, fileName={}, resp={}", fileDownloadUrl, fileName, respStr);
                return null;
            }

            return filePath;
        } catch (Exception e) {
            log.error("文件保存至服务器失败, url={}, originalFilename={}", fileDownloadUrl, originalFilename, e);
            return null;
        }
    }

    private String sanitizeFileName(String originalFilename) {
        if (StrUtil.isBlank(originalFilename)) {
            return originalFilename;
        }
        // 兼容 Windows/Unix 路径：只取最后一段
        int idx1 = originalFilename.lastIndexOf('/');
        int idx2 = originalFilename.lastIndexOf('\\');
        int idx = Math.max(idx1, idx2);
        return idx >= 0 ? originalFilename.substring(idx + 1) : originalFilename;
    }
}
