import Taro from '@tarojs/taro';

// 初始化云开发环境
export const initCloud = async () => {
  if (!Taro.cloud) {
    console.error('请使用 2.2.3 或以上的基础库以使用云能力');
    return;
  }
  
  try {
    await Taro.cloud.init({
      env: 'linefunqueue-xxxxx', // 云开发环境ID，后续替换为实际环境ID
      traceUser: true,
    });
    console.log('云开发初始化成功');
  } catch (error) {
    console.error('云开发初始化失败：', error);
  }
};

// 调用云函数
export const callFunction = async <T = any>(
  name: string,
  data?: any,
): Promise<T> => {
  try {
    const result = await Taro.cloud.callFunction({
      name,
      data,
    });
    return result.result as T;
  } catch (error) {
    console.error(`调用云函数 ${name} 失败：`, error);
    throw error;
  }
};

// 获取集合数据
export const getCollection = <T = any>(
  collectionName: string,
) => {
  return Taro.cloud.database().collection(collectionName) as any;
};

// 上传文件
export const uploadFile = async (
  filePath: string,
  cloudPath: string,
): Promise<string> => {
  try {
    const result = await Taro.cloud.uploadFile({
      cloudPath,
      filePath,
    });
    return result.fileID;
  } catch (error) {
    console.error('上传文件失败：', error);
    throw error;
  }
};

// 下载文件
export const downloadFile = async (fileID: string): Promise<string> => {
  try {
    const result = await Taro.cloud.downloadFile({
      fileID,
    });
    return result.tempFilePath;
  } catch (error) {
    console.error('下载文件失败：', error);
    throw error;
  }
};

// 获取临时文件链接
export const getTempFileURL = async (
  fileID: string | string[],
): Promise<{ fileID: string; tempFileURL: string; status: number; errMsg: string }[]> => {
  try {
    const result = await Taro.cloud.getTempFileURL({
      fileList: Array.isArray(fileID) ? fileID : [fileID],
    });
    return result.fileList;
  } catch (error) {
    console.error('获取临时文件链接失败：', error);
    throw error;
  }
};

// 删除文件
export const deleteFile = async (
  fileID: string | string[],
): Promise<{ fileID: string; status: number; errMsg: string }[]> => {
  try {
    const result = await Taro.cloud.deleteFile({
      fileList: Array.isArray(fileID) ? fileID : [fileID],
    });
    return result.fileList;
  } catch (error) {
    console.error('删除文件失败：', error);
    throw error;
  }
}; 