import {
  MyBetaModalFormProps,
  MyButtons,
  MyModalFormProps,
  renderTextHelper,
} from '@/common';

import { Apis } from '@/gen/Apis';
import { RefundsTypeEnum } from '@/gen/Enums';
import BIllInfo from '@/pages/bills/house_bills/modals/BIllInfo';
import {
  BetaSchemaForm,
  ProCard,
  ProDescriptions,
} from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import { Form, Space, Steps } from 'antd';

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

  return (
    <BetaSchemaForm<ApiTypes.Archive.HouseRegisters.Update>
      {...MyModalFormProps.props}
      title={props.title}
      trigger={<MyButtons.Default title="查看" type="primary" />}
      wrapperCol={{ span: 24 }}
      width="600px"
      key={new Date().getTime()}
      form={form}
      onOpenChange={() => {
        if (props?.item?.id) {
          Apis.Approval.ApprovalInstances.Show({
            id: props.item?.model_id,
          }).then((res) => {
            form.setFieldsValue({
              info_display: res?.data,
            });
          });
        }
      }}
      columns={[
        {
          // title: '登记信息',
          dataIndex: 'info_display',
          valueType: 'text',
          renderFormItem: (_, config) => (
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                {/* 退款详情 */}
                {config?.value?.type === 'Refund' && (
                  <ProCard size="small">
                    <ProDescriptions size="small" column={2}>
                      <ProDescriptions.Item label="申请事项" span={2}>
                        {config?.value?.title || '-'}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="账单类型">
                        <renderTextHelper.Tag
                          Enums={RefundsTypeEnum}
                          value={config?.value?.model?.type}
                        />
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="退款金额">
                        <Space>
                          {config?.value?.model?.refund_amount || '-'}
                          元
                          <BIllInfo
                            item={{
                              id: config?.value?.model?.refundable_id,
                              type: 'link',
                            }}
                            title="查看账单"
                          />
                        </Space>
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="付款信息" span={2}>
                        {config?.value?.model?.payer_name || '-'}｜
                        {config?.value?.model?.payer_bank || '-'}｜
                        {config?.value?.model?.payer_account || '-'}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="收款信息" span={2}>
                        {config?.value?.model?.payee_name || '-'}
                        {config?.value?.model?.payee_bank || '-'}
                        {config?.value?.model?.payee_account || '-'}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="申请人" span={2}>
                        {props?.item?.applicant?.name || '-'}:
                        {props?.item?.applicant?.phone || '-'}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="申请时间">
                        {props?.item?.created_at || '-'}
                      </ProDescriptions.Item>
                    </ProDescriptions>
                  </ProCard>
                )}
                {/* 合同详情 */}
                {config?.value?.type === 'Contract' && (
                  <ProCard size="small">
                    <ProDescriptions size="small" column={2}>
                      <ProDescriptions.Item label="合同名称" span={2}>
                        {config?.value?.model?.name || '-'}
                      </ProDescriptions.Item>

                      <ProDescriptions.Item label="合同编号" span={2}>
                        <Space>
                          {config?.value?.model?.code || '-'}
                          <BIllInfo
                            item={{
                              id: config?.value?.model?.refundable_id,
                              type: 'Contract',
                            }}
                            title="查看合同"
                          />
                          <MyButtons.View
                            title="查看"
                            key="configInfo"
                            onClick={() => {
                              navigate(
                                `/contract/contracts/show/${config?.value?.model?.id}`,
                              );
                            }}
                          />
                        </Space>
                      </ProDescriptions.Item>
                      {/* <ProDescriptions.Item label="收支类型">
                        <renderTextHelper.Tag
                          Enums={ContractTemplatesIncomeExpenseTypeEnum}
                          value={config?.value?.model?.income_expense_type}
                        />
                      </ProDescriptions.Item> */}
                      {/* <ProDescriptions.Item label="合同性质">
                        <renderTextHelper.Tag
                          Enums={ContractsContractNatureEnum}
                          value={config?.value?.model?.contract_nature}
                        />
                      </ProDescriptions.Item> */}
                      <ProDescriptions.Item label="合同类型">
                        {config?.value?.model?.contract_type_name || '-'}
                      </ProDescriptions.Item>
                      {/* <ProDescriptions.Item label="结算模式">
                        <renderTextHelper.Tag
                          Enums={ContractsSettlementModeEnum}
                          value={config?.value?.model?.settlement_mode}
                        />
                      </ProDescriptions.Item> */}
                      <ProDescriptions.Item label="合同金额">
                        {config?.value?.model?.total_amount || '-'}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="保证金金额">
                        {config?.value?.model?.deposit_amount || '无'}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="签约主体">
                        {config?.value?.model?.sign_subject || '-'}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="签约部门">
                        {config?.value?.model?.sign_department || '-'}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="关联项目">
                        {config?.value?.model?.project_name || '-'}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="合同对接人">
                        {config?.value?.model?.contract_liaison || '-'}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="合同有效期" span={2}>
                        {config?.value?.model?.start_time?.substring(0, 10)}至
                        {config?.value?.model?.end_time?.substring(0, 10)}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="申请人" span={2}>
                        {props?.item?.applicant?.name || '-'}:
                        {props?.item?.applicant?.phone || '-'}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="申请时间" span={2}>
                        {props?.item?.created_at || '-'}
                      </ProDescriptions.Item>
                      <ProDescriptions.Item label="附件" span={2}>
                        {config?.value?.model?.attachments.map((item: any) => {
                          const handleDownload = async (
                            e: React.MouseEvent,
                          ) => {
                            e.preventDefault();
                            try {
                              const response = await fetch(item.url);
                              const blob = await response.blob();
                              const url = window.URL.createObjectURL(blob);
                              const a = document.createElement('a');
                              a.href = url;
                              a.download = item.name;
                              document.body.appendChild(a);
                              a.click();
                              window.URL.revokeObjectURL(url);
                              document.body.removeChild(a);
                            } catch (error) {
                              console.error('下载失败:', error);
                              // 如果下载失败，则在新窗口打开
                              window.open(item.url, '_blank');
                            }
                          };

                          return (
                            <div key={item.url}>
                              <a href={item.url} onClick={handleDownload}>
                                {item.name}；
                              </a>
                            </div>
                          );
                        })}
                      </ProDescriptions.Item>
                    </ProDescriptions>
                  </ProCard>
                )}
                <ProCard>
                  <ProDescriptions>
                    <ProDescriptions.Item label="审核记录">
                      <Space direction="vertical" style={{ width: '100%' }}>
                        <Steps
                          progressDot
                          direction="vertical"
                          current={config?.value?.approval_records.length}
                          items={config?.value?.approval_records.map(
                            (item: any) =>
                              item?.node_type === 'Approver'
                                ? {
                                    title: `${
                                      item.company_employee?.name || '-'
                                    }-${item?.company_employee?.phone}`,
                                    description: `${
                                      item.status === 'Approved'
                                        ? `通过 - ${item.opinion || '-'} - ${
                                            item.created_at || '-'
                                          }`
                                        : '待审核'
                                    }`,
                                  }
                                : '',
                          )}
                        />
                      </Space>
                    </ProDescriptions.Item>
                  </ProDescriptions>
                </ProCard>
              </div>
            </Space>
          ),
          colProps: { span: 24 },
        },
      ]}
    />
  );
}
