// 用户组及权限管理
<script setup lang="ts">

import {Lightning} from "@element-plus/icons-vue";
import type {IAppTableUserGroupVo} from "@/model/table/IAppTableUserGroupVo.ts";
import {computed, onMounted, ref} from "vue";
import UserGroupApi from "@/api/userGroup.ts";
import type {AppServeDataResponse} from "@/interface/api/AppServeDataResponse.ts";
import {AppServeResponseCodeEnum} from "@/constant/enums/AppServeResponseCodeEnum.ts";
import MessageUtils from "@/utils/MessageUtils.ts";
import StringUtils from "@/utils/StringUtils.ts";
import type {TableInstance, TreeInstance} from "element-plus";
import type {IGroupPermission} from "@/interface/page/userGroup/IGroupPermission.ts";
import UserApi from "@/api/user.ts";
import TrueFalseTagStyleFormatter from "@/plugin/formatter/TrueFalseTagStyleFormatter.ts";
import type {IQueryUserGroupPermissionData} from "@/interface/page/userGroup/IQueryUserGroupPermissionData.ts";
import AddUserGroupComponent from "@/components/page/userGroup/AddUserGroupComponent.vue";
import type {AppServeResponse} from "@/interface/api/AppServeResponse.ts";
import EditUserGroupComponent from "@/components/page/userGroup/EditUserGroupComponent.vue";
import type {IUpdatePermissionReq} from "@/interface/page/userGroup/IUpdatePermissionReq.ts";

const userGroupList = ref<IAppTableUserGroupVo[]>([]); // 用户组列表
const selectUserGroup = ref<string | undefined>(''); // 当前选择的用户组
const userGroupTableRef = ref<TableInstance>();
const userPermissionTreeRef = ref<TreeInstance>()
const permissionList = ref<IGroupPermission[]>([]); // 简单用户菜单权限表
const trueFalseTagStyleFormatter = new TrueFalseTagStyleFormatter();
const selectUserPermissionMinorMenu = ref<string[]>([]);
const showAddUserGroup = ref<boolean>(false); // 展示添加用户组的弹窗
const showEditUserGroup = ref<boolean>(false); // 是否展示编辑用户的弹窗
const editUserGroupInfo = ref<IAppTableUserGroupVo>({}); // 传送到编辑用户界面的信息

const selectUserGroupMsg = computed((): string => {
  if(selectUserGroup.value == undefined || StringUtils.isNullOrEmpty(selectUserGroup.value)) {
    return '请先选择用户组';
  }
  return selectUserGroup.value;
})

onMounted(() => {
  queryUserGroup();
  loadThisUserGroupPermission();
});

// 查询用户组
const queryUserGroup = () => {
  userGroupList.value = [];
  const loading = MessageUtils.loading();
  UserGroupApi.queryMinLevelUserGroup().then(res => {
    const response = JSON.parse(JSON.stringify(res.data)) as AppServeDataResponse<IAppTableUserGroupVo[]>;
    if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
      userGroupList.value = response.data ?? [];
    } else {
      MessageUtils.warningMessageBox(response.msg);
    }
  }).catch(() => {}).finally(() => {
    loading.close();
  })
}

// 添加用户组
const addUserGroup = () => {
  showAddUserGroup.value = true;
}

// 编辑用户组
const editUserGroup = () => {
  if(selectUserGroup.value == undefined || StringUtils.isNullOrEmpty(selectUserGroup.value)) {
    MessageUtils.warningMessageBox('请先选择一个用户组，点击用户组表格行以选中');
    return;
  }
  const userGroupInfo = userGroupList.value.filter(item => item.userGroup === selectUserGroup.value);
  if(!userGroupInfo || userGroupInfo.length < 1) {
    MessageUtils.warningMessageBox('数据异常，请重新查询用户组信息');
    return;
  }
  const userGroupInfoElement = userGroupInfo[0];
  editUserGroupInfo.value = {
    userGroup: userGroupInfoElement.userGroup,
    groupName: userGroupInfoElement.groupName,
    groupStatus: userGroupInfoElement.groupStatus,
    groupLevel: userGroupInfoElement.groupLevel,
    createTime: userGroupInfoElement.createTime,
    updateTime: userGroupInfoElement.updateTime,
  }
  showEditUserGroup.value = true;
}

// 删除用户组
const deleteUserGroup = () => {
  if(selectUserGroup.value == undefined || StringUtils.isNullOrEmpty(selectUserGroup.value)) {
    MessageUtils.warningMessageBox('请先选择一个用户组，点击用户组表格行以选中');
    return;
  }
  MessageUtils.confirmMessageBox(`确定删除用户组：${selectUserGroup.value}?`,'高风险操作确认').then(() => {
    UserGroupApi.deleteUserGroup(selectUserGroup.value).then((res) => {
      const response = JSON.parse(JSON.stringify(res.data)) as AppServeResponse;
      if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
        MessageUtils.successMessage('删除成功');
        queryUserGroup();
      } else {
        MessageUtils.warningMessageBox(response.msg);
      }
    }).catch(() => {});
  }).catch(() => {});
}

// 选择表格
const selectedChange = (item: IAppTableUserGroupVo | undefined) => {
  selectUserGroup.value = item?.userGroup;
  selectUserPermissionMinorMenu.value = [];
  userPermissionTreeRef.value!.setCheckedKeys(selectUserPermissionMinorMenu.value, false)
}

// 查询用户组权限
const queryUserGroupPermission = () => {
  if(selectUserGroup.value == undefined || StringUtils.isNullOrEmpty(selectUserGroup.value)) {
    MessageUtils.warningMessageBox('请先选择一个用户组，点击用户组表格行以选中');
    return;
  }
  const loading = MessageUtils.loading();
  loadThisUserGroupPermission(); // 查询自己的菜单权限
  loadUserGroupPermission(selectUserGroup.value); // 查询选中的用户组的权限
  loading.close();
}
// 查询对应用户组的权限
const loadUserGroupPermission = (userGroup: string) => {
  selectUserPermissionMinorMenu.value = [];
  UserGroupApi.queryUserGroupPermission(userGroup).then((res) => {
    const response = JSON.parse(JSON.stringify(res.data)) as AppServeDataResponse<IQueryUserGroupPermissionData[]>;
    if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
      MessageUtils.successMessage('查询成功');
      const groupPermission = response.data;
      groupPermission?.forEach(permission => {
        if(permission.menuLevel == 2 && permission.menuId != undefined) {
          selectUserPermissionMinorMenu.value.push(permission.menuId);
        }
        userPermissionTreeRef.value!.setCheckedKeys(selectUserPermissionMinorMenu.value, false)
      });
    } else {
      MessageUtils.warningMessageBox(response.msg);
    }
  }).catch((err) => {
    MessageUtils.errMessageBox(err);
  })
}

// 加载登录的用户的用户组权限
const loadThisUserGroupPermission = () => {
  if(permissionList.value.length > 0) {
    return;
  }
  UserApi.queryUserMenuPermissionSimpleTree().then(res => {
    permissionList.value = [];
    const response = JSON.parse(JSON.stringify(res.data)) as AppServeDataResponse<IGroupPermission[]>;
    if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
      permissionList.value = response.data ?? [];
    } else {
      MessageUtils.warningMessageBox(response.msg);
    }
  }).catch((err) => {
    MessageUtils.errMessageBox(err);
  })
}

// 保存用户组权限
const saveUserGroupPermission = () => {
  const checkedKeys = userPermissionTreeRef.value?.getCheckedKeys(true);
  let permissionList: string[] = [];
  checkedKeys?.forEach((item) => {
    permissionList.push(item.toString());
  });
  const updateReq: IUpdatePermissionReq = {
    userGroup: selectUserGroup.value,
    permissionList: permissionList,
  }
  MessageUtils.confirmMessageBox(`确定更新用户组：${selectUserGroup.value} 的权限，您选择了：${permissionList?.length} 个权限?`,'高风险操作确认').then(() => {
    UserGroupApi.updateUserGroupPermission(updateReq).then((res) => {
      const response = JSON.parse(JSON.stringify(res.data)) as AppServeResponse;
      if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
        MessageUtils.successMessage('更新成功');
        queryUserGroup();
      } else {
        MessageUtils.warningMessageBox(response.msg);
      }
    }).catch((err) => {
      MessageUtils.errMessageBox(err);
    })
  }).catch(() => {});
}

</script>

<template>
  <div style="margin-left: 10px;margin-top: 10px; width: calc(100vw - 280px);">
    <h3>用户组及用户权限管理</h3>
    <div style="width: calc(100vw - 290px);display: flex">
      <div class="containerCard" style="width: 40vw;">
        <h4 style="margin-left: 10px; margin-bottom: 5px; margin-top: 10px; font-weight: bold">当前用户组</h4>
        <el-text type="success" style="margin-left: 10px;">当前选择的用户组：{{selectUserGroupMsg}}</el-text>
        <el-button-group style="width: 100%; margin-left: 10px; margin-bottom: 10px">
          <el-button type="primary" @click="queryUserGroup">查询/刷新</el-button>
          <el-button type="success" @click="addUserGroup"><el-icon><Lightning /></el-icon>添加用户组</el-button>
          <el-button type="warning" @click="editUserGroup">编辑用户组</el-button>
          <el-button type="danger" @click="deleteUserGroup">删除用户组</el-button>
        </el-button-group>
        <el-table :data="userGroupList" stripe border style="width: 100%" max-height="calc(100vh - 270px)" @current-change="selectedChange"
                  ref="userGroupTableRef" highlight-current-row>
          <el-table-column type="index" width="80" label="序号" align="center" fixed="left" show-overflow-tooltip/>
          <el-table-column prop="userGroup" label="用户组ID" width="180" align="center" fixed="left" show-overflow-tooltip />
          <el-table-column prop="groupName" label="用户组名称" align="center"  width="180" show-overflow-tooltip/>
          <el-table-column prop="groupStatus" label="用户组状态" width="100" align="center" show-overflow-tooltip >
            <template #default="scope">
              <el-tag effect="dark" size="small" round :type="trueFalseTagStyleFormatter.canUseTagStyleFormatter(scope.row.groupStatus).type">
                {{trueFalseTagStyleFormatter.canUseTagStyleFormatter(scope.row.groupStatus).label}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="groupLevel" label="用户组级别" min-width="120" align="center" show-overflow-tooltip/>
        </el-table>
      </div>
      <div class="containerCard" style="width: calc(40vw + 120px);margin-left: 5px">
        <h4 style="margin-left: 10px; margin-bottom: 5px; margin-top: 10px; font-weight: bold">用户组权限 --- 菜单权限</h4>
        <div><el-text type="warning" style="margin-left: 10px;">您没有的权限不会显示在此处，您不能编辑其他用户的您没有的权限</el-text></div>
        <div><el-text type="success" style="margin-left: 10px;">当前正在编辑权限的用户组：{{selectUserGroupMsg}}</el-text></div>
        <el-button-group style="width: 100%;margin-left: 10px; margin-bottom: 10px">
          <el-button type="primary" @click="queryUserGroupPermission">查询/刷新</el-button>
          <el-button type="warning" @click="saveUserGroupPermission">保存设定的权限</el-button>
        </el-button-group>
        <el-scrollbar style="height: calc(100vh - 265px)">
          <el-tree ref="userPermissionTreeRef"
              :data="permissionList"
              show-checkbox
              node-key="menuId"
              default-expand-all
              :props="{children: 'children',label: 'menuId'}"
          >
            <template #default="{ node, data }">
              <el-text type="primary">{{ node.label }} --> {{ data.menuName }}</el-text>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
    </div>
  </div>
<!--  添加用户组的弹窗-->
  <AddUserGroupComponent v-model="showAddUserGroup" @re-loading-table-data="queryUserGroup"/>
<!--  编辑用户组弹窗-->
  <EditUserGroupComponent v-model="showEditUserGroup" @re-loading-table-data="queryUserGroup" :group-data="editUserGroupInfo"/>
</template>

<style scoped>
.containerCard {
  border: #ccc solid 1px;
  border-radius: 4px;
  background-color: #fff;
  height: calc(100vh - 132px);
}


</style>