import React, { useState } from 'react';
import { Modal, Form, Spin, message } from 'antd';
import ExtendUpload from '@/utils/ExtendUpload';
import { saveSupplementFile } from '../../../services/bidev';

// 支持的文件格式
const SUPPORTED_FILE_TYPES = {
  'zip': ['.zip'],
  'rar': ['.rar'],
  'pdf': ['.pdf'],
  'word': ['.doc', '.docx'],
  'excel': ['.xls', '.xlsx']
};

const ACCEPT_TYPES = '.zip,.rar,.pdf,.doc,.docx,.xls,.xlsx';

// 文件格式验证函数
const validateFileFormat = (file: File): boolean => {
  const fileName = file.name.toLowerCase();
  const fileExtension = fileName.substring(fileName.lastIndexOf('.'));
  const supportedExtensions = Object.values(SUPPORTED_FILE_TYPES).flat();
  return supportedExtensions.includes(fileExtension);
};

interface SupplementFileUploadProps {
  modalVisible: boolean;
  onCancel: (fileId?: string) => void;
  onOk: (fileId: string) => void;
  fileId?: string;
  readOnly?: boolean;
  recordData?: any;
}

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const modalHeight = window.innerHeight * 96 / 100;

/**
 * 补充评审文件上传组件
 * @param props 
 * @returns 
 */
const SupplementFileUpload: React.FC<SupplementFileUploadProps> = (props) => {
  const { modalVisible, onCancel, onOk, fileId, readOnly, recordData } = props;
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const handleOk = async () => {
    const annexId = form.getFieldValue('annexId');
    const finalFileId = annexId || fileId || '';
    
    if (!readOnly && !finalFileId) {
      message.warning('请先上传文件');
      return;
    }

    setLoading(true);
    try {
      const params = {
        id: recordData?.id,
        supplementReviewFile: finalFileId,
      };
      
      const res = await saveSupplementFile(params);
      if (res.code === 200 && res.success) {
        message.success('补充评审文件保存成功');
        onOk(finalFileId);
      } else {
        message.error(res.message || '保存失败');
      }
    } catch (error) {
      message.error('保存失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    const annexId = form.getFieldValue('annexId');
    onCancel(annexId);
  };

  return (
    <Modal
      destroyOnClose
      title={`${readOnly ? '查看' : '上传'}补充评审文件`}
      visible={modalVisible}
      onCancel={handleCancel}
      onOk={readOnly ? undefined : handleOk}
      okText={readOnly ? undefined : "保存"}
      cancelText="返回"
      okButtonProps={{ hidden: readOnly }}
      style={{ maxHeight: modalHeight }}
      bodyStyle={{ maxHeight: modalHeight - 107, overflowY: 'auto' }}
      centered
    >
      <Spin spinning={loading}>
        <Form name="supplement-file-form" {...layout} form={form}>
          <Form.Item
            name="annexId"
            label="附件"
            extra={readOnly ? null : '支持zip、rar、PDF、Word、Excel格式文件，每个文件最大30MB，限制上传1个文件'}
          >
            <ExtendUpload 
              bid={fileId} 
              btnName="上传" 
              maxSize={30} 
              maxCount={1}
              formatValidator={validateFileFormat}
              uploadProps={{ name: "file", disabled: readOnly, accept: ACCEPT_TYPES }}
            />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
};

export default SupplementFileUpload; 