<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="30%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, reactive } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './config.form.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { createOrEditSchedueManage, putSchedueConfigManage } from '/@/api/schedue/schedueManager';
  import { useMessage } from '/@/hooks/web/useMessage';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const editId = ref('');
  const [registerForm, { validate, setFieldsValue, resetFields, updateSchema }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
    fieldMapToTime: [['timeZone', ['startTime', 'endTime'], 'YYYY-MM-DD HH:mm:ss']],
  });
  const isViewDetail = ref(false);
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    isViewDetail.value = !!data?.isView;

    if (unref(isViewDetail)) {
      setDrawerProps({ showFooter: true });
      if (unref(isUpdate)) {
        setDrawerProps({ title: '编辑定时任务' });
      } else {
        setDrawerProps({ title: '新增定时任务' });
      }
    } else {
      setDrawerProps({ showFooter: false });
      setDrawerProps({ title: '查看定时任务' });
    }

    if (unref(isUpdate)) {
      //回显基础数据
      editId.value = data.record.id;
      updateSchema({
        field: 'invokeTarget',
        componentProps: {
          disabled: true,
        },
      });
      await setFieldsValue(data.record);
    } else {
      editId.value = '';
      updateSchema({
        field: 'invokeTarget',
        componentProps: {
          disabled: false,
        },
      });
    }
  });
  const getTitle = computed(() => (!unref(isUpdate) ? '新增定时任务' : '编辑定时任务'));
  let postObj: any = reactive({});
  async function handleSubmit() {
    setDrawerProps({ confirmLoading: true });
    try {
      const { createMessage } = useMessage();
      const values = await validate();
      if (!values) return;
      postObj = {
        ...values,
        ...{ id: editId.value !== '' ? editId.value : '' },
      };
      let saveMessage = '添加成功';
      let updateMessage = '修改成功';
      editId.value !== ''
        ? await putSchedueConfigManage(postObj)
        : await createOrEditSchedueManage(postObj);

      closeDrawer();
      emit('success');
      createMessage.success(unref(isUpdate) ? updateMessage : saveMessage);
    } finally {
      setTimeout(() => {
        setDrawerProps({ confirmLoading: false });
      }, 300);
    }
  }
</script>
