<script lang="ts" setup>
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Alert, Button, Descriptions, message, Spin } from 'ant-design-vue';

import {
  getStoreBankCardReportDetail,
  migrateStoreBankCardToYiiStore,
  syncStoreBankCardStatusByStore,
} from '../api';
import {
  EPL_TRANSFER_ACCOUNT_TYPE_OPTIONS,
  USE_TYPE_TRANSFER_TEXT,
} from '../config/constants';

const storeId = ref(0);
const storeName = ref('');
const statusInfo = ref<Record<string, any> | null>(null);
const loading = ref(false);
const syncing = ref(false);
const migrating = ref(false);

const hasReportRecord = computed(() => Boolean(statusInfo.value?.id));

const eplStateTextMap: Record<string, string> = {
  '0': '无效',
  '1': '有效',
  '2': '待审核',
  '3': '审核不通过',
};

const eplStateText = computed(() => {
  const state = String(statusInfo.value?.epl_state ?? '');
  return (
    statusInfo.value?.epl_state_text ||
    eplStateTextMap[state] ||
    (hasReportRecord.value ? '未知' : '-')
  );
});

const lastQueryAtText = computed(() => {
  const ts = statusInfo.value?.last_query_at;
  if (!ts) {
    return '-';
  }
  const date = new Date(Number(ts) * 1000);
  return Number.isNaN(date.getTime()) ? '-' : date.toLocaleString();
});

const accountTypeText = computed(() => {
  if (statusInfo.value?.account_type_text) {
    return statusInfo.value.account_type_text;
  }
  const accountType = String(statusInfo.value?.account_type ?? '');
  const option = EPL_TRANSFER_ACCOUNT_TYPE_OPTIONS.find(
    (item) => item.value === accountType,
  );
  return option?.label || '-';
});

async function loadStatus() {
  if (!storeId.value) {
    return;
  }
  loading.value = true;
  try {
    statusInfo.value = await getStoreBankCardReportDetail(storeId.value);
  } catch {
    statusInfo.value = null;
    message.error('查询卡状态失败');
  } finally {
    loading.value = false;
  }
}

async function handleSync() {
  if (!storeId.value) {
    return;
  }
  syncing.value = true;
  try {
    statusInfo.value = await syncStoreBankCardStatusByStore(storeId.value);
    message.success('卡状态已同步');
  } finally {
    syncing.value = false;
  }
}

async function handleMigrateToStore() {
  if (!storeId.value) {
    return;
  }
  if (!hasReportRecord.value) {
    message.warning('暂无报备记录，无法迁移到门店');
    return;
  }
  migrating.value = true;
  try {
    await migrateStoreBankCardToYiiStore({
      store_id: storeId.value,
      report_id: statusInfo.value?.id,
    });
    message.success('银行卡信息已迁移到门店');
  } finally {
    migrating.value = false;
  }
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  showConfirmButton: false,
  cancelText: '关闭',
  onCancel() {
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      statusInfo.value = null;
      return;
    }
    const data = modalApi.getData<Record<string, any>>();
    storeId.value = data?.storeId ?? 0;
    storeName.value = data?.storeName ?? '';
    loadStatus();
  },
});

const modalTitle = computed(() => {
  const prefix = '查看卡状态';
  return storeName.value ? `${prefix} - ${storeName.value}` : prefix;
});
</script>

<template>
  <Modal :title="modalTitle" class="w-[560px]">
    <Spin :spinning="loading">
      <Alert
        v-if="!loading && !statusInfo"
        message="未找到银行卡信息"
        show-icon
        type="warning"
        class="mb-4"
      />
      <Alert
        v-else-if="!loading && statusInfo && !hasReportRecord"
        message="该卡尚未在易票联报备，以下为门店银行卡信息"
        show-icon
        type="info"
        class="mb-4"
      />
      <Descriptions v-if="statusInfo" bordered :column="1" size="small">
        <Descriptions.Item label="报备状态">
          {{ statusInfo.report_status_text || '未报备' }}
        </Descriptions.Item>
        <Descriptions.Item label="易票联状态">
          {{ eplStateText }}
        </Descriptions.Item>
        <Descriptions.Item label="报备卡用途">
          {{ statusInfo.use_type_text || USE_TYPE_TRANSFER_TEXT }}
        </Descriptions.Item>
        <Descriptions.Item label="账户类型">
          {{ accountTypeText }}
        </Descriptions.Item>
        <Descriptions.Item label="开户人">
          {{ statusInfo.bank_user_name || '-' }}
        </Descriptions.Item>
        <Descriptions.Item label="银行卡号">
          {{ statusInfo.bank_card_masked || statusInfo.bank_card || '-' }}
        </Descriptions.Item>
        <Descriptions.Item label="开户行">
          {{ statusInfo.bank_name || '-' }}
        </Descriptions.Item>
        <Descriptions.Item label="联行号">
          {{ statusInfo.bank_no || '-' }}
        </Descriptions.Item>
        <Descriptions.Item label="审核意见">
          {{ statusInfo.audit_remarks || '-' }}
        </Descriptions.Item>
        <Descriptions.Item label="最后查询时间">
          {{ lastQueryAtText }}
        </Descriptions.Item>
      </Descriptions>
    </Spin>
    <div v-if="statusInfo" class="mt-4 flex justify-end gap-2">
      <Button
        v-if="hasReportRecord"
        :loading="migrating"
        @click="handleMigrateToStore"
      >
        迁移到门店
      </Button>
      <Button :loading="syncing" type="primary" @click="handleSync">
        同步卡状态
      </Button>
    </div>
  </Modal>
</template>
