<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { SysJobApi } from '#/api/system/sysJob';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { getVxePopupContainer } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { apiAdd, apiUpdate } from '#/api/system/sysJob';
import { getDictOptions } from '#/utils/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

const emit = defineEmits<{
  success: [];
}>();
const formData = ref<SysJobApi.SysJob>();

const formSchema: VbenFormSchema[] = [
  {
    component: 'Select',
    componentProps: {
      allowClear: false,
      getVxePopupContainer,
      options: getDictOptions(DictEnum.SYS_JOB_TYPE),
    },
    fieldName: 'jobType',
    label: '定时任务类型',
    rules: 'selectRequired',
  },
  {
    component: 'Input',
    fieldName: 'cronExpression',
    label: 'cron表达式',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'className',
    label: 'bean或类名称',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'methodName',
    label: '方法名',
    // rules: 'required',
  },
  {
    component: 'Textarea',
    fieldName: 'params',
    label: '参数',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'clientKey',
    label: '系统标识',
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(DictEnum.SYS_JOB_STATUS, true),
    },
    defaultValue: 1,
    fieldName: 'status',
    label: '任务状态',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'remark',
    label: '备注',
    // rules: 'required',
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 120,
  },
  schema: formSchema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [Drawer, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    const data = drawerApi.getData<SysJobApi.SysJob>();
    if (data) {
      formData.value = data;
      await formApi.setValues(formData.value);
    } else {
      formApi.resetForm();
    }
    await markInitialized();
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const data = await formApi.getValues<SysJobApi.SysJob>();
    try {
      await (formData.value?.id
        ? apiUpdate({ id: formData.value.id, ...data })
        : apiAdd(data));
      resetInitialized();
      emit('success');
      drawerApi.close();
    } finally {
      drawerApi.unlock();
    }
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

const getDrawerTitle = computed(() =>
  formData.value?.id ? '修改定时任务' : '新增定时任务',
);
</script>
<template>
  <Drawer class="w-full max-w-[800px]" :title="getDrawerTitle">
    <BasicForm class="mx-4" />
  </Drawer>
</template>
