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

import { useAccess } from '@vben/access';
import { useVbenDrawer } from '@vben/common-ui';

import {
  Button,
  Descriptions,
  Modal as AntdModal,
  Space,
  Spin,
  Table,
  Tag,
  message,
} from 'ant-design-vue';

import {
  getChinaErpSyncLogsApi,
  syncChinaOrderToErpApi,
} from '#/views/business/order/api/order-ops';

defineOptions({ name: 'ChinaErpSyncLogDrawer' });

const emit = defineEmits<{
  synced: [];
}>();

const { hasAccessByCodes } = useAccess();

const canSync = computed(() => hasAccessByCodes(['Super Admin']));

const loading = ref(false);
const syncing = ref(false);
const logs = ref<
  Array<{
    content: string;
    content_preview: string;
    created_at: string;
    id: number;
    is_success: number;
    order_id: number;
  }>
>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const orderId = ref(0);
const orderNo = ref('');
const isSyncErp = ref(0);

const showSyncButton = computed(
  () => canSync.value && isSyncErp.value !== 1,
);

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 70 },
  { title: '同步时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
  { title: '结果', dataIndex: 'is_success', key: 'is_success', width: 90 },
  { title: '内容摘要', dataIndex: 'content_preview', key: 'content_preview', ellipsis: true },
  { title: '操作', key: 'action', width: 90 },
];

const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-[70%]',
  placement: 'right',
  showConfirmButton: false,
  showCancelButton: false,
  destroyOnClose: true,
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData<{
        is_sync_erp?: number;
        order_id: number;
        order_no?: string;
      }>();
      orderId.value = data?.order_id ?? 0;
      orderNo.value = data?.order_no ?? '';
      isSyncErp.value = data?.is_sync_erp ?? 0;
      page.value = 1;
      void loadLogs();
    } else {
      logs.value = [];
      total.value = 0;
      orderId.value = 0;
      orderNo.value = '';
      isSyncErp.value = 0;
    }
  },
});

async function loadLogs() {
  if (!orderId.value) {
    return;
  }
  loading.value = true;
  drawerApi.setState({ loading: true });
  try {
    const res = await getChinaErpSyncLogsApi({
      order_id: orderId.value,
      page: page.value,
      pageSize: pageSize.value,
    });
    logs.value = res.list ?? [];
    total.value = res.total ?? 0;
  } finally {
    loading.value = false;
    drawerApi.setState({ loading: false });
  }
}

function onPageChange(p: number, ps: number) {
  page.value = p;
  pageSize.value = ps;
  void loadLogs();
}

function showContentDetail(record: { content: string }) {
  let text = record.content;
  try {
    const parsed = JSON.parse(record.content);
    text = JSON.stringify(parsed, null, 2);
  } catch {
    // keep raw
  }
  AntdModal.info({
    title: '同步详情',
    width: 'min(800px, 96vw)',
    content: text,
    okText: '关闭',
  });
}

function handleSync() {
  if (!orderId.value) {
    return;
  }
  AntdModal.confirm({
    title: '同步到 ERP',
    content: `确认将订单 ${orderNo.value || orderId.value} 同步到 MES？`,
    okText: '确认同步',
    cancelText: '取消',
    onOk: async () => {
      syncing.value = true;
      try {
        await syncChinaOrderToErpApi({ order_id: orderId.value });
        message.success('同步成功');
        isSyncErp.value = 1;
        emit('synced');
        page.value = 1;
        await loadLogs();
      } finally {
        syncing.value = false;
      }
    },
  });
}
</script>

<template>
  <Drawer title="中药 ERP 同步记录">
    <Spin :spinning="loading">
      <div class="flex flex-col gap-4">
        <Descriptions bordered :column="2" size="small">
          <Descriptions.Item label="订单号">
            {{ orderNo || '—' }}
          </Descriptions.Item>
          <Descriptions.Item label="ERP 状态">
            <Tag v-if="isSyncErp === 1" color="green">已同步</Tag>
            <Tag v-else color="red">未同步</Tag>
          </Descriptions.Item>
        </Descriptions>

        <Space>
          <Button
            v-if="showSyncButton"
            :loading="syncing"
            type="primary"
            @click="handleSync"
          >
            同步到 ERP
          </Button>
          <Button :loading="loading" @click="loadLogs">刷新</Button>
        </Space>

        <Table
          :columns="columns"
          :data-source="logs"
          :loading="loading"
          :pagination="{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            showTotal: (t: number) => `共 ${t} 条`,
            onChange: onPageChange,
          }"
          row-key="id"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'is_success'">
              <Tag :color="record.is_success === 0 ? 'success' : 'error'">
                {{ record.is_success === 0 ? '成功' : '失败' }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'action'">
              <Button size="small" type="link" @click="showContentDetail(record)">
                详情
              </Button>
            </template>
          </template>
        </Table>

        <div
          v-if="!loading && logs.length === 0"
          class="py-4 text-center text-gray-500"
        >
          暂无按订单关联的同步记录
        </div>
      </div>
    </Spin>
  </Drawer>
</template>
