import { useNavigate } from "@remix-run/react";
import { useState } from "react";

interface FileInfoProps {
  fileInfo: {
    fileName: string;
    contractNumber: string;
    fileSize?: string;  
    fileFormat?: string;
    pageCount?: number;
    uploadTime?: string;
    uploadUser?: string;
    auditStatus?: number;
    path?: string;
    previousRoute?: string;
  };
  onConfirmResults: () => void;
}

export function FileInfo({ fileInfo, onConfirmResults }: FileInfoProps) {
  const navigate = useNavigate();
  const [isNavigating, setIsNavigating] = useState(false);

  const handleDownloadFile = async () => {
    try {
      const urlBefore = 'http://172.18.0.100:9000/docauditai/';
      const downloadUrl = `${urlBefore}${fileInfo.path}`;
      
      // 使用fetch获取文件内容
      const response = await fetch(downloadUrl);
      if (!response.ok) {
        throw new Error(`下载失败: ${response.status} ${response.statusText}`);
      }
      
      // 将响应转换为Blob
      const blob = await response.blob();
      
      // 创建Blob URL
      const blobUrl = URL.createObjectURL(blob);
      
      // 创建一个隐藏的a标签并点击它
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = blobUrl;
      // 从路径中获取文件名
      const fileName = fileInfo.path?.split('/').pop() || 'document';
      a.download = decodeURIComponent(fileName);
      document.body.appendChild(a);
      a.click();
      
      // 清理
      setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(blobUrl);
      }, 100);
    } catch (error) {
      console.error('下载文件失败:', error);
      alert(`下载文件失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };

  const handleBack = () => {
    // 防抖处理 - 如果已经在导航中，不重复触发
    if (isNavigating) return;
    
    // 设置导航状态为true
    setIsNavigating(true);
    
    // 根据来源页面返回
    const previousRoute = fileInfo.previousRoute || 'documents';
    const returnTo = previousRoute === 'documents' 
      ? "/documents" 
      : previousRoute === 'filesUpload' 
        ? "/files/upload"
        : "/rules-files";
    
    // 立即导航返回
    navigate(returnTo);
  };

  const handleExportReport = () => {
    alert('导出评查报告功能');
  };

  return (
    <div className="mb-4 file-info-header">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-xl font-medium max-w-xl">
            {fileInfo.fileName} 
          </h2>
          <span className="text-xs text-gray-500">
            合同编号：{fileInfo.contractNumber}
          </span>
          {fileInfo.fileSize && (
            <span className="text-xs text-gray-500 ml-2">
            |  {fileInfo.fileSize} | {fileInfo.fileFormat} | {fileInfo.pageCount}页
            </span>
          )}
          {fileInfo.uploadTime && (
            <div className="text-xs text-gray-500 mt-1">
              上传时间：{fileInfo.uploadTime} | 上传用户：{fileInfo.uploadUser}
            </div>
          )}
        </div>
        <div className="flex space-x-3">
          {/* 返回上一级 */}
          <button 
            className="ant-btn ant-btn-default flex items-center"
            onClick={() => handleBack()}
            disabled={isNavigating}
          >
            <i className="ri-arrow-left-line mr-1"></i> {isNavigating ? '返回中...' : '返回'}
          </button>
          <button 
            className="ant-btn ant-btn-default flex items-center"
            onClick={handleDownloadFile}
          >
            <i className="ri-file-download-line mr-1"></i> 下载原文件
          </button>
          {/* <button 
            className="ant-btn ant-btn-default flex items-center"
            onClick={handleExportReport}
          >
            <i className="ri-file-copy-line mr-1"></i> 导出评查报告
          </button> */}
          <button 
            className={`ant-btn ant-btn-primary flex items-center ${fileInfo.auditStatus === 1 ? 'hidden' : ''}`}
            onClick={onConfirmResults}
          >
            <i className="ri-check-double-line mr-1"></i> 确认评查结果
          </button>
        </div>
      </div>
    </div>
  );
} 