package org.hzhub.service;

import cn.hutool.core.util.RandomUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hzhub.common.core.domain.dto.OssDTO;
import org.hzhub.common.core.exception.ServiceException;
import org.hzhub.common.core.service.OssService;
import org.hzhub.common.core.utils.StringUtils;
import org.hzhub.common.core.utils.file.ContentTypeUtil;
import org.hzhub.common.oss.core.OssClient;
import org.hzhub.common.oss.entity.UploadResult;
import org.hzhub.common.oss.factory.OssFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 简易 OSS 服务实现（用于 hzhub-ai）
 * 上传文件至 OSS，文件信息存储至 sys_oss 表
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OssServiceImpl implements OssService {

    private final JdbcTemplate jdbcTemplate;

    @Override
    public OssDTO uploadFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("上传文件不能为空");
        }
        String originalFileName = file.getOriginalFilename();
        String suffix = StringUtils.substring(originalFileName, originalFileName.lastIndexOf("."));
        OssClient storage = OssFactory.instance();
        UploadResult uploadResult;
        try {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix, ContentTypeUtil.getContentType(suffix, file.getContentType()));
        } catch (IOException e) {
            throw new ServiceException("上传失败: " + e.getMessage());
        }

        // 保存到 sys_oss 表
        Long ossId = saveOssRecord(originalFileName, suffix, storage.getConfigKey(), uploadResult, file.getSize(), file.getContentType());
        OssDTO dto = new OssDTO();
        dto.setOssId(ossId);
        dto.setFileName(uploadResult.getFilename());
        dto.setOriginalName(originalFileName);
        dto.setFileSuffix(suffix);
        dto.setUrl(uploadResult.getUrl());
        return dto;
    }

    @Override
    public String selectUrlByIds(String ossIds) {
        if (StringUtils.isBlank(ossIds)) return "";
        List<String> urls = new ArrayList<>();
        for (String idStr : ossIds.split(",")) {
            idStr = idStr.trim();
            if (StringUtils.isBlank(idStr)) continue;
            try {
                String url = jdbcTemplate.queryForObject(
                    "SELECT url FROM sys_oss WHERE oss_id = ?", String.class, Long.parseLong(idStr));
                if (url != null) {
                    urls.add(url);
                }
            } catch (Exception e) {
                log.warn("查询 OSS URL 失败: ossId={}", idStr, e);
            }
        }
        return StringUtils.joinComma(urls);
    }

    @Override
    public List<OssDTO> selectByIds(String ossIds) {
        if (StringUtils.isBlank(ossIds)) return List.of();
        List<OssDTO> result = new ArrayList<>();
        for (String idStr : ossIds.split(",")) {
            idStr = idStr.trim();
            if (StringUtils.isBlank(idStr)) continue;
            try {
                List<OssDTO> rows = jdbcTemplate.query(
                    "SELECT oss_id, file_name, original_name, file_suffix, url FROM sys_oss WHERE oss_id = ?",
                    (rs, rowNum) -> {
                        OssDTO dto = new OssDTO();
                        dto.setOssId(rs.getLong("oss_id"));
                        dto.setFileName(rs.getString("file_name"));
                        dto.setOriginalName(rs.getString("original_name"));
                        dto.setFileSuffix(rs.getString("file_suffix"));
                        dto.setUrl(rs.getString("url"));
                        return dto;
                    },
                    Long.parseLong(idStr));
                if (!rows.isEmpty()) {
                    result.add(rows.get(0));
                }
            } catch (Exception e) {
                log.warn("查询 OSS 记录失败: ossId={}", idStr, e);
            }
        }
        return result;
    }

    private Long saveOssRecord(String originalName, String suffix, String configKey, UploadResult result, long size, String contentType) {
        Long ossId = RandomUtil.randomLong(Long.MAX_VALUE);
        String extJson = String.format("{\"fileSize\":%d,\"contentType\":\"%s\"}", size, contentType);
        jdbcTemplate.update(
            "INSERT INTO sys_oss (oss_id, url, file_name, original_name, file_suffix, service, ext1) VALUES (?, ?, ?, ?, ?, ?, ?)",
            ossId, result.getUrl(), result.getFilename(), originalName, suffix, configKey, extJson);
        return ossId;
    }
}
