import { MyBetaModalFormProps, renderTextHelper } from '@/common';
import { MyModal } from '@/components/MyModal';
import { Apis } from '@/gen/Apis';
import { CreditRatingEnum, RatingOutlookEnum } from '@/gen/Enums';
import { ProCard, ProDescriptions } from '@ant-design/pro-components';
import { Space, Spin, Tag } 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"
      onOpen={() => {
        if (props?.item?.id) {
          setLoading(true);
          Apis.Company.SupplierCreditReports.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="调查机构" span={2}>
                  {data?.investigation_agency || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="出具日期">
                  {data?.issue_date || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="有效期">
                  {data?.expiry_date || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="信用评级">
                  <renderTextHelper.Tag
                    Enums={CreditRatingEnum}
                    value={data?.credit_rating}
                  />
                </ProDescriptions.Item>
                <ProDescriptions.Item label="评级展望">
                  <renderTextHelper.Tag
                    Enums={RatingOutlookEnum}
                    value={data?.rating_outlook}
                  />
                </ProDescriptions.Item>

                <ProDescriptions.Item label="失信执行" span={2}>
                  {data?.has_execution_info ? (
                    <Space>
                      <Tag color="red">是</Tag>
                      {data?.execution_info || '-'}
                    </Space>
                  ) : (
                    <Tag color="green">否</Tag>
                  )}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="法律诉讼" span={2}>
                  {data?.has_lawsuit_record ? (
                    <Space>
                      <Tag color="red">是</Tag>
                      {data?.lawsuit_info || '-'}
                    </Space>
                  ) : (
                    <Tag color="green">否</Tag>
                  )}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="行政处罚" span={2}>
                  {data?.has_admin_penalty ? (
                    <Space>
                      <Tag color="red">是</Tag>
                      {data?.admin_penalty_info || '-'}
                    </Space>
                  ) : (
                    <Tag color="green">否</Tag>
                  )}
                </ProDescriptions.Item>

                <ProDescriptions.Item label="履约能力评价" span={2}>
                  {data?.performance_evaluation || '-'}
                </ProDescriptions.Item>

                <ProDescriptions.Item label="相关文件" span={2}>
                  {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.Item label="创建人">
                  {data?.creator_name || '-'}
                  {data?.creator_phone || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="创建日期">
                  {data?.created_at || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="最近修改">
                  {data?.updated_at || '-'}
                </ProDescriptions.Item>
              </ProDescriptions>
            </Spin>
          </ProCard>
        </Space>
      }
    />
  );
}
