<script setup lang="ts">
import type { Post } from '#/api/system/post/model';

import { defineEmits, ref } from 'vue';

import { useVbenDrawer, useVbenForm } from '@vben/common-ui';

import { addPost, detailPost, updatePost } from '#/api/system/post/post';

import { drawerFormSchema } from './config-data';

const emit = defineEmits<{ reload: [] }>();

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});
const isUpdateRef = ref<boolean>(false);
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { postId, isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate) {
        const postData = await detailPost(postId);
        // 将任务类型字符串转换为数组
        if (postData.taskType) {
          postData.taskType = postData.taskType.split(',');
        }
        await formApi.setValues(postData);
      }
    } catch (error) {
      console.error(error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  onClosed() {
    formApi.resetForm();
  },
  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues<Post>();
      // 将任务类型数组转换为逗号分隔的字符串
      if (Array.isArray(data.taskType)) {
        data.taskType = data.taskType.join(',');
      }
      isUpdateRef.value ? await updatePost(data) : await addPost(data);
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});
</script>

<template>
  <Drawer :title="isUpdateRef ? '编辑' : '新增'">
    <Form />
  </Drawer>
</template>
<style scoped lang="scss">
:deep(.el-input-number) {
  width: 100%;
}
</style>
