import OSS from 'ali-oss';
import { getShopSettingByCategory } from '@/api/shop/shopSetting';
import type { ShopSetting } from '@/api/shop/shopSetting/model';

// OSS 配置缓存
let ossConfigCache: {
  baseUrl: string;
  region: string;
  accessKeyId: string;
  accessKeySecret: string;
  bucket: string;
} | null = null;

// 获取 OSS 配置
async function getOssConfig() {
  // 如果已有缓存，直接返回
  if (ossConfigCache) {
    return ossConfigCache;
  }

  try {
    // 从后台设置获取 upload 分类的配置
    const settings = await getShopSettingByCategory('upload');

    // 从设置中找到 OSS 相关配置
    const ossSettings: Partial<Record<string, string>> = {};
    settings.forEach((item: ShopSetting) => {
      if (item.settingKey && item.settingValue) {
        ossSettings[item.settingKey] = item.settingValue;
      }
    });

    // 检查必要的配置
    const region = ossSettings.ossRegion || 'oss-cn-shenzhen';
    const bucket = ossSettings.ossBucket || 'oss-aishangjia';
    const accessKeyId = ossSettings.ossAccessKeyId;
    const accessKeySecret = ossSettings.ossAccessKeySecret;
    const baseUrl = ossSettings.ossBaseUrl || `https://${bucket}.${region}.aliyuncs.com`;

    if (!accessKeyId || !accessKeySecret) {
      throw new Error('OSS 配置不完整，请在后台设置中配置 accessKeyId 和 accessKeySecret');
    }

    // 缓存配置
    ossConfigCache = {
      baseUrl,
      region,
      bucket,
      accessKeyId,
      accessKeySecret
    };

    return ossConfigCache;
  } catch (error) {
    console.error('获取 OSS 配置失败:', error);
    throw error;
  }
}

// 清除 OSS 配置缓存（用于配置更新后重新加载）
export function clearOssConfigCache() {
  ossConfigCache = null;
}

/**
 * 阿里云 OSS 上传
 * @param file 文件对象
 * @param options 上传选项
 */
export const uploadAliOss = async (file: File, options?: Record<string, unknown>) => {
  // 获取 OSS 配置
  const config = await getOssConfig();

  // 构建 OSS 客户端
  const client = new OSS({
    region: config.region,
    accessKeyId: config.accessKeyId,
    accessKeySecret: config.accessKeySecret,
    bucket: config.bucket,
    secure: true // 使用 HTTPS
  });

  const headers = {
    // 指定该Object被下载时的网页缓存行为
    'Cache-Control': 'no-cache',
    // 指定该Object被下载时的名称
    // 指定该Object被下载时的内容编码格式
    'Content-Encoding': 'utf-8',
    // 指定过期时间，单位为毫秒
    Expires: '1000',
    // 指定Object的存储类型
    'x-oss-storage-class': 'Standard',
    // 指定初始化分片上传时是否覆盖同名Object。此处设置为true，表示禁止覆盖同名Object
    'x-oss-forbid-overwrite': 'true'
  };

  // 生成文件名：时间戳 + 原始后缀
  const suffix = file.name.substring(file.name.lastIndexOf('.'));
  const objectName = `uploads/${Date.now()}${suffix}`;

  // 上传文件
  const result = await client.multipartUpload(objectName, file, {
    ...options,
    parallel: 4,
    partSize: 1024 * 1024 * 5,
    headers
  });

  // 设置完整 URL
  result.url = `${config.baseUrl}/${result.name}`;

  return result;
};
