import { MyBetaModalFormProps, renderTextHelper } from '@/common';
import { MyModal } from '@/components/MyModal';
import { Apis } from '@/gen/Apis';
import {
  CooperationSuggestionEnum,
  InfoVerificationEnum,
  QualificationEvaluationEnum,
  RiskLevelEnum,
} 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"
      onOpen={() => {
        if (props?.item?.id) {
          setLoading(true);
          Apis.Company.SupplierFieldReports.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?.investigator || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="调查地点">
                  {data?.location || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="调查起始日期">
                  {data?.investigation_start_date || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="调查结束日期">
                  {data?.investigation_end_date || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="出具日期">
                  {data?.issue_date || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="创建人">
                  {data?.creator_name || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="创建人电话">
                  {data?.creator_phone || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="信息核实">
                  <renderTextHelper.Tag
                    Enums={InfoVerificationEnum}
                    value={data?.info_verification}
                  />
                </ProDescriptions.Item>
                <ProDescriptions.Item label="风险等级">
                  <renderTextHelper.Tag
                    Enums={RiskLevelEnum}
                    value={data?.risk_level}
                  />
                </ProDescriptions.Item>
                <ProDescriptions.Item label="合作建议">
                  <renderTextHelper.Tag
                    Enums={CooperationSuggestionEnum}
                    value={data?.cooperation_suggestion}
                  />
                </ProDescriptions.Item>
                <ProDescriptions.Item label="资质评价">
                  <renderTextHelper.Tag
                    Enums={QualificationEvaluationEnum}
                    value={data?.qualification_evaluation}
                  />
                </ProDescriptions.Item>
                <ProDescriptions.Item label="差异说明" span={2}>
                  {data?.discrepancy_note || '-'}
                </ProDescriptions.Item>

                <ProDescriptions.Item label="综合说明" span={2}>
                  {data?.comprehensive_explanation || '-'}
                </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?.created_at || '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="最近修改">
                  {data?.updated_at || '-'}
                </ProDescriptions.Item>
              </ProDescriptions>
            </Spin>
          </ProCard>
        </Space>
      }
    />
  );
}
