<template>
  <div class="app-container">
    <el-container style="height: 100%; border: 1px solid #eee" v-loading="loading">
      <el-aside
        width="400px"
        style="
          background-color: transparent;
          border-right: 1px solid #eee;
          margin: 0;
          padding-top: 40px;
        "
      >
        <el-table
          ref="singleTable"
          :data="roleList"
          highlight-current-row
          @current-change="handleCurrentChange"
          :show-header="false"
          border
        >
          <el-table-column align="center" property="roleName" label="角色名称" />
          <template slot="append">
            <div
              @click="handleAddRole"
              style="
                height: 44px;
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
              "
            >
              <i class="el-icon-plus mr5" style="color: #1890ff"></i>
              <el-button type="text">新增角色</el-button>
            </div>
          </template>
        </el-table>
      </el-aside>

      <el-container>
        <el-header height="auto">
          <div class="sf-title mt10">角色信息</div>
          <el-table :data="currentRole ? [currentRole] : []" border>
            <el-table-column align="center" property="id" label="角色ID" />
            <el-table-column align="center" property="roleName" label="角色名称" />
            <el-table-column align="center" property="status" label="状态">
              <template slot-scope="scope">
                {{ RULE_STATUS.getLabelByValue(scope.row.status) }}
              </template>
            </el-table-column>
            <el-table-column align="center" property="createTime" label="创建时间" />
            <el-table-column align="center" property="updateTime" label="最后编辑时间" />
            <el-table-column
              align="center"
              label="操作"
              class-name="small-padding fixed-width"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleEditRole(scope.row)">
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-header>

        <el-main>
          <div class="sf-title">分配功能权限</div>
          <el-table :data="tableData" border row-key="id" :span-method="handleSpanMethod">
            <el-table-column align="center" property="firstLevel" label="一级功能" />
            <el-table-column align="center" property="secondLevel" label="二级功能" />
            <!-- <el-table-column align="center" property="thirdLevel" label="权限名称" /> -->
          </el-table>
        </el-main>
      </el-container>
    </el-container>
    <CrudPopup ref="crud" />
  </div>
</template>

<script>
import ApiButton from "@/components/ApiButton/index.vue";
import CrudPopup from "../roleList/components/CrudPopup/index.vue";
import { geMenuTreeList, getRoleAllList, getRoleMenuList } from "@/api/admin";
import { RULE_STATUS } from '@/enums/index'
export default {
  name: "RoleDetail",
  components: {
    ApiButton,
    CrudPopup,
  },
  data() {
    return {
      RULE_STATUS,
      loading: true,
      roleList: [],
      currentRole: null,
      treeData: [],
      menuIds: [],
    };
  },
  created() {
    Promise.all([this.loadRoleList(), this.loadTreeList()]).finally(() => {
      this.loading = false;
    });
  },
  computed: {
    currentMenus() {
      if (this.menuIds.length === 0 || this.treeData.length === 0) return [];
      return this.filterMenusAndKeepParents(this.treeData, this.menuIds);
    },
    tableData() {
      const result = [];
      const flattenMenuData = (data, parentNames = []) => {
        data.forEach((item) => {
          if (item.children?.length > 0) {
            flattenMenuData(item.children, [...parentNames, item.menuName]);
          } else {
            const [firstLevel, secondLevel, ...others] = [...parentNames, item.menuName];
            result.push({
              firstLevel,
              secondLevel,
              thirdLevel: others.join("/"),
            });
          }
        });
      };
      flattenMenuData(this.currentMenus);
      return this.mergeRowsAndCols(result);
    },
  },
  watch: {
    currentRole(val) {
      if (val?.id) {
        this.loadMenuIdList(val.id);
      }
    },
  },
  methods: {
    loadRoleList() {
      return getRoleAllList().then((res) => {
        this.roleList = res.data;
        let selectRole;
        if (this.currentRole) {
          selectRole = this.roleList.find((item) => item.id === this.currentRole.id);
        }
        this.$refs.singleTable.setCurrentRow(selectRole || res.data[0]);
      });
    },
    loadTreeList() {
      return geMenuTreeList().then((res) => {
        this.treeData = res.data;
      });
    },
    loadMenuIdList(roleId) {
      return getRoleMenuList({ roleId }).then((res) => {
        this.menuIds = res.data.map((item) => item.menuId);
      });
    },
    // 添加角色 {}
    // 计算表格合并相同项
    mergeRowsAndCols(inputList) {
      const firstLevelCount = {};
      const secondLevelCount = {};
      const outputList = [];

      inputList.forEach((item) => {
        const { firstLevel, secondLevel } = item;
        firstLevelCount[firstLevel] = (firstLevelCount[firstLevel] || 0) + 1;
        secondLevelCount[secondLevel] = (secondLevelCount[secondLevel] || 0) + 1;
      });
      inputList.forEach((item, index) => {
        const { firstLevel, secondLevel, thirdLevel } = item;
        const newItem = { firstLevel, secondLevel, thirdLevel };

        if (firstLevelCount[firstLevel] > 1) {
          if (index === inputList.findIndex((x) => x.firstLevel === firstLevel)) {
            newItem.firstRowSpan = firstLevelCount[firstLevel];
          } else {
            newItem.firstColSpan = 0;
          }
        }

        if (secondLevelCount[secondLevel] > 1) {
          if (index === inputList.findIndex((x) => x.secondLevel === secondLevel)) {
            newItem.secondRowSpan = secondLevelCount[secondLevel];
          } else {
            newItem.secondColSpan = 0;
          }
        }

        outputList.push(newItem);
      });
      return outputList;
    },
    // 根据全量菜单过滤
    filterMenusAndKeepParents(menus, menuIds) {
      const filteredMenus = [];

      for (const menu of menus) {
        if (menuIds.includes(menu.id)) {
          // 如果菜单在menuIds中，则保留该菜单
          const filteredMenu = { ...menu };

          // 如果菜单有子菜单，递归过滤并保留父菜单
          if (menu.children) {
            filteredMenu.children = this.filterMenusAndKeepParents(menu.children, menuIds);
          }

          filteredMenus.push(filteredMenu);
        } else if (menu.children) {
          // 如果菜单不在menuIds中但有子菜单，递归过滤并保留父菜单
          const filteredChildren = this.filterMenusAndKeepParents(menu.children, menuIds);
          if (filteredChildren.length > 0) {
            const filteredMenu = { ...menu, children: filteredChildren };
            filteredMenus.push(filteredMenu);
          }
        }
      }
      return filteredMenus;
    },
    handleCurrentChange(item) {
      this.currentRole = item;
    },
    // 新增角色
    handleAddRole() {
      this.$refs.crud.open().then((res) => {
        this.currentRole = res;
        this.loadRoleList();
      });
    },
    // 编辑角色
    handleEditRole() {
      this.$refs.crud
        .open({
          ...this.currentRole,
          menuIdList: this.menuIds,
        })
        .then(this.loadRoleList);
    },
    handleSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return {
          rowspan: row.firstRowSpan >= 0 ? row.firstRowSpan : 1,
          colspan: row.firstColSpan >= 0 ? row.firstColSpan : 1,
        };
      } else if (columnIndex === 1) {
        return {
          rowspan: row.secondRowSpan >= 0 ? row.secondRowSpan : 1,
          colspan: row.secondColSpan >= 0 ? row.secondColSpan : 1,
        };
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  height: 100%;
}
</style>
