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

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getOaPlatformList } from '#/views/system/oa-platform/api';

import { formOptions } from './config/search';
import { gridOptions } from './config/table';

/**
 * OA 通知发送日志列表（只读，仅查看）
 */
defineOptions({ name: 'OaNotifyLog' });

/** 平台编码 → 显示名映射 */
const platformMap = ref<Record<string, string>>({});

/**
 * 消息类型 → {名称, Tag 颜色} 映射
 * 顺带补全现有 slot 只处理 text/markdown 两类的不足，覆盖所有 OA 支持的消息类型
 */
const MESSAGE_TYPE_MAP: Record<string, { name: string; color: string }> = {
  text: { name: '文本', color: 'processing' },
  markdown: { name: 'MD', color: 'warning' },
  image: { name: '图片', color: 'cyan' },
  news: { name: '图文', color: 'gold' },
  template_card: { name: '卡片', color: 'purple' },
  link: { name: '链接', color: 'blue' },
  action_card: { name: '动作卡', color: 'magenta' },
  actionCard: { name: '动作卡', color: 'magenta' },
  interactive: { name: '交互', color: 'geekblue' },
  feed_card: { name: '流式', color: 'volcano' },
};

/**
 * 取消息类型展示信息（未命中时回退为「未知」+ 灰色 Tag）
 */
function getMessageTypeInfo(type: string): { name: string; color: string } {
  return MESSAGE_TYPE_MAP[type] ?? { name: type || '未知', color: 'default' };
}

const [Grid] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

/**
 * 加载平台列表用于列展示
 */
async function loadPlatforms() {
  try {
    const list = await getOaPlatformList();
    const rows: any[] = Array.isArray(list) ? list : list?.data || [];
    platformMap.value = rows.reduce(
      (acc, item) => {
        acc[item.platform_code] = item.name;
        return acc;
      },
      {} as Record<string, string>,
    );
  } catch (e) {
    console.error('加载平台列表失败', e);
  }
}

loadPlatforms();

/**
 * 解析 JSON 字符串便于展示
 */
function formatPayload(raw: any): string {
  if (!raw) return '';
  if (typeof raw === 'object') {
    return JSON.stringify(raw, null, 2);
  }
  try {
    const parsed = JSON.parse(String(raw));
    return JSON.stringify(parsed, null, 2);
  } catch {
    return String(raw);
  }
}
</script>

<template>
  <Page auto-content-height title="OA 通知发送日志">
    <Grid>
      <template #toolbar-actions>
        <span class="text-xs text-gray-400">
          日志为只读，记录每次 OA 通知发送的请求和响应（含成功和失败）
        </span>
      </template>
      <template #platform_code="{ row }">
        <Tag v-if="platformMap[row.platform_code]" color="processing">
          {{ platformMap[row.platform_code] }}
        </Tag>
        <span v-else>{{ row.platform_code }}</span>
      </template>
      <!-- 消息类型：按 MESSAGE_TYPE_MAP 映射，覆盖所有 OA 支持的类型 -->
      <template #message_type="{ row }">
        <Tag :color="getMessageTypeInfo(row.message_type).color">
          {{ getMessageTypeInfo(row.message_type).name }}
        </Tag>
      </template>
      <!-- 发送类型：normal 正常业务发送 / test 测试发送 -->
      <template #send_type="{ row }">
        <Tag :color="row.send_type === 'test' ? 'warning' : 'processing'">
          {{ row.send_type === 'test' ? '测试' : '正常' }}
        </Tag>
      </template>
      <template #request_payload="{ row }">
        <Tooltip>
          <template #title>
            <pre class="max-w-[400px] overflow-auto text-xs">{{
              formatPayload(row.request_payload)
            }}</pre>
          </template>
          <span class="cursor-pointer text-blue-500">查看请求体</span>
        </Tooltip>
      </template>
      <template #status="{ row }">
        <Tag :color="row.status === 1 ? 'success' : 'error'">
          {{ row.status === 1 ? '成功' : '失败' }}
        </Tag>
      </template>
      <template #error_msg="{ row }">
        <Tooltip v-if="row.error_msg">
          <template #title>
            <span class="max-w-[400px] inline-block">{{ row.error_msg }}</span>
          </template>
          <span class="cursor-pointer text-red-500 line-clamp-1">
            {{ row.error_msg }}
          </span>
        </Tooltip>
        <span v-else class="text-gray-400">-</span>
      </template>
      <template #toolbar-tools></template>
    </Grid>
  </Page>
</template>
