<route lang="yaml">
meta:
  enabled: false
</route>

<script lang="ts" setup name="AppRolePermit">
import Permit from './components/Permit.vue'
import { getAppPermitListById } from '@/api/apps/appPermitApi'
import { getRoleByList } from '@/api/system/roleApi'
import useSettingsStore from '@/store/modules/settings'

const settingsStore = useSettingsStore()

const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()
const appId = parseInt(route.params.appId.toString())

interface TreeNode {
  label: string
  roleId: number
  isLeaf: boolean
  children?: any[]
}

const state = reactive({
  loading: false,
  curRoleId: 0,
  roles: [] as TreeNode[],
  permitList: [],
  permitTreeData: [] as any[],
  search: {
    appId,
    roleId: 0,
    keywords: '',
  },
})

const roleTreeRef = ref()

function tranListToTreeData(list: any[], rootValue: number): any[] {
  const arr: any[] = []
  list.forEach((item) => {
    if (item.parentId === rootValue) {
      // 找到之后 就要去找 item 下面有没有子节点
      const children = tranListToTreeData(list, item.permitId)
      if (children.length) {
        // 如果children的长度大于0 说明找到了子节点
        item.children = children
      }
      arr.push(item) // 将内容加入到数组中
    }
  })
  return arr
}

// 查询Permit列表
const getAppRolePermitData = async () => {
  const curRoleId = state.curRoleId
  if (curRoleId > 0) {
    state.loading = true
    const { data } = await getAppPermitListById(appId, state.curRoleId)
    state.loading = false
    state.permitList = data
    state.permitTreeData = tranListToTreeData(data, 0)
  }
}

// 查询Role数据
const getRoleData = async () => {
  state.loading = true
  const { data } = await getRoleByList({})
  if (data && data.length > 0) {
    state.curRoleId = data[0].roleId
    await getAppRolePermitData()
    const children: TreeNode[] = []
    data.forEach((item: any) => {
      return children.push({
        label: item.roleName,
        roleId: item.roleId,
        isLeaf: true,
      })
    })
    state.roles = [
      {
        label: '系统角色',
        isLeaf: false,
        roleId: -1,
        children,
      },
    ]
  }
  await nextTick(() => {
    roleTreeRef.value.setCurrentKey(data[0].roleId)
  })
}

const onTreeNodeClick = async (node: TreeNode) => {
  state.curRoleId = node.roleId
  await getAppRolePermitData()
}

const permitTableRef = ref()
const permitRef = ref()

const onPermitAdd = () => {
  permitRef.value.showAddModel(appId, state.curRoleId)
}

const onAddSub = (row: any) => {
  window.console.log(row)
}

const onEdit = (row: { appId: any; roleId: any; permitId: any }) => {
  const { appId, roleId, permitId } = row
  permitRef.value.showEditModel(appId, roleId, permitId)
}

const onDelete = (row: any) => {
  window.console.log(row)
}

const onUp = (row: any) => {
  window.console.log(row)
}
const onDown = (row: any) => {
  window.console.log(row)
}

// 组件处理成功回调
const onSuccess = () => {
  getAppRolePermitData()
}

const onSearch = () => {
  getAppRolePermitData()
}

onMounted(() => {
  getRoleData()
})

// 返回列表页
function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'appStore' })
  }
  else {
    router.push({ name: 'appStore' })
  }
}
</script>

<template>
  <div class="absolute-container">
    <page-header title="应用权限管理" content="为每个应用配置基于角色的权限。">
      <el-button size="default" round @click="goBack">
        <template #icon>
          <el-icon>
            <svg-icon name="i-ep:arrow-left" />
          </el-icon>
        </template>
        返回
      </el-button>
    </page-header>

    <div class="page-main">
      <LayoutContainer left-side-width="250px" hide-left-side-toggle>
        <template #leftSide>
          <el-scrollbar class="tree">
            <ElTree ref="roleTreeRef" :data="state.roles" default-expand-all node-key="roleId" @node-click="onTreeNodeClick">
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <div class="label" :title="node.label">
                    <el-icon v-if="data.isLeaf" size="16px" style="margin-right: 5px;">
                      <svg-icon name="ep:avatar" />
                    </el-icon>
                    <div class="text">
                      {{ data.label }}
                    </div>
                  </div>
                </div>
              </template>
            </ElTree>
          </el-scrollbar>
        </template>

        <div class="container">
          <tool-bar>
            <template #right>
              <el-input v-model="state.search.keywords" placeholder="请输入关键词筛选" clearable style="width: 200px;" />
              <el-button style="margin-left: 10px;" @click="onSearch">
                <template #icon>
                  <el-icon>
                    <svg-icon name="i-ep:search" />
                  </el-icon>
                </template>
              </el-button>

              <el-button type="primary" @click="onPermitAdd">
                <template #icon>
                  <el-icon>
                    <svg-icon name="i-ep:plus" />
                  </el-icon>
                </template>
              </el-button>
            </template>
          </tool-bar>
          <el-table
            ref="permitTableRef"
            v-loading="state.loading"
            class="list-table"
            :data="state.permitTreeData"
            row-key="permitId"
            default-expand-all
            size="small"
            border stripe highlight-current-row
            height="100%"
          >
            <el-table-column type="index" align="center" label="序号" width="70" />

            <el-table-column label="权限名称" width="250px">
              <template #default="{ row }">
                <span>{{ row.permitTitle }}</span>
              </template>
            </el-table-column>

            <el-table-column label="权限编码" min-width="100">
              <template #default="{ row }">
                <span>{{ row.permitCode }}</span>
              </template>
            </el-table-column>

            <el-table-column label="类型" header-align="center" align="center" width="80">
              <template #default="{ row }">
                <span v-if="row.permitType === 0"><el-tag>分组</el-tag></span>
                <span v-else><el-tag>权限</el-tag></span>
              </template>
            </el-table-column>

            <el-table-column label="简要说明">
              <template #default="{ row }">
                <span>{{ row.permitDesc }}</span>
              </template>
            </el-table-column>

            <el-table-column label="排序" header-align="center" align="center" width="60">
              <template #default="{ row }">
                <span>{{ row.sortNo }}</span>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="160" header-align="center" align="center">
              <template #default="{ row }">
                <el-button v-if="row.permitType === 0" size="small" type="primary" @click="onAddSub(row)">
                  添加
                </el-button>
                <el-button size="small" type="success" @click="onEdit(row)">
                  修改
                </el-button>
                <el-button size="small" type="danger" @click="onDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </LayoutContainer>
      <Permit ref="permitRef" @success="onSuccess" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.absolute-container {
  .page-header {
    margin-bottom: 0;
  }

  :deep(.left-side) {
    display: flex;
    flex-direction: column;
    height: 100%;

    .btns {
      display: inline-flex;
      width: 100%;
      margin-bottom: var(--container-padding);

      .add {
        width: 100%;
      }
    }

    .tree {
      flex: 1;
      overflow-y: auto;

      .el-tree {
        .el-tree-node__content {
          height: 40px;
        }

        .is-current > .el-tree-node__content {
          background-color: var(--el-color-primary-light-9);
        }

        .custom-tree-node {
          flex: 1;
          position: relative;
          width: 0;
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;

          .label {
            display: inline-flex;
            align-items: center;
            width: calc(100% - 10px);
            color: var(--el-text-color-primary);

            .text {
              @include text-overflow;
            }
          }

          &:hover {
            .actions {
              display: block;
            }
          }

          .actions {
            display: none;
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);

            .el-button {
              padding: 5px 8px;
            }
          }
        }
      }
    }
  }
}
</style>
