<template>
  <div>
    <el-input
      v-model="treeSearchValue"
      placeholder="请输入权限进行搜索"
      class="mb-1"
      clearable
      @input="onQueryChanged"
    />
    <div class="flex flex-wrap">
      <el-checkbox v-model="isExpandAll" label="展开/折叠" />
    </div>
    <el-tree-v2
      ref="permissionRef"
      show-checkbox
      :data="permissionTreeData"
      :props="treeProps"
      :filter-method="filterMethod"
    >
      <template #default="{ node }">
        <span>{{ transformI18n(node.label) }}</span>
      </template>
    </el-tree-v2>
  </div>
</template>

<script setup lang="ts">
const props = withDefaults(defineProps<{ id: string }>(), {
  id: ""
});
import { transformI18n } from "@/plugins/i18n";
import { ref, onMounted, watch } from "vue";
import { handleTree } from "@/utils/tree";
import { getKeyList } from "@pureadmin/utils";
import { getUserPermissionsAPI, getPermissionListAPI } from "@/api/system";
import { PermissionInfo } from "types/system";

/**树形选择节点 */
const permissionRef = ref(null);
/**树形选择配置 */
const treeProps = {
  value: "id",
  label: "title",
  children: "children",
  disabled: "disabled"
};
const treeSearchValue = ref();
const isExpandAll = ref(false);

/**权限列表 */
const permissions = ref<PermissionInfo[]>([]);
/**权限树 */
const permissionTreeData = ref([]);

/**获取权限列表 */
const getPermissions = async () => {
  const { data } = await getPermissionListAPI({
    page: 1,
    pageSize: 999999
  });
  permissions.value = getKeyList(data.result, "id");
  for (const key in data.result) {
    data.result[key]["disabled"] = true;
  }
  permissionTreeData.value = handleTree(data.result, "id", "parent_id");
};
/**获取用户权限 */
const getUserPermissions = async () => {
  const { data } = await getUserPermissionsAPI(props.id);
  let permission = data;
  permissionRef.value.setCheckedKeys(permission);
};
const onQueryChanged = (query: string) => {
  permissionRef.value!.filter(query);
};
const filterMethod = (query: string, node) => {
  return transformI18n(node.title)!.includes(query);
};
watch(isExpandAll, val => {
  val
    ? permissionRef.value.setExpandedKeys(permissions.value)
    : permissionRef.value.setExpandedKeys([]);
});

onMounted(async () => {
  await getPermissions();
  await getUserPermissions();
  isExpandAll.value = true;
});
function getRef() {
  return permissionRef.value;
}

defineExpose({ getRef });
</script>
