<script lang="ts" setup>
/**
 * OA 定时任务 — 配置发送用户弹窗（按平台分流）
 * - work_wechat_app：SceneTargetsPanel（个人/客户群 targets）
 * - 其它 webhook 平台：按平台勾选 @ 员工（at_users.admin_ids）
 * 仅展示当前任务已绑机器人所属平台的 Tab
 */
import { computed, ref } from 'vue';

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

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

import UserTagSelect from '#/components/form/components/user-tag-select.vue';
import {
  getOaCronTaskInfo,
  updateOaCronTask,
} from '#/views/system/oa-cron-task/api';
import { getAdminList } from '#/views/system/admin/api';
import { getOaPlatformList } from '#/views/system/oa-platform/api';
import { getOaRobotList } from '#/views/system/oa-robot/api';
import SceneTargetsPanel from '#/views/system/oa-scene/components/scene-targets-panel.vue';

type AtSlot = { admin_ids: number[]; userids: string[] };

const gridApi = ref();
const loading = ref(false);
const detail = ref<Record<string, any>>({});
const targets = ref<any[]>([]);
const selectedAtUsers = ref<Record<string, AtSlot>>({});
const adminList = ref<Array<{ id: number; name: string; avatar?: string }>>(
  [],
);
const platforms = ref<Array<{ platform_code: string; name: string }>>([]);
const activePlatform = ref('');
/** 已绑机器人所属平台编码（决定展示哪些 Tab） */
const boundPlatformCodes = ref<string[]>([]);

const visiblePlatforms = computed(() =>
  platforms.value.filter((p) =>
    boundPlatformCodes.value.includes(p.platform_code),
  ),
);

function isWorkWechatApp(code: string) {
  return code === 'work_wechat_app';
}

/**
 * 规范化详情 at_users（兼容旧纯数组）
 */
function normalizeAtUsers(
  raw: Record<string, any> | undefined,
): Record<string, AtSlot> {
  const result: Record<string, AtSlot> = {};
  for (const [code, val] of Object.entries(raw || {})) {
    if (Array.isArray(val)) {
      result[code] = {
        admin_ids: val.map((id) => Number(id)).filter((id) => id > 0),
        userids: [],
      };
    } else {
      result[code] = {
        admin_ids: ((val as any)?.admin_ids || [])
          .map((id: any) => Number(id))
          .filter((id: number) => id > 0),
        userids: ((val as any)?.userids || [])
          .map((u: any) => String(u))
          .filter((u: string) => u !== ''),
      };
    }
  }
  return result;
}

function adminIdsOf(platformCode: string): number[] {
  return selectedAtUsers.value[platformCode]?.admin_ids || [];
}

function useridsOf(platformCode: string): string[] {
  return selectedAtUsers.value[platformCode]?.userids || [];
}

function setAdminIds(platformCode: string, ids: (string | number)[]) {
  selectedAtUsers.value = {
    ...selectedAtUsers.value,
    [platformCode]: {
      admin_ids: ids.map((n) => Number(n)).filter((n) => n > 0),
      userids: useridsOf(platformCode),
    },
  };
}

function toggleAllAtUsers(platformCode: string, e: any) {
  const checked = !!e?.target?.checked;
  setAdminIds(
    platformCode,
    checked ? adminList.value.map((a) => a.id) : [],
  );
}

/**
 * 打开时加载投递目标、@ 人、已绑机器人平台
 */
async function loadAll(id: number) {
  loading.value = true;
  try {
    const [info, platformList, robotRes, adminRes] = await Promise.all([
      getOaCronTaskInfo(id),
      getOaPlatformList(),
      getOaRobotList({ page: 1, pageSize: 500 }),
      getAdminList({ page: 1, pageSize: 500 }),
    ]);
    detail.value = info || {};
    targets.value = Array.isArray(info?.targets) ? [...info.targets] : [];
    selectedAtUsers.value = normalizeAtUsers(info?.at_users);

    const robotIds = new Set(
      (Array.isArray(info?.robot_ids) ? info.robot_ids : []).map(Number),
    );
    const robotItems = robotRes?.items || robotRes?.data || robotRes || [];
    const list = Array.isArray(robotItems) ? robotItems : [];
    const codes = new Set<string>();
    for (const r of list) {
      if (robotIds.has(Number(r.id))) {
        const code = String(r.platform_code || '');
        if (code) codes.add(code);
      }
    }
    boundPlatformCodes.value = [...codes];

    const rows = Array.isArray(platformList)
      ? platformList
      : platformList?.data || [];
    platforms.value = (Array.isArray(rows) ? rows : [])
      .filter((p: any) => codes.has(String(p.platform_code)))
      .map((p: any) => ({
        platform_code: p.platform_code,
        name: p.name,
      }));
    // 保证绑定了机器人但平台列表缺失时仍有 Tab
    for (const code of codes) {
      if (!platforms.value.some((p) => p.platform_code === code)) {
        platforms.value.push({ platform_code: code, name: code });
      }
    }
    activePlatform.value = platforms.value[0]?.platform_code || '';

    const adminRows = adminRes?.items || adminRes?.data || adminRes || [];
    adminList.value = (Array.isArray(adminRows) ? adminRows : []).map(
      (a: any) => ({
        id: a.id,
        name: a.nick_name || a.name || a.username || String(a.id),
        avatar: a.avatar,
      }),
    );
  } finally {
    loading.value = false;
  }
}

/**
 * 打包提交用的 at_users（仅含有勾选的平台）
 */
function buildAtUsersPayload(): Record<string, AtSlot> {
  const out: Record<string, AtSlot> = {};
  for (const [code, slot] of Object.entries(selectedAtUsers.value)) {
    if (isWorkWechatApp(code)) continue;
    const adminIds = (slot.admin_ids || []).filter((id) => id > 0);
    const userids = (slot.userids || []).filter((u) => u !== '');
    if (adminIds.length === 0 && userids.length === 0) continue;
    out[code] = { admin_ids: adminIds, userids };
  }
  return out;
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  class: 'w-[760px]',
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const id = detail.value?.id;
    if (!id) return;
    modalApi.setState({ loading: true, confirmLoading: true });
    try {
      // 同时保存 targets（应用 API）与 at_users（webhook @ 人）
      await updateOaCronTask({
        id,
        targets: targets.value,
        at_users: buildAtUsersPayload(),
      });
      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 class="space-y-3">
      <Alert
        type="info"
        show-icon
        message="按平台分流：企微应用 API 配置投递人/群；群机器人（企微/钉钉/飞书）配置要 @ 的员工。仅展示已绑定机器人的平台。"
      />
      <div v-if="visiblePlatforms.length === 0" class="text-sm text-gray-400">
        请先在「机器人」列绑定至少一个推送机器人
      </div>
      <Tabs
        v-else
        v-model:active-key="activePlatform"
        type="card"
      >
        <Tabs.TabPane
          v-for="p in visiblePlatforms"
          :key="p.platform_code"
          :tab="p.name"
        >
          <template v-if="isWorkWechatApp(p.platform_code)">
            <div class="mb-2 text-sm text-gray-500">
              企微应用 API 投递目标（个人 / 客户群）
            </div>
            <SceneTargetsPanel
              v-model="targets"
              :admin-list="adminList"
              platform-code="work_wechat_app"
            />
          </template>
          <template v-else>
            <div class="mb-2 flex items-center justify-between">
              <span class="text-sm text-gray-500">
                @ 系统员工
                <span v-if="p.platform_code === 'feishu'" class="text-orange-500">
                  （飞书 webhook 将解析为 OA open_id）
                </span>
              </span>
              <Checkbox
                :checked="
                  adminList.length > 0 &&
                  adminIdsOf(p.platform_code).length === adminList.length
                "
                @change="(e: any) => toggleAllAtUsers(p.platform_code, e)"
              >
                全选
              </Checkbox>
            </div>
            <div v-if="adminList.length === 0" class="text-sm text-gray-400">
              暂无员工可选
            </div>
            <UserTagSelect
              v-else
              :model-value="adminIdsOf(p.platform_code)"
              :options="
                adminList.map((a) => ({
                  value: a.id,
                  label: a.name,
                  avatar: a.avatar || '',
                }))
              "
              placeholder="选择要 @ 的员工（可多选）"
              @update:model-value="(v) => setAdminIds(p.platform_code, v)"
            />
          </template>
        </Tabs.TabPane>
      </Tabs>
    </div>
  </Modal>
</template>
