import { MyBetaModalFormProps, renderTextHelper } from '@/common';
import { MyModal } from '@/components/MyModal';
import { Apis } from '@/gen/Apis';
import {
  ContractTemplatesIncomeExpenseTypeEnum,
  ContractTemplatesSourceEnum,
} 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>({});

  return (
    <MyModal
      width="800px"
      title="查看"
      onOpen={() => {
        if (props?.item?.id) {
          setLoading(true);
          Apis.Contract.ContractTemplates.Show({ id: props.item.id })
            .then((res) => {
              setData(res?.data || {});
            })
            .finally(() => {
              setLoading(false);
            });
        }
      }}
      node={
        <Space direction="vertical" style={{ width: '100%' }}>
          <ProCard>
            <Spin spinning={loading}>
              <ProDescriptions column={2} bordered>
                <ProDescriptions.Item label="模板名称">
                  {data?.name}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="模板编号">
                  {data?.code}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="收支类型">
                  <renderTextHelper.Tag
                    Enums={ContractTemplatesIncomeExpenseTypeEnum}
                    value={data?.income_expense_type}
                  />
                </ProDescriptions.Item>
                <ProDescriptions.Item label="合同类型">
                  {data?.contract_type?.name || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="模板来源">
                  <renderTextHelper.Tag
                    Enums={ContractTemplatesSourceEnum}
                    value={data?.source}
                  />
                </ProDescriptions.Item>
                <ProDescriptions.Item label="模板描述" span={2}>
                  {data?.description || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="创建日期">
                  {data?.created_at}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="最近修改">
                  {data?.updated_at}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="模板附件" span={2}>
                  {data?.attachment && data.attachment.length > 0 && (
                    <div style={{ marginBottom: 8 }}>
                      <button
                        onClick={() => {
                          data.attachment.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?.attachment?.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>
      }
    />
  );
}
