<template>
  <div class="main-content">
    <div>
      <el-form inline size="small">
        <el-form-item label="选择角色">
          <el-select v-model="roleId" placeholder="请选择角色" @change="fetchRoleMenu">
            <el-option v-for="item in roles" :key="item.id" :label="item.roleCnName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin-top: 20px">
      <el-tree
        ref="treeRef"
        :data="menuTree"
        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="saveAuth">保存授权</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { queryRoleList, queryRoleMenuTreeSelected, createRoleAuth } from '@/api/role'
import type { ElTree } from 'element-plus'

const treeRef = ref<InstanceType<typeof ElTree>>()
const roles = ref<any[]>([])
const roleId = ref('')
const menuTree = ref<any[]>([])
const checkedKeys = ref<string[]>([])
const loading = ref(false)

async function fetchRoles() {
  try {
    const res = await queryRoleList()
    roles.value = res.data || []
  } catch (error: any) {
    ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  }
}

async function fetchRoleMenu(roleIdVal: string) {
  try {
    const res = await queryRoleMenuTreeSelected({ roleId: roleIdVal })
    menuTree.value = (res.data as any)?.menuTree || []
    checkedKeys.value = (res.data as any)?.selectedIds || []
  } catch (error: any) {
    ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  }
}

async function saveAuth() {
  if (!roleId.value) {
    ElMessage.warning('请先选择角色')
    return
  }
  const checkedNodes = treeRef.value?.getCheckedNodes(false, true) || []
  const halfCheckedNodes = treeRef.value?.getHalfCheckedNodes() || []
  const menuIds = [...checkedNodes, ...halfCheckedNodes].map((node: any) => node.id)

  loading.value = true
  try {
    await createRoleAuth({ roleId: roleId.value, menuIds })
    ElMessage.success('授权成功')
  } catch (error: any) {
    ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  } finally {
    loading.value = false
  }
}

fetchRoles()
</script>
