<script lang="ts" setup>
/**
 * OA 定时任务 — 配置推送机器人弹窗
 * 从列表「机器人」列打开；仅保存 robot_ids，不改消息类型/图片
 */
import { ref } from 'vue';

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

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

import {
  getOaCronTaskInfo,
  updateOaCronTask,
} from '#/views/system/oa-cron-task/api';
import { getOaPlatformList } from '#/views/system/oa-platform/api';
import { getOaRobotList } from '#/views/system/oa-robot/api';

const gridApi = ref();
const loading = ref(false);
const detail = ref<Record<string, any>>({});
const robotIds = ref<number[]>([]);
const platforms = ref<Array<{ platform_code: string; name: string }>>([]);
const robotsByPlatform = ref<Record<string, Array<{ id: number; name: string }>>>({});
const activePlatform = ref('');

/**
 * 打开时加载任务已绑机器人与全量机器人列表
 */
async function loadAll(id: number) {
  loading.value = true;
  try {
    const [info, platformList, robotRes] = await Promise.all([
      getOaCronTaskInfo(id),
      getOaPlatformList(),
      getOaRobotList({ page: 1, pageSize: 500 }),
    ]);
    detail.value = info || {};
    robotIds.value = Array.isArray(info?.robot_ids)
      ? info.robot_ids.map(Number)
      : [];

    const rows = Array.isArray(platformList)
      ? platformList
      : platformList?.data || [];
    platforms.value = (Array.isArray(rows) ? rows : []).map((p: any) => ({
      platform_code: p.platform_code,
      name: p.name,
    }));
    if (!activePlatform.value && platforms.value.length) {
      activePlatform.value = platforms.value[0].platform_code;
    }

    const robotItems = robotRes?.items || robotRes?.data || robotRes || [];
    const list = Array.isArray(robotItems) ? robotItems : [];
    const map: Record<string, Array<{ id: number; name: string }>> = {};
    for (const r of list) {
      const code = String(r.platform_code || '');
      if (!map[code]) map[code] = [];
      map[code].push({ id: Number(r.id), name: String(r.name || r.id) });
    }
    robotsByPlatform.value = map;
  } finally {
    loading.value = false;
  }
}

function toggleRobot(id: number, checked: boolean) {
  const set = new Set(robotIds.value);
  if (checked) set.add(id);
  else set.delete(id);
  robotIds.value = [...set];
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  class: 'w-[560px]',
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const id = detail.value?.id;
    if (!id) return;
    modalApi.setState({ loading: true, confirmLoading: true });
    try {
      // 只传 robot_ids，后端未传 targets 时保留原值
      await updateOaCronTask({ id, robot_ids: robotIds.value });
      message.success('机器人配置已保存');
      gridApi.value?.query?.();
      modalApi.close();
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    const data = modalApi.getData<{ id?: number; gridApi?: any }>();
    gridApi.value = data?.gridApi;
    if (data?.id) {
      await loadAll(data.id);
    }
  },
});
</script>

<template>
  <Modal :title="`配置推送机器人：${detail.name || ''}`">
    <div v-if="loading" class="py-8 text-center text-gray-400">加载中…</div>
    <div v-else>
      <Tabs v-if="platforms.length" v-model:active-key="activePlatform" type="card">
        <Tabs.TabPane
          v-for="p in platforms"
          :key="p.platform_code"
          :tab="p.name"
        >
          <div
            v-if="!(robotsByPlatform[p.platform_code] || []).length"
            class="text-sm text-gray-400"
          >
            该平台暂无机器人，请先在「OA机器人管理」添加
          </div>
          <div v-else class="flex flex-col gap-1">
            <Checkbox
              v-for="r in robotsByPlatform[p.platform_code]"
              :key="r.id"
              :checked="robotIds.includes(r.id)"
              @change="(e: any) => toggleRobot(r.id, !!e?.target?.checked)"
            >
              {{ r.name }}
            </Checkbox>
          </div>
        </Tabs.TabPane>
      </Tabs>
      <div v-else class="text-sm text-gray-400">暂无平台数据</div>
    </div>
  </Modal>
</template>
