<script lang="ts" setup name="SystemRoleList">
import type { Ref } from 'vue'
import { getCurrentInstance, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Switch } from '@element-plus/icons-vue'
import type { DataScopeTypeInfo, RoleInfo } from './role-interface'
import SystemEditRole from './editRole.vue'
import FunctionPerm from './functionPerm.vue'
import DataPerm from './dataPerm.vue'
import { delRole, getDataScopeTypeList, getRoleList } from '@/api/system/role'
import { toTreeList } from '@/utils/structure'
const { proxy } = getCurrentInstance() as any

const editDialog = ref() // 组件

// 数据权限类型字典
const dataScopeTypeDict: { [key: string]: string } = {
  1: '所有数据',
  2: '所属及下属部门',
  3: '本部门',
  4: '自定义',
}

// 默认查询条件
const defaultQuery = {
  keyword: '',
}
// 查询条件
const listQuery = reactive({ ...defaultQuery })
// 搜索重置
function reset() {
  Object.assign(listQuery, defaultQuery)
  fetchData()
}
// 表格表头
const columns = ref([
  { text: '角色名称', value: 'name', align: 'left' },
  { text: '所在组织机构', value: 'deptName' },
  { text: '数据权限类型', value: 'dataScopeTypeName' },
  { text: '别名', value: 'tips' },
  { text: '排序', value: 'num', width: 80, align: 'center' },
])
// 数据列表
const list: Ref<RoleInfo[]> = ref([])
const loading = ref(false)

// 搜索按钮
function search() {
  fetchData()
}
// 查询数据
function fetchData() {
  loading.value = true
  getRoleList(listQuery).then((res) => {
    const data = res.data.map((item: RoleInfo): RoleInfo => {
      return {
        ...item,
        dataScopeTypeName: dataScopeTypeDict[parseInt(item.dataScopeType)],
      }
    })
    const treeData = toTreeList<RoleInfo>(data)
    list.value = treeData
    loading.value = false
  })
}

// 获取角色类型列表
const roleTypeList: Ref<DataScopeTypeInfo[]> = ref([])
function fetchRoleType() {
  getDataScopeTypeList().then((res) => {
    roleTypeList.value = res.data
  })
}
// 编辑角色
function edit(row: RoleInfo) {
  editDialog.value.initDialog('update', row)
}
// 删除角色
function del(row: RoleInfo) {
  ElMessageBox.confirm(
    `确定要删除${row.name}吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    delRole(row.id).then((res) => {
      ElMessage.success('删除成功')
    })
    fetchData()
  })
}
// 添加角色
function add() {
  editDialog.value.initDialog('create')
}

// 打开功能权限菜单
const functionPerm = ref()
function openFunctionPerm(row: RoleInfo) {
  functionPerm.value.initDialog(row)
}

// 打开数据权限菜单
const dataPerm = ref()
function openDataPerm(row: RoleInfo) {
  dataPerm.value.initDialog(row)
}
// 表格组件
const table = ref()
const expansion = ref(false)
// 展开或折叠
function expandOrCollapse() {
  expansion.value = !expansion.value
  toggleRowExpansionAll(list.value, expansion.value)
}
// 展开所有行的递归函数
function toggleRowExpansionAll(data: RoleInfo[], isExpansion: boolean) {
  data.forEach((item) => {
    table.value.toggleRowExpansion(item, isExpansion)
    if (item.children && item.children.length > 0) {
      toggleRowExpansionAll(item.children, isExpansion)
    }
  })
}
onMounted(() => {
  fetchRoleType()
  fetchData()
})
</script>

<template>
  <app-container>
    <search-area @search="search">
      <search-item>
        <el-input v-model="listQuery.keyword" placeholder="角色名称" />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/sys/role/add')" icon="icon-add" title="新增" @click="add" />
        <icon-button icon="icon-fold" title="展开/折叠" @click="expandOrCollapse" />
      </template>
      <el-table ref="table" v-loading="loading" :data="list" row-key="id" border stripe style="width: 100%;" :tree-props="{ children: 'children' }">
        <el-table-column
          v-for="column of columns" :key="column.value" :label="column.text" :prop="column.value" :width="column.width" :align="column.align"
        />
        <el-table-column v-if="proxy.hasPerm('/sys/role/funcAuthor') || proxy.hasPerm('/sys/role/dataAuthor') || proxy.hasPerm('/sys/role/update') || proxy.hasPerm('/sys/role/delete')" label="操作" width="250" align="left" header-align="center">
          <template #default="scope">
            <el-button v-if="proxy.hasPerm('/sys/role/update')" type="primary" link size="small" class="table-text-button" @click="edit(scope.row)">
              修改
            </el-button>
            <el-button v-if="proxy.hasPerm('/sys/role/delete')" type="primary" link size="small" class="table-text-button" @click="del(scope.row)">
              删除
            </el-button>
            <el-button v-if="proxy.hasPerm('/sys/role/funcAuthor')" type="primary" link size="small" class="table-text-button" @click="openFunctionPerm(scope.row)">
              功能权限
            </el-button>
            <!-- 只有自定义显示配置数据权限按钮 -->
            <el-button v-if="proxy.hasPerm('/sys/role/dataAuthor') && scope.row.dataScopeType === '4'" type="primary" link size="small" class="table-text-button" @click="openDataPerm(scope.row)">
              数据权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </table-container>
    <system-edit-role ref="editDialog" :role-type-list="roleTypeList" @close-refresh="search" />
    <function-perm ref="functionPerm" />
    <data-perm ref="dataPerm" />
  </app-container>
</template>
