<template>
  <ElDrawer ref="elDrawerRef" v-model="drawerVisible" :title="drawerProps.title" v-bind="$attrs" destroy-on-close>
    <template #header="scope">
      <slot name="header" v-bind="scope">
        <div style="display: flex">
          <slot name="title">
            <span style="flex: 1">{{ drawerProps.title }}</span>
          </slot>
        </div>
      </slot>
    </template>
    <el-form label-width="100px" label-suffix=" :" @submit.enter.prevent="handleConfirm">
      <el-form-item>
        <el-checkbox v-model="isExpand" @change="changeExpand"> 展开/折叠 </el-checkbox>
        <el-checkbox v-model="isNodeAll" @change="changeNodeAll"> 全选/全不选 </el-checkbox>
        <el-checkbox v-model="isCheckStrictly"> 父子联动 </el-checkbox>
      </el-form-item>
      <el-form-item label="权限">
        <el-tree
          :data="treeMenus"
          show-checkbox
          ref="treeRef"
          node-key="menuId"
          :default-expand-all="isExpand"
          :check-strictly="!isCheckStrictly"
          :props="treeProps"
          empty-text="加载中，请稍候">
        </el-tree>
      </el-form-item>
    </el-form>
    <template #footer>
      <slot name="footer">
        <ElButton @click="drawerVisible = false">取 消</ElButton>
        <ElButton type="primary" @click="handleConfirm()">确 定</ElButton>
      </slot>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts" name="MenuDrawer">
import { MenuVO } from '@/api/interface/system/menu'
import { RoleVO } from '@/api/interface/system/role'
import RoleApi from '@/api/module/system/role'
import { ResultEnum } from '@/enums/HttpEnum'
import { CheckboxValueType } from 'element-plus'

interface EcoDrawerProps {
  api?: (params: any) => Promise<any> // 调用接口
  title: string // 顶部标题
  row: Partial<RoleVO>
  getTableList?: () => void
}
const treeProps = {
  children: 'children',
  label: 'title',
  value: 'menuId'
}

/**
 * 全部展开/折叠
 * @param value
 */
const changeExpand = (value: CheckboxValueType) => {
  for (const i in treeRef.value!.store.nodesMap) {
    treeRef.value!.store.nodesMap[i].expanded = value
  }
}

/**
 * 全选
 * @param value
 */
const changeNodeAll = (value: CheckboxValueType) => {
  if (value) {
    treeRef.value!.setCheckedNodes(treeMenus.value as any)
  } else {
    treeRef.value!.setCheckedNodes([])
  }
}

const isExpand = ref(true)
const isNodeAll = ref(false)
const isCheckStrictly = ref(true)

const treeRef = ref()
const allMenus = ref<MenuVO[]>([])
const treeMenus = ref<Menu.MenuOptions[]>([])
const hasMenus = ref<string[]>([])

const drawerVisible = ref(false)
const drawerProps = ref<EcoDrawerProps>({
  title: '',
  row: {}
})

// emit
const emit = defineEmits(['submit'])

// 接收父组件传过来的参数
const acceptParams = (params: EcoDrawerProps) => {
  drawerProps.value = params
  drawerVisible.value = true
  getMenu(params.row.roleId || '')
}

/**
 * 获取权限信息
 * @param roleId
 */
const getMenu = (roleId: string) => {
  if (!roleId) return
  RoleApi.getMenu(roleId).then(res => {
    hasMenus.value = res.data.hasMenus
    allMenus.value = res.data.allMenus
    treeMenus.value = res.data.treeMenus
    nextTick(() => {
      console.log(hasMenus.value)
      hasMenus.value.forEach(item => {
        const node = treeRef.value!.getNode(item)
        if (node?.isLeaf) {
          treeRef.value!.setChecked(node, true, false)
        }
      })
    })
  })
}

const handleConfirm = async () => {
  try {
    const checkedKeys = treeRef.value!.getCheckedKeys()
    const halfCheckedKeys = treeRef.value!.getHalfCheckedKeys()
    const { code } = await drawerProps.value.api!({ roleId: drawerProps.value.row.roleId, menuIds: [...checkedKeys, ...halfCheckedKeys] })
    if (code == ResultEnum.SUCCESS) {
      ElMessage.success({ message: `${drawerProps.value.title}成功！` })
      drawerProps.value.getTableList!()
      emit('submit')
      drawerVisible.value = false
    }
  } catch (error) {
    console.log(error)
  }
}

defineExpose({
  acceptParams
})
</script>

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