<script setup>
import RPC from '@/utils/rpc'
const props = defineProps({
  row: [Object],
  authList: {
    type: Array,
    default: [],
  },
})

const emit = defineEmits(['closed', 'onSuccess'])

const dialogVisible = ref(false)

const isAdd = computed(() => props.type === 'add')

onMounted(() => {
  dialogVisible.value = true
})

const formRef = ref(null)
const formField = ref({})
const formRules = reactive({})

const loading = ref(false)

function closed() {
  emit('closed')
}

const submitForm = async () => {
  const checkedNodes = treeRef.value.getCheckedNodes() || []
  loading.value = true
  RPC.post('/assign_permissions', {
    role_id: props.row.id,
    permission_ids: checkedNodes.map((item) => item.id) || [],
  })
    .then((res) => {
      ElMessage.success('操作成功')
      emit('onSuccess')
      emit('closed')
    })
    .finally(() => {
      loading.value = false
    })
}
const authValue = ref(props.row?.permissions?.map((item) => item.id) || [])

const treeRef = ref()
</script>

<template>
  <el-dialog
    align-center
    title="分配权限"
    width="80%"
    v-model="dialogVisible"
    @closed="closed"
    :close-on-click-modal="false"
  >
    <el-tree
      ref="treeRef"
      :data="authList"
      show-checkbox
      check-strictly
      node-key="id"
      default-expand-all
      :default-checked-keys="authValue"
      :props="{
        children: 'children',
        label: 'name',
      }"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closed"> 取 消 </el-button>
        <el-button type="primary" :loading="loading" @click="submitForm"> 确 定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

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