<script lang="ts" setup>
import type { VxeGridListeners } from '#/adapter/vxe-table';

import { ref } from 'vue';

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

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

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

import { deleteOaRobot } from './api';
import FormModalDemo from './components/modal.vue';
import ChatBindModal from './components/chat-bind-modal.vue';
import TestSendModal from './components/test-send-modal.vue';
import TestResultModal from './components/test-result-modal.vue';
import WebhookModal from './components/webhook-modal.vue';
import AppCredentialModal from './components/app-credential-modal.vue';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';
import { isWorkWechatApp } from './config/form';
import { getOaRobotInfo } from './api';

/**
 * OA 机器人管理列表页
 * 顶部支持按名称/平台编码/状态搜索
 * 操作：新增、编辑（基础信息）、改地址（webhook/secret）、绑定群聊、测试、删除（单个/批量）
 */
defineOptions({ name: 'OaRobot' });

const hasTopTableDropDownActions = ref(false);

/** 平台编码 → 显示名映射，用于表格中渲染平台列 */
const platformMap = ref<Record<string, any>>({});

const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};

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

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: FormModalDemo,
});

const [TestModal, testModalApi] = useVbenModal({
  connectedComponent: TestSendModal,
});

const [TestResultEditModal, testResultModalApi] = useVbenModal({
  connectedComponent: TestResultModal,
});

const [WebhookEditModal, webhookModalApi] = useVbenModal({
  connectedComponent: WebhookModal,
});

const [ChatBindEditModal, chatBindModalApi] = useVbenModal({
  connectedComponent: ChatBindModal,
});

const [AppCredentialEditModal, appCredentialModalApi] = useVbenModal({
  connectedComponent: AppCredentialModal,
});

/**
 * 打开新增/编辑弹窗
 * 编辑时拉详情（含 corp_id/chat_id/members），避免列表 mask/缺字段
 */
const showModal = async (data: any = {}, isUpdate = false) => {
  let values = data;
  if (isUpdate && data?.id) {
    try {
      values = await getOaRobotInfo(data.id);
    } catch (e) {
      console.error('加载机器人详情失败', e);
      values = data;
    }
  }
  formModalApi.setData({
    values,
    update: isUpdate,
    gridApi,
  });
  formModalApi.open();
};

/**
 * 打开行级测试发送弹窗
 * 传入完整 row（含 id、platform_code、name），后端按 id 自动取已加密密钥
 * 注入 onFinished 回调：发送完成后关闭参数弹窗，打开结果弹窗
 *
 * onFinished payload 字段透传给 test-result-modal.vue 的 setData：
 * - results / summary：核心结果数据
 * - robotName / robotId / platformCode：机器人上下文
 * - testContent / testAtAll / testMobiles：测试参数
 * - sentAt：发送完成时间戳（秒）
 */
const openTestModal = (row: any) => {
  testModalApi.setData({
    row,
    onFinished: (payload: any) => {
      // 参数弹窗会在调用 onFinished 前自行关闭，这里只负责打开结果弹窗
      testResultModalApi.setData(payload);
      testResultModalApi.open();
    },
  });
  testModalApi.open();
};

/**
 * 打开「改地址」独立弹窗
 * 仅修改 webhook_url 和 secret，不动其他字段
 */
const openWebhookModal = (row: any) => {
  webhookModalApi.setData({ row, gridApi });
  webhookModalApi.open();
};

/** 打开应用 API「改凭证」弹窗（拉详情拿 agent_id / use_platform_credential） */
const openAppCredentialModal = async (row: any) => {
  let detail = row;
  if (row?.id) {
    try {
      detail = await getOaRobotInfo(row.id);
    } catch (e) {
      console.error('加载机器人凭证详情失败', e);
    }
  }
  appCredentialModalApi.setData({ row: detail, gridApi });
  appCredentialModalApi.open();
};

/**
 * 打开「绑定群聊」独立弹窗
 * 入口：列表「chat_names」列的「未绑定」link 按钮（也支持手动调用）
 * 仅同步机器人-群聊关系，不动其他字段
 */
const openChatBindModal = (row: any) => {
  chatBindModalApi.setData({ row, gridApi });
  chatBindModalApi.open();
};

/**
 * 删除机器人（支持单个和批量）
 */
const deleteApi = (row: any) => {
  let ids: any[] = [];
  if (row) {
    ids.push(row);
  } else {
    ids = gridApi.grid.getCheckboxRecords().map((item: any) => item.id);
  }
  deleteOaRobot({ ids }).then(() => {
    message.success('删除成功!');
    gridApi.query();
  });
};

/**
 * 加载平台列表（用于表格中 platform_code 列展示成中文名）
 */
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;
        return acc;
      },
      {} as Record<string, any>,
    );
  } catch (e) {
    console.error('加载平台列表失败', e);
  }
}

loadPlatforms();
</script>

<template>
  <Page auto-content-height title="OA 机器人管理">
    <FormModal />
    <TestModal />
    <TestResultEditModal />
    <WebhookEditModal />
    <AppCredentialEditModal />
    <ChatBindEditModal />
    <Grid>
      <template #toolbar-actions>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              icon: 'ant-design:plus-outlined',
              onClick: showModal.bind(null),
            },
          ]"
          :drop-down-actions="[
            {
              label: '批量删除',
              icon: 'ant-design:delete-outlined',
              ifShow: hasTopTableDropDownActions,
              popConfirm: {
                title: '确定删除吗？',
                confirm: deleteApi.bind(null, false),
              },
            },
          ]"
        />
      </template>
      <!-- 平台列：渲染成中文平台名 + 图标 -->
      <template #platform_code="{ row }">
        <Tag v-if="platformMap[row.platform_code]" color="processing">
          {{ platformMap[row.platform_code].name }}
        </Tag>
        <span v-else>{{ row.platform_code }}</span>
      </template>
      <!--
        绑定群聊列：
        - 有绑定：直接展示后端拼接好的群聊名称串
        - 未绑定：显示可点击的「未绑定」link 按钮，点击后打开独立绑定弹窗
      -->
      <template #chat_names="{ row }">
        <!-- 应用 API：展示 chatid，不走 N:N 绑定弹窗 -->
        <span v-if="isWorkWechatApp(row.platform_code)">
          {{ row.chat_id || row.chat_names || '未配置群聊' }}
        </span>
        <span v-else-if="row.chat_names">{{ row.chat_names }}</span>
        <TableAction
          v-else
          :actions="[
            {
              label: '未绑定',
              type: 'link',
              size: 'small',
              class: '!px-0',
              onClick: openChatBindModal.bind(null, row),
            },
          ]"
        />
      </template>
      <!-- Webhook / 应用凭证状态 -->
      <template #webhook_status="{ row }">
        <Tag
          v-if="isWorkWechatApp(row.platform_code)"
          :color="row.has_app_credential ? 'success' : 'default'"
        >
          {{ row.has_app_credential ? '应用已配置' : '应用未配置' }}
        </Tag>
        <Tag
          v-else
          :color="row.has_webhook || row.webhook_url ? 'success' : 'default'"
        >
          {{ row.has_webhook || row.webhook_url ? '已配置' : '未配置' }}
        </Tag>
      </template>
      <!-- Secret 状态列 -->
      <template #secret_status="{ row }">
        <Tag :color="row.has_secret || row.secret ? 'success' : 'default'">
          {{ row.has_secret || row.secret ? '已配置' : '未配置' }}
        </Tag>
      </template>
      <!-- 状态列 -->
      <template #status="{ row }">
        <Tag :color="row.status === 1 ? 'success' : 'default'">
          {{ row.status === 1 ? '启用' : '禁用' }}
        </Tag>
      </template>
      <template #toolbar-tools></template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              onClick: showModal.bind(null, row, true),
            },
            {
              label: isWorkWechatApp(row.platform_code) ? '改凭证' : '改地址',
              type: 'link',
              icon: isWorkWechatApp(row.platform_code)
                ? 'ant-design:key-outlined'
                : 'ant-design:link-outlined',
              size: 'small',
              onClick: isWorkWechatApp(row.platform_code)
                ? openAppCredentialModal.bind(null, row)
                : openWebhookModal.bind(null, row),
            },
            {
              label: '测试',
              type: 'link',
              icon: 'ant-design:thunderbolt-outlined',
              size: 'small',
              onClick: openTestModal.bind(null, row),
            },
            {
              label: '删除',
              type: 'link',
              icon: 'ant-design:delete-outlined',
              size: 'small',
              danger: true,
              popConfirm: {
                title: '确定删除吗？',
                confirm: deleteApi.bind(null, row.id),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
