<script lang="ts" setup>
/**
 * OA 定时任务「编辑」弹窗：只改任务基础信息
 * 启停 / 全局封面 / 全局跳转 / 备注；消息类型与正文改由「消息配置」列独立弹窗
 */
import { ref } from 'vue';

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

import { Alert, Checkbox, Input, Switch, Textarea, message } from 'ant-design-vue';

import UploadImage from '#/components/form/components/upload-image.vue';
import {
  getOaCronTaskInfo,
  updateOaCronTask,
} from '#/views/system/oa-cron-task/api';

const gridApi = ref();
const loading = ref(false);
const detail = ref<Record<string, any>>({});
const enabled = ref(false);
const cardImageUrls = ref<string[]>([]);
const jumpUrl = ref('');
const syncCardImage = ref(true);
const syncJumpUrl = ref(true);
const remark = ref('');

/**
 * 打开时加载任务基础字段（不含消息类型/payload）
 */
async function loadAll(id: number) {
  loading.value = true;
  try {
    const info = await getOaCronTaskInfo(id);
    detail.value = info || {};
    enabled.value = Number(info?.enabled) === 1;
    const cover = String(info?.card_image_url || '');
    cardImageUrls.value = cover ? [cover] : [];
    jumpUrl.value = String(info?.jump_url || '');
    remark.value = String(info?.remark || '');
  } finally {
    loading.value = false;
  }
}

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 {
      // 不传 active_types / preset_payloads / robot_ids，避免误改其它分弹窗配置
      await updateOaCronTask({
        id,
        enabled: enabled.value ? 1 : 0,
        card_image_url: cardImageUrls.value[0] || '',
        sync_card_image: syncCardImage.value ? 1 : 0,
        jump_url: jumpUrl.value || '',
        sync_jump_url: syncJumpUrl.value ? 1 : 0,
        remark: remark.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 class="cron-edit space-y-4">
      <Alert
        v-if="Number(detail.type) === 2"
        type="warning"
        show-icon
        message="主动触发任务：业务事件发生时推送（如申请提现成功）。启停控制是否推送；消息/机器人/发送人请在列表列配置。"
      />
      <Alert
        v-else
        type="info"
        show-icon
        message="此处只改启停、封面、跳转与备注。消息类型与发送内容请在列表「消息配置」列中编辑。"
      />

      <div class="flex flex-wrap items-center gap-4">
        <div class="flex items-center gap-2">
          <span>启停</span>
          <Switch
            v-model:checked="enabled"
            checked-children="开"
            un-checked-children="关"
          />
        </div>
        <div class="text-gray-500">编码：{{ detail.task_code }}</div>
      </div>

      <div>
        <div class="mb-2 font-medium">全局封面图</div>
        <UploadImage v-model="cardImageUrls" :max-count="1" :multiple="false" />
        <Checkbox v-model:checked="syncCardImage" class="mt-2">
          保存时同步到全部消息类型的图片字段（不改链接）
        </Checkbox>
      </div>

      <div>
        <div class="mb-2 font-medium">全局跳转链接</div>
        <Input
          v-model:value="jumpUrl"
          placeholder="卡片/详情跳转 URL，与封面图分存"
          allow-clear
        />
        <Checkbox v-model:checked="syncJumpUrl" class="mt-2">
          保存时同步到全部消息类型的链接字段（不改图片）
        </Checkbox>
      </div>

      <div>
        <div class="mb-2 font-medium">备注</div>
        <Textarea
          v-model:value="remark"
          :rows="3"
          placeholder="可选备注"
          allow-clear
        />
      </div>
    </div>
  </Modal>
</template>
