<script lang="ts" setup>
/**
 * OA 推送任务管理页（定时 crontab + 主动触发如提现）
 * 列表 Switch 启停；列点击配置消息/机器人/发送用户；编辑弹窗只管任务基础信息
 */
import type { VxeGridListeners } from '#/adapter/vxe-table';

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';

import { updateOaCronTask } from './api';
import FormModalDemo from './components/modal.vue';
import MessageConfigModalDemo from './components/message-config-modal.vue';
import RobotsModalDemo from './components/robots-modal.vue';
import TargetsModalDemo from './components/targets-modal.vue';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';

defineOptions({ name: 'OaCronTask' });

const gridEvents: VxeGridListeners<any> = {};

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

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

const [MessageConfigModal, messageConfigModalApi] = useVbenModal({
  connectedComponent: MessageConfigModalDemo,
});

const [RobotsModal, robotsModalApi] = useVbenModal({
  connectedComponent: RobotsModalDemo,
});

const [TargetsModal, targetsModalApi] = useVbenModal({
  connectedComponent: TargetsModalDemo,
});

/**
 * 打开任务基础信息编辑（启停/封面/跳转/备注）
 */
function openEdit(row: Record<string, any>) {
  formModalApi.setData({ id: row.id, gridApi });
  formModalApi.open();
}

/**
 * 打开消息配置（类型 + payload_schema 内容）
 */
function openMessageConfig(row: Record<string, any>) {
  messageConfigModalApi.setData({ id: row.id, gridApi });
  messageConfigModalApi.open();
}

/**
 * 打开配置机器人弹窗
 */
function openRobots(row: Record<string, any>) {
  robotsModalApi.setData({ id: row.id, gridApi });
  robotsModalApi.open();
}

/**
 * 打开配置发送用户弹窗
 */
function openTargets(row: Record<string, any>) {
  targetsModalApi.setData({ id: row.id, gridApi });
  targetsModalApi.open();
}

/**
 * 列表行内切换启停（立即落库，避免依赖保存按钮）
 */
async function handleEnabledChange(
  row: Record<string, any>,
  checked: boolean | string | number,
) {
  const next = checked === true || checked === 1 || checked === '1' ? 1 : 0;
  const old = Number(row.enabled) === 1 ? 1 : 0;
  if (next === old) {
    return;
  }
  row.enabled = next;
  try {
    await updateOaCronTask({ id: row.id, enabled: next });
    message.success(next === 1 ? '已启用' : '已禁用');
  } catch {
    row.enabled = old;
  }
}
</script>

<template>
  <Page auto-content-height>
    <FormModal />
    <MessageConfigModal />
    <RobotsModal />
    <TargetsModal />
    <Grid>
      <template #task_type="{ row }">
        <Tag :color="Number(row.type) === 2 ? 'orange' : 'blue'">
          {{ Number(row.type) === 2 ? '主动触发' : '定时' }}
        </Tag>
      </template>
      <template #enabled="{ row }">
        <Switch
          :checked="Number(row.enabled) === 1"
          checked-children="开"
          un-checked-children="关"
          @change="(checked) => handleEnabledChange(row, checked)"
        />
      </template>
      <template #card_image="{ row }">
        <Image
          v-if="row.card_image_url"
          :src="row.card_image_url"
          :width="40"
          :height="40"
          style="object-fit: cover; border-radius: 4px"
        />
        <span v-else class="text-gray-400">未配置</span>
      </template>
      <template #message_config="{ row }">
        <a class="cursor-pointer text-primary" @click="openMessageConfig(row)">
          {{ row.active_types_summary || '点击配置' }}
        </a>
      </template>
      <template #robots="{ row }">
        <a class="cursor-pointer text-primary" @click="openRobots(row)">
          {{ row.robot_names || '未配置（点击配置）' }}
        </a>
      </template>
      <template #send_users="{ row }">
        <a class="cursor-pointer text-primary" @click="openTargets(row)">
          {{ row.target_summary || '未配置（点击配置）' }}
        </a>
      </template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              type: 'link',
              onClick: () => openEdit(row),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
