<template>
  <Modal v-model:open="data.isShowModal" :footer="null" :title="$t('common.assignMenu')" @cancel="_close"
          width="36%">
    <Empty v-show="!data.treeDatas || data.treeDatas.length === 0"/>
    <div v-show="data.treeDatas && data.treeDatas.length > 0">
      <Tree
        v-model:checkedKeys="data.checkedKeys"
        checkable
        :height="233"
        :tree-data="data.treeDatas"
        checkedStrategy="parent">
        <template #title="{ title, key }">
          <span>{{ title }}</span>
        </template>
      </Tree>
    </div>

    <div style="width: 100%;text-align: right;margin-top: 10px">
      <Button @click="_close" :disabled="data.loading">{{ $t('common.cancel') }}</Button>

      <Button type="primary" style="margin-left: 10px" @click="handleSubmit" :loading="data.loading"
               :disabled="data.loading">{{ $t('common.confirm') }}
      </Button>
    </div>
  </Modal>
</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import { $t } from '@vben/locales';
import {Modal, Empty,Tree, Button,message} from 'ant-design-vue';
import {menu,role} from '#/api';
import {toTree} from "#/utils/common";

const data = reactive({
  isShowModal: false,
  checkedKeys: [],
  treeDatas: [],
  role: null,
  loading: false,
})

function handleSubmit() {
  data.loading = true;
  message.info($t('common.processing'));
  let param = {id: data.role.uid, assignIds: data.checkedKeys}
  role.assignMenuPermissionAndRemoveOld(param).then((res) => {
    if (res.error) {
      return;
    }
    message.success($t('common.assignSuccess'));
    _close();
  }).finally(
    () => {
      data.loading = false;
    }
  )
}

function _open(role) {
  data.isShowModal = true;
  data.role = role;
  //查询可见菜单
  menu.queryVisible({}).then(res => {
    if (res.error) {
      return;
    }
    let datas = res.data.map((item) => {
      return {title: item.name, key: item.uid , parentId: item.parentId}
    });
    data.treeDatas = toTree(datas ,'key' ,'parentId');
  })
  //查询角色关联菜单
  menu.queryByRole({roleUid: role.uid}).then(res => {
    if (res.error) {
      return;
    }
    data.checkedKeys = res.data.map((item) => item.uid);
  })
}

function _close() {
  data.isShowModal = false;
  data.treeDatas = [];
  data.checkedKeys = [];
}

//开放方法
defineExpose({_open, _close})
</script>

<style scoped>

</style>