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

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

import { Descriptions, Tag } from 'ant-design-vue';

import { getSyncChinaOrderLogDetail } from '../api';

const data = ref<Record<string, any>>({});
const contentText = computed(() => {
  const c = data.value.content;
  if (c == null) return '（无）';
  try {
    return typeof c === 'string' ? c : JSON.stringify(c, null, 2);
  } catch {
    return String(c);
  }
});

const [Modal, modalApi] = useVbenModal({
  showConfirmButton: false,
  cancelText: '关闭',
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  async onOpenChange(isOpen) {
    if (!isOpen) {
      data.value = {};
      return;
    }
    const payload = modalApi.getData<{ id?: number; values?: any }>();
    const id = Number(payload?.id || payload?.values?.id || 0);
    if (id <= 0) {
      data.value = payload?.values || {};
      return;
    }
    modalApi.setState({ loading: true });
    try {
      const res = await getSyncChinaOrderLogDetail(id);
      data.value = res?.data || res || {};
    } catch {
      data.value = payload?.values || {};
    } finally {
      modalApi.setState({ loading: false });
    }
  },
});
</script>

<template>
  <Modal class="w-[90%] md:w-[720px]" title="同步中药 ERP 日志详情">
    <Descriptions bordered :column="1" size="small">
      <Descriptions.Item label="ID">{{ data.id }}</Descriptions.Item>
      <Descriptions.Item label="订单ID">{{ data.order_id }}</Descriptions.Item>
      <Descriptions.Item label="结果">
        <Tag :color="Number(data.is_success) === 0 ? 'success' : 'error'">
          {{ data.is_success_txt }}
        </Tag>
      </Descriptions.Item>
      <Descriptions.Item label="时间">{{ data.created_at }}</Descriptions.Item>
      <Descriptions.Item label="内容">
        <pre class="max-h-80 overflow-auto whitespace-pre-wrap break-all text-xs">{{ contentText }}</pre>
      </Descriptions.Item>
    </Descriptions>
  </Modal>
</template>
