import { MyBetaModalFormProps, renderTextHelper } from '@/common';
import { MyModal } from '@/components/MyModal';
import { Apis } from '@/gen/Apis';
import { CompanySealsTypeEnum } from '@/gen/Enums';
import { ProCard, ProDescriptions } from '@ant-design/pro-components';
import { Space, Spin } from 'antd';
import { useState } from 'react';

export default function Show(props: MyBetaModalFormProps) {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<any>({});

  const handleOpenModal = () => {
    if (props?.item?.id) {
      setLoading(true);
      Apis.Contract.ContractOthers.Show({ id: props.item.id })
        .then((res) => {
          setData(res?.data || {});
        })
        .finally(() => {
          setLoading(false);
        });
    }
  };
  return (
    <MyModal
      title={props.title || '查看'}
      type={props.item?.type || 'primary'}
      width="800px"
      onOpen={handleOpenModal}
      node={
        <Space direction="vertical" style={{ width: '100%' }}>
          <ProCard extra={props.extra}>
            <Spin spinning={loading}>
              <ProDescriptions column={2}>
                {/* 基本信息 */}
                <ProDescriptions.Item label="申请标题">
                  {data?.title || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="关联项目">
                  {data?.asset_project?.name || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="申请人">
                  {data?.company_employee?.name || '-'}
                  {data?.company_employee?.phone || '-'}
                </ProDescriptions.Item>

                {/* 用印详情 */}
                <ProDescriptions.Item label="申请份数">
                  {data?.copies || data?.number_contract_copies || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="是否用印">
                  {data?.is_sealed ? '是' : '否'}
                </ProDescriptions.Item>

                <ProDescriptions.Item label="用印日期">
                  {data?.use_sealed_date || '-'}
                </ProDescriptions.Item>

                {/* 印章信息 */}
                <ProDescriptions.Item label="印章信息" span={3}>
                  {(data?.seals || data?.seals)?.map(
                    (sealId: string, index: number) => (
                      <Space key={index} style={{ marginRight: 16 }}>
                        {data?.seals?.[index]?.company_supplier?.name || '-'}
                        <renderTextHelper.Tag
                          Enums={CompanySealsTypeEnum}
                          value={data?.seals?.[index]?.type || '-'}
                          key={`seal_id_${index}`}
                        />
                      </Space>
                    ),
                  ) || '-'}
                </ProDescriptions.Item>

                {/* 申请信息 */}
                <ProDescriptions.Item label="简要说明" span={3}>
                  {data?.reason || '-'}
                </ProDescriptions.Item>

                {/* 时间信息 */}
                <ProDescriptions.Item label="最近修改" span={3}>
                  {data?.updated_at || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="附件" span={3}>
                  {data?.files && data.files.length > 0 && (
                    <div style={{ marginBottom: 8 }}>
                      <button
                        onClick={() => {
                          data.files.forEach((file: any, index: number) => {
                            setTimeout(async () => {
                              const fileName = file?.name || `文件${index + 1}`;
                              try {
                                const response = await fetch(file?.url);
                                const blob = await response.blob();
                                const url = window.URL.createObjectURL(blob);
                                const a = document.createElement('a');
                                a.href = url;
                                a.download = fileName;
                                document.body.appendChild(a);
                                a.click();
                                window.URL.revokeObjectURL(url);
                                document.body.removeChild(a);
                              } catch (error) {
                                console.error('下载失败:', error);
                                window.open(file?.url, '_blank');
                              }
                            }, index * 100); // 延迟100ms避免浏览器阻塞
                          });
                        }}
                        style={{
                          padding: '4px 12px',
                          marginBottom: '8px',
                          backgroundColor: '#1890ff',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer',
                        }}
                      >
                        全部下载
                      </button>
                    </div>
                  )}
                  {data?.files?.map((file: any, index: number) => {
                    const fileName = file?.name || `文件${index + 1}`;

                    const handleDownload = async (e: React.MouseEvent) => {
                      e.preventDefault();
                      try {
                        const response = await fetch(file?.url);
                        const blob = await response.blob();
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = fileName;
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(a);
                      } catch (error) {
                        console.error('下载失败:', error);
                        // 如果下载失败，则在新窗口打开
                        window.open(file?.url, '_blank');
                      }
                    };
                    return (
                      <div key={index}>
                        <a href={file?.url} onClick={handleDownload}>
                          {fileName}
                        </a>
                      </div>
                    );
                  }) || '-'}
                </ProDescriptions.Item>
              </ProDescriptions>
            </Spin>
          </ProCard>
        </Space>
      }
    />
  );
}
