<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 isUpdate = ref(false);

const formSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'id',
    label: 'id',
  },
  {
    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>();
    isUpdate.value = !!data?.id;
    if (isUpdate.value) {
      await formApi.setValues(data);
    } 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 (isUpdate.value ? apiUpdate(data) : apiAdd(data));
      resetInitialized();
      emit('success');
      drawerApi.close();
    } finally {
      drawerApi.unlock();
    }
  }
}

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

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