import { request } from "@umijs/max";
import { message } from "antd";

export interface SampleVo {
  /**
   * 创建时间
   */
  createTime?: string[];
  /**
   * 页码，从 1 开始", example = "1
   */
  remark?: string;
  /**
   * 样本文件id
   */
  sampleFileId?: number;
  /**
   * 样本格式
   */
  sampleMineType?: string;
  /**
   * 样本名称
   */
  sampleName?: string;
  /**
   * 样本大小
   */
  sampleSize?: string;
  /**
   * 样本时长
   */
  sampleTime?: string[];
}

/**
 * 返回数据
 *
 * PageResultAiSampleRespVO
 */
export interface PageResultAiSampleRespVO {
  /**
   * 数据
   */
  list?: AiSampleRespVO[];
  /**
   * 总量
   */
  total?: number;
}

/**
 * com.tashow.cloud.ai.controller.admin.aisample.vo.AiSampleRespVO
 *
 * AiSampleRespVO
 */
export interface AiSampleRespVO {
  /**
   * 创建时间
   */
  createTime?: string;
  /**
   * 主键
   */
  id?: number;
  /**
   * 样本注释
   */
  remark?: string;
  /**
   * 样本文件id
   */
  sampleFileId?: number;
  /**
   * 样本格式
   */
  sampleMineType?: string;
  /**
   * 样本名称
   */
  sampleName?: string;
  /**
   * 样本大小
   */
  sampleSize?: string;
  /**
   * 样本时长
   */
  sampleTime?: string;
  tags?: { tagName?: string; id?: number }[];
}

export interface SampleReqVo extends PageParam {
  current: number | undefined;
  name?: string;
  status?: number;
}

// 获得样本库分页
export const getSamplePage = async (params: SampleReqVo) => {
  return request("/ai/sample/page", {
    method: "GET",
    params,
  });
};
export const getSample = async (id: number) => {
  return request("/ai/sample/get", {
    method: "GET",
    params: { id },
  });
};

// 创建样本库
export const createSample = (formData: FormData) => {
  return request("/ai/sample/create", {
    method: "POST",
    headers: {
      "Content-Type": "multipart/form-data",
    },
    data: formData,
  });
};

export const updateSample = (params: SampleReqVo) => {
  return request("/ai/sample/update", {
    method: "PUT",
    data: params,
  });
};

export const deleteSample = (id: string) => {
  return request("/ai/sample/delete", {
    method: "DELETE",
    params: { id },
  });
};

//获得样本标签分组库列表
export const getSampleTagGroup = async () => {
  return request("/ai/sampleTagGroup/list", {
    method: "GET",
  });
};

//创建样本标签分组库
export const createSampleTagGroup = (data: { groupName: string }) => {
  return request("/ai/sampleTagGroup/create", {
    method: "POST",
    data,
  });
};

//添加关联标签

export const relateSample = (data: {
  tagId: number[];
  sampleIds: number[];
}) => {
  return request("/ai/sample/relate", {
    method: "PUT",
    data,
  });
};

// 删除管理标签
export const deleteSampleTagRelate = (data: {
  tagId: number[];
  sampleIds: number[];
}) => {
  return request("/ai/sample/deleteRelate", {
    method: "DELETE",
    data,
  });
};

//更新样本库
export const updateSamples = (
  params: { id: number; remark?: string; sampleName?: string }[]
) => {
  return request("/ai/sample/updates", {
    method: "PUT",
    data: params,
  });
};

// 删除样本标签分组库

export const deleteSampleTagGroup = async (id?: number) => {
  return request("/ai/sampleTagGroup/delete", {
    method: "DELETE",
    params: { id },
  });
};

//更新样本标签分组库

export const updateSampleTagGroup = async (params: {
  id: number;
  groupName: string;
}) => {
  return request("/ai/sampleTagGroup/update", {
    method: "PUT",
    data: params,
  });
};

//获得样本标签库分页

export const getSampleTagPage = async (params: {
  groupId?: number;
  pageNo?: number;
  pageSize?: number;
}) => {
  return request("/ai/sampleTag/page", {
    method: "GET",
    params,
  });
};

//创建样本标签库

export const createSampleTag = (data: {
  groupIds: number[];
  tagName: string;
}) => {
  return request("/ai/sampleTag/create", {
    method: "POST",
    data,
  });
};

// 删除样本标签库
export const deleteSampleTag = async (id?: number) => {
  return request("/ai/sampleTag/delete", {
    method: "DELETE",
    params: { id },
  });
};

//更新样本标签库

export const updateSampleTag = async (params: {
  groupIds: number[];
  tagName: string;
}) => {
  return request("/ai/sampleTag/update", {
    method: "PUT",
    data: params,
  });
};

// 下载
export const downloadSample = async (ids: number[]) => {
  return request("/ai/sample/download", {
    method: "GET",
    params: { ids },
    responseType: "blob",
  });
};

export const getGroupListByYagId = async (id: number) => {
  return request("/ai/sampleTag/group-list-by-tag-id", {
    method: "GET",
    params: { tagId: id },
  });
};

export async function downloadZipFile(ids: number[]) {
  try {
    const response = await downloadSample(ids);

    const blob = response; // Blob {size: 3164203, type: 'application/zip'}

    // 验证文件类型
    if (blob.type !== "application/zip" && !blob.type.includes("zip")) {
      console.warn("返回的可能不是 ZIP 文件:", blob.type);
      const downloadUrl = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = downloadUrl;
      link.download = `音频文件_${new Date().getTime()}.wav`; // 设置文件名和后缀
      document.body.appendChild(link);
      link.click();

      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(downloadUrl);
      return;
    }

    // 从响应头获取文件名
    let fileName = "音频文件";
    const contentDisposition =
      response.response?.headers?.["content-disposition"];
    if (!fileName && contentDisposition) {
      const match = contentDisposition.match(
        /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
      );
      if (match?.[1]) {
        fileName = decodeURIComponent(match[1].replace(/['"]/g, ""));
      }
    }

    // 默认文件名
    fileName = fileName || `archive_${new Date().getTime()}.zip`;

    // 创建下载链接
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = downloadUrl;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);

    message.success(
      `下载成功，文件大小：${(blob.size / 1024 / 1024).toFixed(2)} MB`
    );
    return true;
  } catch (error) {
    console.error("下载失败:", error);
    message.error("下载失败，请稍后重试");
    return false;
  }
}
