// 用户组及权限管理
<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";
import {menuStore} from "@/stores/menu.ts";
import type {IBaseMenuPermissionVo} from "@/model/table/IBaseMenuPermissionVo.ts";
import type {IGroupOperationPermission} from "@/interface/page/userGroup/IGroupOperationPermission.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;
})
const menuStoreInstance = menuStore();

onMounted(() => {
  queryUserGroup(); // 查询用户组
  getOperationPermission(); // 获取操作权限  ---- 下面一行获取用户组权限将在此方法执行完毕后调用
  //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);
  queryUserGroupPermission();
}

// 查询用户组权限
const queryUserGroupPermission = () => {
  if(selectUserGroup.value == undefined || StringUtils.isNullOrEmpty(selectUserGroup.value)) {
    return;
  }
  const loading = MessageUtils.loading();
  selectUserPermissionMinorMenu.value = [];
  loadThisUserGroupPermission(); // 查询自己的菜单权限
  getUserGroupOperationPermission(selectUserGroup.value); // 获取选中的用户组操作权限
  loadUserGroupPermission(selectUserGroup.value); // 查询选中的用户组的权限
  loading.close();
}

// 获取操作权限
const getUserGroupOperationPermission = (userGroup: string) => {
  UserGroupApi.queryUserGroupOperationPermission(userGroup).then(res => {
    const response = JSON.parse(JSON.stringify(res.data)) as AppServeDataResponse<IGroupOperationPermission[]>;
    if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
      const operationPermissionList: IGroupOperationPermission[] = response.data ?? [];
      for (let operationPermissionItem of operationPermissionList) {
        if(operationPermissionItem.permissionId != undefined) {
          selectUserPermissionMinorMenu.value.push(operationPermissionItem.permissionId);
        }
      }
      userPermissionTreeRef.value!.setCheckedKeys(selectUserPermissionMinorMenu.value, false);
    } else {
      MessageUtils.warningMessageBox(response.msg);
    }
  }).catch(() => {});
}

// 查询对应用户组的权限
const loadUserGroupPermission = (userGroup: string) => {
  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 => {
        const operationPermission = menuStoreInstance.getOperationPermission();
        if(permission.menuLevel == 2 && permission.menuId != undefined && !operationPermission.some(item => item.menuId == permission.menuId)) {
          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) {
      const menuPermission = response.data ?? [];
      const operationPermission = menuStoreInstance.getOperationPermission();
      menuPermission.forEach(menuPermission => {
        menuPermission.children?.forEach(minorMenu => {
          const iBaseMenuPermissionVos = operationPermission.filter(item => item.menuId == minorMenu.menuId);
          minorMenu.children = [];
          iBaseMenuPermissionVos.forEach(item => {
            minorMenu.children?.push({
              menuId: item.permissionId,
              menuName: item.permissionName,
            });
          })
        });
      })
      permissionList.value = menuPermission ?? [];
    } else {
      MessageUtils.warningMessageBox(response.msg);
    }
  }).catch((err) => {
    MessageUtils.errMessageBox(err);
  })
}

// 保存用户组权限
const saveUserGroupPermission = () => {
  const checkedKeys = userPermissionTreeRef.value?.getCheckedKeys(true);
  let menuPermissionList: string[] = []; // 菜单权限
  let operationPermissionList: string[] = []; // 操作权限
  checkedKeys?.forEach((item) => {
    const permissionId = item.toString().trim();
    if(permissionId.includes(':')) { // 含有冒号的视为操作权限
      operationPermissionList.push(permissionId);
    } else {
      menuPermissionList.push(permissionId);
    }
  });
  // 如果用户选择了这个菜单下的操作权限，则自动添加菜单权限
  const operationPermission = menuStoreInstance.getOperationPermission();
  operationPermission.forEach(item => {
    if(!menuPermissionList.includes(item.menuId ?? '') && operationPermissionList.includes(item.permissionId ?? '')) {
      menuPermissionList.push(item.menuId ?? '');
    }
  })
  // 更新权限
  MessageUtils.confirmMessageBox(`确定更新用户组：${selectUserGroup.value} 的权限?`,'高风险操作确认').then(() => {
    // 更新菜单权限
    const updateMenuPermissionReq: IUpdatePermissionReq = {
      userGroup: selectUserGroup.value,
      permissionList: menuPermissionList,
    }
    UserGroupApi.updateUserGroupPermission(updateMenuPermissionReq).then((res) => {
      const response = JSON.parse(JSON.stringify(res.data)) as AppServeResponse;
      if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
        MessageUtils.successMessage('更新菜单权限成功');
        return;
      }
      MessageUtils.warningMessageBox(response.msg);
    }).catch((err) => {
      MessageUtils.errMessageBox(err);
    });
    // 更新操作权限
    const updateOperationPermissionReq: IUpdatePermissionReq = {
      userGroup: selectUserGroup.value,
      permissionList: operationPermissionList,
    }
    UserGroupApi.updateUserGroupOperationPermission(updateOperationPermissionReq).then((res) => {
      const response = JSON.parse(JSON.stringify(res.data)) as AppServeResponse;
      if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
        MessageUtils.successMessage('更新操作权限成功');
        queryUserGroup();
        return;
      }
      MessageUtils.warningMessageBox(response.msg);
    })
  }).catch(() => {});
}
// 获取用户操作权限
const getOperationPermission = () => {
  UserApi.queryUserOperationPermission().then(res => {
    const responseString = JSON.stringify(res.data);
    const permissionResponse: AppServeDataResponse<IBaseMenuPermissionVo[]> = JSON.parse(responseString) as AppServeDataResponse<IBaseMenuPermissionVo[]>;
    if (permissionResponse.code == AppServeResponseCodeEnum.SUCCESS && permissionResponse.data != undefined) {
      menuStoreInstance.setOperationPermission(permissionResponse.data);
      return;
    }
    MessageUtils.warningMessage(permissionResponse.msg);
  }).catch(() => {}).finally(() => {
    loadThisUserGroupPermission();
  })
}

</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 width="60" fixed="left" align="center">
            <template #default="scope">
              <el-radio v-model="selectUserGroup" :label="scope.row.userGroup">&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column type="index" width="80" label="序号" align="center" show-overflow-tooltip/>
          <el-table-column prop="userGroup" label="用户组ID" width="180" align="center" 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'}"
          >
            <template #default="{ node, data }">
              <el-text v-if="node.level <= 2" type="primary">{{ data.menuId }} --> {{ data.menuName }}</el-text>
              <el-text v-if="node.level == 3" type="primary">{{ data.menuName }}&nbsp;&nbsp;&nbsp;&nbsp;>>> {{ data.menuId }}</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>