<template>
  <div>
    <el-tree
      ref="treeRef"
      :data="dataScopeTree"
      show-checkbox
      node-key="id"
      :default-checked-keys="checkedKeys"
      :props="{ label: 'name', children: 'children' }"
      default-expand-all
    />
    <el-button type="primary" style="margin-top: 20px" :loading="loading" @click="saveScope">保存数据范围</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { queryDataScopeTree, queryDataScopeTreeSelected, createDataScopeAuth } from '@/api/data-scope'
import type { ElTree } from 'element-plus'

const props = defineProps<{
  roleId: string
}>()

const treeRef = ref<InstanceType<typeof ElTree>>()
const dataScopeTree = ref<any[]>([])
const checkedKeys = ref<string[]>([])
const loading = ref(false)

async function fetchTree() {
  try {
    const [treeRes, selectedRes] = await Promise.all([
      queryDataScopeTree(),
      queryDataScopeTreeSelected({ roleId: props.roleId })
    ])
    dataScopeTree.value = treeRes.data || []
    checkedKeys.value = selectedRes.data || []
  } catch (error: any) {
    ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  }
}

async function saveScope() {
  const checkedNodes = treeRef.value?.getCheckedNodes(false, true) || []
  const halfCheckedNodes = treeRef.value?.getHalfCheckedNodes() || []
  const scopeIds = [...checkedNodes, ...halfCheckedNodes].map((node: any) => node.id)

  loading.value = true
  try {
    await createDataScopeAuth({ roleId: props.roleId, scopeIds })
    ElMessage.success('保存成功')
  } catch (error: any) {
    ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  if (props.roleId) fetchTree()
})
</script>
