<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle">
    <BasicForm @register="registerForm" class="!pt-4" />
    <template #footer>
      <a-button @click="closeModal">取消</a-button>
      <a-button type="danger" v-if="eventId" @click="handleDelete">删除</a-button>
      <a-button type="primary" @click="handleSubmit">确定</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import {
    addSchedule,
    updateSchedule,
    getScheduleInfo,
    deleteSchedule,
  } from '/@/api/system/schedule';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { formatToDateTime } from '/@/utils/dateUtil';

  const { t } = useI18n();
  const FormSchema: FormSchema[] = [
    {
      field: 'startDate',
      label: '开始时间',
      component: 'DatePicker',
      required: true,
      colProps: { span: 12 },
      componentProps: {
        format: 'YYYY-MM-DD HH:mm:ss',
        style: { width: '100%' },
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'endDate',
      label: '结束时间',
      component: 'DatePicker',
      colProps: { span: 12 },
      componentProps: {
        format: 'YYYY-MM-DD HH:mm:ss',
        style: { width: '100%' },
        getPopupContainer: () => document.body,
      },
      dynamicRules: ({ model }) => {
        return [
          {
            required: true,
            validator: () => {
              if (formatToDateTime(model.endDate) < formatToDateTime(model.startDate)) {
                return Promise.reject();
              }
              return Promise.resolve();
            },
            message: t('结束时间不能小于开始时间'),
            trigger: 'change',
          },
        ];
      },
    },
    {
      field: 'scheduleContent',
      label: '日程内容',
      component: 'InputTextArea',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入日程内容',
      },
    },
  ];

  const { notification } = useMessage();
  const eventId = ref('');
  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    schemas: FormSchema,
    showActionButtonGroup: false,
    layout: 'vertical',
    rowProps: {
      gutter: 32,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false, destroyOnClose: true, width: 800 });
    eventId.value = data.eventId;

    if (unref(eventId)) {
      const record = await getScheduleInfo(eventId.value);
      setFieldsValue({
        ...record,
      });
    } else {
      setFieldsValue({
        startDate: data.date,
        endDate: data.date,
      });
    }
  });

  const getTitle = computed(() => (!unref(eventId) ? '新增' : '编辑'));

  const handleDelete = async () => {
    await deleteSchedule([eventId.value]);
    closeModal();
    emit('success');
    notification.success({
      message: '删除',
      description: t('成功'),
    });
  };

  const handleSubmit = async () => {
    try {
      const values = await validate();

      setModalProps({ confirmLoading: true });

      if (!unref(eventId)) {
        await addSchedule(values);
        notification.success({
          message: '新增',
          description: t('成功'),
        });
      } else {
        values.id = eventId.value;
        await updateSchedule(values);
        notification.success({
          message: '编辑',
          description: t('成功'),
        });
      }

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  };
</script>
