import request from '@/utils/request';
import { DocumentForm, DocumentQuery, DocumentVO, DocumentMarkForm, DocumentAuditForm, DocumentSubmitForm } from './types';
import { AxiosPromise } from 'axios';
import axios from 'axios';
import FileSaver from 'file-saver';
import { blobValidate } from '@/utils/ruoyi';
import { globalHeaders } from '@/utils/request';

const baseURL = import.meta.env.VITE_APP_BASE_API;

/**
 * 查询文档列表
 * @param query
 */
export const listDocument = (query: DocumentQuery): AxiosPromise<any> => {
  return request({
    url: '/document/document/list',
    method: 'get',
    params: query
  });
};

/**
 * 新增文档
 * @param data
 */
export const addDocument = (data: DocumentForm) => {
  return request({
    url: '/document/document',
    method: 'post',
    data: data
  });
};

/**
 * 标识文档
 * @param data
 */
export const markDocument = (data: DocumentMarkForm) => {
  return request({
    url: '/document/document/mark',
    method: 'put',
    data: data
  });
};

/**
 * 审核文档
 * @param data
 */
export const auditDocument = (data: DocumentAuditForm) => {
  return request({
    url: '/document/document/audit',
    method: 'put',
    data: data
  });
};

/**
 * 递交文档
 * @param data
 */
export const submitDocument = (data: DocumentSubmitForm) => {
  return request({
    url: '/document/document/submit',
    method: 'put',
    data: data
  });
};

/**
 * 确认递交文档
 * @param id 文档ID
 */
export const confirmSubmit = (id: number) => {
  return request({
    url: '/document/document/confirmSubmit',
    method: 'delete',
    params: { id }
  });
};

/**
 * 查询文档审核记录
 * @param query 查询参数
 */
export const listDocumentAuditLog = (query: any): AxiosPromise<any> => {
  return request({
    url: '/document/document/logAudit',
    method: 'get',
    params: query
  });
};

/**
 * 归档文档
 * @param documentId 文档ID
 */
export const filingDocument = (documentId: number) => {
  return request({
    url: '/document/document/filing',
    method: 'put',
    data: { documentId }
  });
};

/**
 * 下载文档（带加载提示和错误处理）
 * @param ossId OSS文件ID
 * @param fileName 文件名（可选，作为备用文件名）
 */
export const downloadDocumentFile = async (ossId: number, fileName?: string) => {
  const loadingInstance = ElLoading.service({
    text: '正在下载文件，请稍候',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    const res = await axios({
      method: 'post',
      url: `${baseURL}/document/document/download/${ossId}`,
      responseType: 'blob',
      headers: globalHeaders()
    });

    const isBlob = blobValidate(res.data);

    if (isBlob) {
      const blob = new Blob([res.data], { type: 'application/octet-stream' });
      // 优先使用后端返回的文件名（包含正确的扩展名）
      const downloadFileName = res.headers['download-filename']
        ? decodeURIComponent(res.headers['download-filename'])
        : (fileName || `download_${ossId}`);
      FileSaver.saveAs(blob, downloadFileName);
      return true;
    } else {
      // 处理错误响应
      const resText = await res.data.text();
      const rspObj = JSON.parse(resText);
      ElMessage.error(rspObj.msg || '下载文件失败');
      return false;
    }
  } catch (error) {
    console.error('下载文件出错:', error);
    ElMessage.error('下载文件出现错误，请联系管理员！');
    return false;
  } finally {
    loadingInstance.close();
  }
};