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

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

import type { Dept, DeptList } from '#/views/workflow/typing';

import { ref } from 'vue';

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

import { notification } from 'ant-design-vue';

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

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

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

function convertToTreeNode(item: Dept): 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: Dept) => convertToTreeNode(item));
}

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

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const deptIds = formApi.form.values.deptIds;
    modalApi.lock();
    try {
      await linkWorkflow({
        workflowId: workflowId.value,
        deptIds,
      });
      notification.success({
        message: '操作成功',
      });
      emits('success');
      await modalApi.close();
    } finally {
      modalApi.lock(false);
    }
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      workflowId.value = modalApi.getData().id;
      const res = await linkDetail(workflowId.value);
      const deptIds = res.map((item: DeptList) => item.deptId);
      await getDeptList();
      // 设置表单字段的值为过滤出的 deptIds
      formApi.form.setValues({
        deptIds,
      });
    }
  },
});

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>
