import { MyBetaModalFormProps, MyButtons, renderTextHelper } from '@/common';
import { ContractBillsIncomeExpenseTypeEnum } from '@/gen/Enums';

import { ProCard, ProDescriptions } from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import { Form, Space } from 'antd';

export default function Update(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();
  const navigate = useNavigate();

  return (
    <>
      <Space direction="vertical" style={{ width: '100%' }}>
        <ProCard title="基本信息" size="small">
          <ProDescriptions size="small" column={2}>
            <ProDescriptions.Item label="标的名称" span={2}>
              <Space>
                {props?.item?.model?.name || '-'}
                <MyButtons.View
                  title="查看合同"
                  key="configInfo"
                  onClick={() => {
                    navigate(
                      `/contract/contracts/show/${props?.item?.model?.contracts_id}`,
                    );
                  }}
                />
              </Space>
            </ProDescriptions.Item>

            <ProDescriptions.Item label="支付金额">
              {props?.item?.model?.amount && props?.item?.model?.amount !== '-'
                ? (parseFloat(props?.item?.model?.amount) / 100).toFixed(2)
                : '-'}
              元
            </ProDescriptions.Item>
            <ProDescriptions.Item label="账单变更">
              <renderTextHelper.Tag
                Enums={ContractBillsIncomeExpenseTypeEnum}
                value={props?.item?.model?.cost_type}
              />
            </ProDescriptions.Item>
            <ProDescriptions.Item label="变更金额">
              {props?.item?.model?.cost_amount &&
              props?.item?.model?.cost_amount !== '-'
                ? (parseFloat(props?.item?.model?.cost_amount) / 100).toFixed(2)
                : '-'}
              元
            </ProDescriptions.Item>
            <ProDescriptions.Item label="变更后金额">
              {(() => {
                const amount = props?.item?.model?.amount
                  ? parseFloat(props?.item?.model?.amount) / 100
                  : 0;
                const costAmount = props?.item?.model?.cost_amount
                  ? parseFloat(props?.item?.model?.cost_amount) / 100
                  : 0;
                const costType = props?.item?.model?.cost_type;

                let finalAmount = amount;
                if (costType === 'Increase') {
                  finalAmount = amount + costAmount;
                } else if (costType === 'Decrease') {
                  finalAmount = amount - costAmount;
                }

                return finalAmount >= 0 ? finalAmount.toFixed(2) : '0.00';
              })()}
              元
            </ProDescriptions.Item>
            <ProDescriptions.Item label="申请人" span={2}>
              {props?.item?.applicant_name || '-'}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="申请时间" span={2}>
              {props?.item?.created_at || '-'}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="标的说明" span={2}>
              {props?.item?.model?.completed_description || '-'}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="标的附件" span={2}>
              {props?.item?.model?.completed_attachments &&
                props?.item?.model?.completed_attachments.length > 0 && (
                  <div style={{ marginBottom: 8 }}>
                    <button
                      onClick={() => {
                        props?.item?.model?.completed_attachments.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>
                )}
              {props?.item?.model?.completed_attachments?.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>
        </ProCard>
      </Space>
    </>
  );
}
