<!--
 * @Author: xiejiang
 * @Date: 2024-12-06 17:31:56
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-08 10:25:04
 * @Description: 
 * Copyright（c）2024 by 好老师教育科技有限公司 All right Reserved.
-->
<template>
  <Drawer
    :drawer-visible="drawerVisible"
    width="480px"
    title="权限克隆"
    :loading="submitLoading"
    confirm-btn-text="保存"
    :cancel-btn="false"
    @confirm="handleConfirm"
    @close="close"
  >
    <t-tree
      :data="menuTree"
      :checkable="true"
      v-model="allChecked"
      expand-all
      value-mode="all"
      activable
      hover
      transition
    >
    </t-tree>
  </Drawer>
</template>

<script setup lang="ts">
import { MessagePlugin } from 'tdesign-vue-next'
import { ResMenuTree } from '@/api/interface/menu/index'
import { getMenuTree, postDataRangeClone } from '@/api/modules/menu/index'

const menuTree = ref<ResMenuTree[]>([])
const drawerVisible = ref(false)
const submitLoading = ref(false)
const loading = ref(false)
const roleId = ref('')
const sourceMenuId = ref('')

const allChecked = ref([])

// 为树形结构的每个节点添加新参数
function newParamToTree(tree: ResMenuTree[]): ResMenuTree[] {
  return tree.map(node => {
    const newNode = {
      ...node,
      children: node?.children || [],
      label: node?.menuName || '-',
      value: node?.menuId
    }
    if (newNode.children && newNode.children.length > 0) {
      newNode.children = newParamToTree(newNode.children)
    }
    return newNode
  })
}

const getData = () => {
  loading.value = true
  getMenuTree({})
    .then(res => {
      menuTree.value = newParamToTree(res.data)
    })
    .finally(() => {
      loading.value = false
    })
}

// 保存权限
const handleConfirm = () => {
  if (allChecked.value.length == 0) {
    MessagePlugin.error('请选择需要克隆的权限！')
    return
  }
  submitLoading.value = true
  postDataRangeClone({
    roleId: roleId.value,
    targetMenuId: allChecked.value,
    sourceMenuId: sourceMenuId.value
  }).finally(() => {
    submitLoading.value = false
    close()
  })
}

const open = (roleID: string, sourceMenuID: string) => {
  roleId.value = roleID
  sourceMenuId.value = sourceMenuID
  drawerVisible.value = true
}

// 关闭抽屉
const close = () => {
  drawerVisible.value = false
}

onMounted(() => {
  getData()
})

defineExpose({
  open
})
</script>

<style lang="less" scoped></style>
