<script lang="ts" setup>
// @ts-ignore
import { defineEmits, h, onMounted } from 'vue';

// @ts-ignore
import { useVbenDrawer } from '@vben/common-ui';

import dayjs from 'dayjs';
import { ElButton } from 'element-plus';
import { isArray } from 'lodash-es';

// @ts-ignore
import { useVbenForm } from '#/adapter/form';

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

defineOptions({
  name: 'CreateTaskDrawer',
});

const props = defineProps<{
  drawerloing?: boolean;
}>();

const emit = defineEmits<{ submit: [data: any] }>();

// 创建表单，使用不包含全选按钮的基本 schema
const [Form, formApi] = useVbenForm({
  schema: drawerFormSchema(3),
  showDefaultActions: false,
});
onMounted(() => {
  formApi.updateSchema([
    {
      fieldName: 'executorIds',
      suffix: () => {
        // 使用 h 函数创建全选按钮
        return h(
          ElButton,
          {
            onClick: async () => {
              // 导入需要的函数
              const { queryExecutorList } = await import(
                '#/api/schedule/index'
              );
              // 获取所有执行人选项
              const res = await queryExecutorList({ postId: 3 });
              const allValues = res.map((item: any) => item);
              // 使用 formApi 设置字段值
              formApi.setFieldValue('executorIds', allValues);
            },
          },
          '全选',
        );
      },
    },
  ]);
});
const [Drawer, drawerApi] = useVbenDrawer({
  onCancel() {
    drawerApi.close();
  },
  onConfirm: async () => {
    try {
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const formData = await formApi.getValues();
      if (formData.formType === '3') {
        formData.formType = '';
      }
      const { attachments } = formData;
      if (isArray(attachments) && attachments.length > 0) {
        const mapattachments = attachments
          .map((item) => {
            return item.response.data.fileName;
          })
          .join(',');
        formData.attachments = mapattachments;
      }
      formData.startTime = dayjs(formData.startTime).format(
        'YYYY-MM-DD HH:mm:ss',
      );
      formData.endTime = dayjs(formData.endTime).format('YYYY-MM-DD HH:mm:ss');
      emit('submit', formData);
    } catch (error) {
      console.error('提交失败:', error);
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values } = drawerApi.getData<Record<string, any>>();
      if (values) {
        formApi.setValues(values);
      }
    }
  },
  title: '场站新增任务',
});
</script>
<template>
  <Drawer>
    <Form v-loading="drawerloing" />
  </Drawer>
</template>
