<script setup lang="ts">
import type { SysDeptApi } from '#/api/auth/dept';
import type { SysRoleApi } from '#/api/auth/role';

import { useVbenModal } from '@vben/common-ui';
import { findGroupParentIds } from '@vben/utils';

import { uniq } from 'lodash-es';

import { useVbenForm } from '#/adapter/form';
import { treeList } from '#/api/auth/dept';
import { authDataScope, getRoleDeptIds } from '#/api/auth/role';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { dataScopeModalSchemas } from './data';

type DeptTreeOption = SysDeptApi.DeptTreeOption;

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

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'vertical',
  schema: dataScopeModalSchemas,
  showDefaultActions: false,
});

// const deptTree = ref<DeptTreeOption[]>([]);
/**
 * 保存部门数据 用于获取祖先节点
 */
let treeData: DeptTreeOption[] = [];
async function setupDeptTree(id: number) {
  const [roleDeptIds, deptTreeList] = await Promise.all([
    getRoleDeptIds(id),
    treeList(),
  ]);
  // const resp = await getRoleDeptIds(id);
  /**
   * 设置部门树数据
   */
  formApi.updateSchema([
    { fieldName: 'deptIds', componentProps: { treeData: deptTreeList } },
  ]);
  /**
   * 设置选中 必须先传递treeData
   * Note: Tree missing follow keys: '1981565541727186945'
   */
  await formApi.setFieldValue('deptIds', roleDeptIds);
  // 设置菜单信息
  treeData = deptTreeList;
}

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      treeData = [];
      return null;
    }
    modalApi.modalLoading(true);

    const data = modalApi.getData<SysRoleApi.Role>();

    setupDeptTree(data.id!);
    // const record = await roleInfo(id);
    await formApi.setValues(data);
    markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // formApi.getValues拿到的是一个readonly对象，不能直接修改，需要cloneDeep
    const data = await formApi.getValues();
    // 不为自定义权限的话 删除部门id
    if (data.dataScope === 5) {
      let { deptIds, deptCheckStrictly } = data;
      // 节点关联 需要拼接上祖级ID(获取的是不带的)
      if (deptCheckStrictly) {
        // 找到所有父级ID
        const parentIds = findGroupParentIds(treeData, deptIds, { id: 'id' });
        // 去重
        deptIds = uniq([...parentIds, ...deptIds]);
      }
      // 赋值
      data.deptIds = deptIds;
    } else {
      data.deptIds = [];
    }
    await authDataScope(data);
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal class="min-h-[600px] w-[550px]" title="分配权限">
    <BasicForm />
  </BasicModal>
</template>
