<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`授权 ${params.role_name}`"
    width="80%"
    @open="openDialog"
    @closed="closeDialog"
    :destroy-on-close="true"
  >
    <el-tree
      ref="treeRef"
      :data="data"
      show-checkbox
      default-expand-all
      node-key="id"
    ></el-tree>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleCommitClick"> 授权 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { ref, watch, reactive } from 'vue';
import { getMenuTree, getRoleMenu, bindRoleMenu } from '~/service/menu';
const treeRef = ref();

const props = defineProps({
  modelValue: Boolean,
  data: Object
});
const emits = defineEmits(['update:modelValue']);

const dialogVisible = ref(props.modelValue);
const data = ref([]);

getMenuTree().then((res) => {
  if (res.code === 0) {
    data.value = res.data;
  }
});

const params = reactive({
  role_guid: '',
  role_name: ''
});
watch(
  () => props.modelValue,
  (v) => {
    console.log('watch props.modelValue', v);
    dialogVisible.value = v;
  }
);

const openDialog = async () => {
  params.role_guid = props.data.role_guid;
  params.role_name = props.data.role_name;
  loadRoleMenu();
};

const closeDialog = () => {
  dialogVisible.value = false;
  emits('update:modelValue', false);
  // props.done();
};

const loadRoleMenu = async () => {
  const { code, data } = await getRoleMenu(params);
  if (code == 0) {
    console.log('load', data);
    treeRef.value?.setCheckedKeys(data, false);
  }
};

const handleCommitClick = async () => {
  const menu_ids = treeRef.value?.getCheckedKeys(false);
  if (menu_ids.length == 0) {
    ElMessage.warning('请选择菜单');
    return;
  }
  const { code } = await bindRoleMenu({
    ...params,
    menu_guid: menu_ids.join()
  });
  if (code == 0) {
    loadRoleMenu();
  }
};
</script>
