<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="600px" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #paramJson="{ model }">
        <CodeEditor
          style="min-height: 200px"
          v-model:value="model.paramJson"
          @change="model.paramJson = $event;"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { defineEmits, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './schema';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { CodeEditor } from "@/components/CodeEditor";
  import * as TaskApi from '@/api/data/taskApi';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const entity = ref();

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    entity.value = data?.record;

    await setFieldsValue({
      ...data.record,
    });
  });

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

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      const {
        ...rest
      } = values;
      const action = !unref(isUpdate) ? TaskApi.add : TaskApi.update;
      const data = !unref(isUpdate)
        ? {
            ...rest,
          }
        : Object.assign({},
          {
            ...unref(entity),
            ...rest,
          },
        );
      await action(data);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style lang="scss" scoped>
@use '@/assets/custom.scss';
</style>
