<template>
  <Modal
    :options="getModalOptions"
    :on-positive-click="handleConfirm"
    :on-negative-click="handleClose"
    :on-close="handleClose"
  >
    <template #Context>
      <n-tree
        block-line
        cascade
        checkable
        :data="allTreeData"
        key-field="id"
        label-field="title"
        :default-expand-all="true"
        :default-checked-keys="checkedTreeData"
        @update:checked-keys="handleCheckTree"
      />
    </template>
  </Modal>
</template>
<script>
import { defineComponent, computed, onBeforeMount, reactive, toRefs } from 'vue'
import { getRolePermission, savePermission } from '@/api/system/role/index'
import Modal from '@/components/Modal/index.vue'
import { toTreeData } from '@/utils/handleData.js'
export default defineComponent({
  name: 'ConfigModal',
  components: { Modal },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {}
    }
  },
  emits: {
    'update:visible': null,
    'reload': null
  },
  setup(props, { emit }) {
    const data = reactive({
      menuIds: [],
      checkedTreeData: [],
      allTreeData: []
    })
    const getModalOptions = computed(() => {
      return {
        title: '权限分配',
        show: props.visible,
        negativeText: '取消',
        positiveText: '确认'
      }
    })
    onBeforeMount(() => {
      getMenuByRoleId()
    })

    // 获取当前角色的权限菜单列表
    async function getMenuByRoleId() {
      const res = await getRolePermission(props.data.id)
      data.allTreeData = toTreeData(res.data, 'id', 'pid', 'children')
      const checkedArr = res.data
      if (checkedArr.length) {
        checkedArr.forEach((item) => {
          if (item.checked) {
            data.checkedTreeData.push(item.id)
          }
        })
      }
      data.menuIds = data.checkedTreeData
    }

    // 勾选节点
    function handleCheckTree(keys) {
      data.menuIds = keys
    }

    function handleConfirm() {
      savePermission({ roleId: props.data.id, menuIds: data.menuIds }).then(res => {
        if (res.code === 0) {
          emit('reload')
          handleClose()
        }
      }).catch(e => {
        console.log(e)
      })
    }

    /* 关闭弹窗 */
    const handleClose = () => {
      emit('update:visible', false)
    }

    return {
      ...toRefs(data),
      getModalOptions,
      handleCheckTree,
      handleConfirm,
      handleClose
    }
  }
})
</script>
