<template>
    <el-row>
      <el-dialog :title="title" v-model="visible" width="50%" top="5vh" append-to-body>
        <el-form :model="form" label-width="80px" ref="dataScopeRef">  
            <el-form-item label="权限列表">
                <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
                <!-- <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox> -->
                <el-tree
                    class="tree-border"
                    :data="deptOptions"
                    show-checkbox
                    default-expand-all
                    ref="deptRef"
                    node-key="uid"
                    :check-strictly="false"
                    empty-text="加载中，请稍候"
                    :props="{ label: 'permission_name', children: 'children' }"
                ></el-tree>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
            <el-button type="primary" @click="submitDataScope">确 定</el-button>
            <el-button @click="cancelDataScope">取 消</el-button>
            </div>
        </template> 
      </el-dialog>
    </el-row>
</template>
  
  <script setup name="distributionMenu">
  import { listMenu, dataScope ,getRolePermissions} from '@/api/menu.js'; 
  
  const form = ref(
    { 
        permission_uids: [],
        roleId: undefined
    }
  )
 
  const deptRef = ref()
  const dataScopeRef = ref()
  const deptOptions = ref([])
  const deptNodeAll = ref(false)
  const deptExpand = ref(true) 
  const visible = ref(false);  
  const loading = ref(false);
  const title = ref('')
  
  const queryParams = reactive({
    page: 1,
    page_size: 10, 
    userId:'',
    role_name: undefined,
    role_code: undefined
  })
  
  const tableRef = ref();
  const queryFormRef = ref();
  
  const show = async (rows,type) => {  
    title.value = type == 'menu' ? '分配菜单权限' : '分配按钮权限'
    await getList(type); 
    visible.value = true;
    form.value.roleId = rows.uid; 
    const res = await getRolePermissions(rows.uid);
    const checkedKeys = [] 
    if(res?.meta.code == 200){
        const checkedKeys = res.data ? res.data.map(item => item.uid) : [];  
        deptRef.value?.setCheckedKeys(checkedKeys);
    }   
  }
  
  //获取权限树
  const getList = async (type) => {
    loading.value = true; 
    const params = {
        permission_types: type == 'menu' ? '1,3': '2'
    }
    const res = await listMenu(params);
    deptOptions.value = res.data; 
    loading.value = false;
  }

  /** 树权限（全选/全不选） */
const handleCheckedTreeNodeAll = (value) => {
    deptRef.value?.setCheckedNodes(value ? deptOptions.value : []);
}

/** 树权限（展开/折叠）*/
const handleCheckedTreeExpand = (value) => { 
    let treeList = deptOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      if (deptRef.value) {
        deptRef.value.store.nodesMap[treeList[i].uid].expanded = value;
      }
    } 
}

/** 所有菜单节点数据 */
const getDeptAllCheckedKeys = async () => {
  // 目前被选中的菜单节点
  let checkedKeys = deptRef.value?.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = deptRef.value?.getHalfCheckedKeys();
  if (halfCheckedKeys) {
    checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
  }
  return checkedKeys
}

// 提交按钮（数据权限）
const submitDataScope = async () => {  
  if (form.value.roleId) {
    form.value.permission_uids = await getDeptAllCheckedKeys();  
    const res = await dataScope(form.value);
    if (res.meta.code === 200) {
        ElMessage.success(`分配成功`);   
        visible.value = false;
        getList();
    }else {
        ElMessage.error(`分配失败`);
    }
  
  }
}

/** 取消按钮（数据权限）*/
const cancelDataScope = () => {
  dataScopeRef.value?.resetFields(); 
  form.value =    { 
        permission_uids: [],
        roleId: undefined
    };
  visible.value = false;
}
  // 暴露
  defineExpose({
    show,
  });
  </script>
  
  <style scoped></style>
  