<script lang="ts" setup>
/**
 * 日历待办新增/编辑弹窗
 * 打开时通过 modalApi.setData 传入：
 * - update: 是否编辑态
 * - values: 编辑回填数据（时间戳字段已由本组件转为格式串）
 * - defaultDate: 新建时的默认日期（右键格子带入，默认当天 09:00）
 * - onSaved: 保存/删除成功后的刷新回调（父页面重拉当月待办）
 */
import { ref } from 'vue';

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

import { Button, message, Modal as AntModal } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenForm } from '#/adapter/form';

import { createCalendarTodo, deleteCalendarTodo, updateCalendarTodo } from '../api';
import { todoModalFormProps } from '../config/form';

const isUpdate = ref(false);
const currentId = ref(0);
const onSavedRef = ref<null | (() => void)>(null);

const [Form, formApi] = useVbenForm(todoModalFormProps);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const e = await formApi.validate();
    if (!e.valid) return;
    const values = await formApi.getValues();
    // 时间字段由格式串转秒级时间戳提交，与后端 int 字段对齐
    const payload: Record<string, any> = {
      id: currentId.value || undefined,
      title: values.title,
      content: values.content || '',
      todo_time: values.todo_time ? dayjs(values.todo_time).unix() : 0,
      remind_at: values.remind_at ? dayjs(values.remind_at).unix() : 0,
      remind_channels: values.remind_at ? values.remind_channels || [] : [],
      remind_email: values.remind_email || '',
      remind_phone: values.remind_phone || '',
    };
    modalApi.lock();
    try {
      await (isUpdate.value ? updateCalendarTodo(payload) : createCalendarTodo(payload));
      message.success(isUpdate.value ? '保存成功' : '创建成功');
      onSavedRef.value?.();
      modalApi.close();
    } finally {
      modalApi.unlock();
    }
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formApi.resetForm();
      return;
    }
    const data = (modalApi.getData() || {}) as Record<string, any>;
    isUpdate.value = !!data.update;
    currentId.value = Number(data.values?.id || 0);
    onSavedRef.value = data.onSaved || null;
    formApi.resetForm();
    if (data.update && data.values) {
      const v = data.values;
      formApi.setValues({
        id: v.id,
        title: v.title,
        content: v.content,
        todo_time: v.todo_time ? dayjs.unix(Number(v.todo_time)).format('YYYY-MM-DD HH:mm') : '',
        remind_at:
          Number(v.remind_at) > 0 ? dayjs.unix(Number(v.remind_at)).format('YYYY-MM-DD HH:mm') : '',
        remind_channels: v.remind_channels ? String(v.remind_channels).split(',').filter(Boolean) : [],
        remind_email: v.remind_email || '',
        remind_phone: v.remind_phone || '',
      });
    } else {
      // 新建：右键格子带入日期，默认上午 9 点
      const base = data.defaultDate ? dayjs(data.defaultDate) : dayjs();
      formApi.setValues({
        todo_time: base.hour(9).minute(0).format('YYYY-MM-DD HH:mm'),
        remind_channels: ['notice'],
      });
    }
  },
});

/** 编辑态底部左侧的删除入口：待办属于轻量数据，允许在编辑弹窗内直接删除 */
function handleDelete() {
  if (!currentId.value) return;
  AntModal.confirm({
    title: '删除待办',
    content: '确定删除这条待办吗？删除后不可恢复。',
    okText: '删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      await deleteCalendarTodo({ id: currentId.value });
      message.success('删除成功');
      onSavedRef.value?.();
      modalApi.close();
    },
  });
}
</script>
<template>
  <!-- Markdown 编辑器工具栏需要更宽的容器，弹窗放宽到 640px -->
  <Modal :title="isUpdate ? '编辑待办' : '新建待办'" class="w-[640px]">
    <Form />
    <template #prepend-footer>
      <Button v-if="isUpdate" danger @click="handleDelete">删除</Button>
    </template>
  </Modal>
</template>
