<script setup lang="ts">
import type { DataNode } from 'ant-design-vue/es/tree';

import type { Recordable } from '@vben/types';

import { ref } from 'vue';

import { useVbenModal, VbenTree } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { getAllDeptTree } from '#/api';

import { useFormSchema } from '../data';

const emits = defineEmits(['success']);
const formData = ref<string[]>([]);
const deptData = ref<DataNode[]>([]);

function convertToTreeNode(item: any): DataNode {
  return {
    key: item.id,
    title: item.name,
    pid: item.pid || '',
    children: item.children?.map(convertToTreeNode) ?? null,
  };
}

async function getDeptList() {
  const res = await getAllDeptTree(0);
  deptData.value = res.map((item) => convertToTreeNode(item));
}

const [Form] = useVbenForm({
  schema: useFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    // const values = await formApi.getValues();
    if (!formData.value) return;

    modalApi.lock();
    try {
      emits('success');
      modalApi.close();
    } finally {
      modalApi.lock(false);
    }
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      await getDeptList();
    }
  },
});

function getNodeClass(node: Recordable<any>) {
  const classes: string[] = [];
  if (node.value?.type === 'button') {
    classes.push('inline-flex');
    if (node.index % 3 >= 1) {
      classes.push('!pl-0');
    }
  }

  return classes.join(' ');
}
</script>

<template>
  <Modal title="修改工作流">
    <Form class="mx-4">
      <template #deptIds="slotProps">
        <VbenTree
          :tree-data="deptData"
          multiple
          bordered
          :default-expanded-level="2"
          :get-node-class="getNodeClass"
          v-bind="slotProps"
          value-field="key"
          label-field="title"
        >
          <template #node="{ value }">
            <!--              <IconifyIcon v-if="value.meta.icon" :icon="value.meta.icon" />-->
            {{ value.title }}
          </template>
        </VbenTree>
      </template>
    </Form>
  </Modal>
</template>

<style scoped></style>
