<template>
  <div>
    <div class="title">权限管理</div>
    <el-form
      ref="searchFormRef"
      class="form"
      :inline="true"
      label-width="98px"
      :model="queryParams"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          clearable
          placeholder="请输入"
          style="width: 220px"
          v-model="queryParams.name"
          @keyup.enter="getList"
        />
      </el-form-item>

      <el-form-item label-width="100px">
        <el-button icon="Search" type="primary" @click="getList"> 搜索 </el-button>
        <el-button icon="RefreshRight" @click="resetQuery"> 重置 </el-button>
      </el-form-item>
    </el-form>

    <div style="margin-bottom: 20px">
      <el-button icon="Plus" type="primary" @click="add"> 新建 </el-button>
    </div>
    <div ref="tableContainerEl" class="table_border table">
      <el-table
        ref="tableRef"
        :data="tableData"
        v-loading="loading"
        header-row-class-name="table-header"
        row-key="id"
      >
        <el-table-column label="名称" prop="name" show-overflow-tooltip />
        <el-table-column align="center" label="字段" prop="code" show-overflow-tooltip />
        <el-table-column align="center" label="描述" prop="description" show-overflow-tooltip />
        <el-table-column align="center" label="类型" prop="type" width="100">
          <template #default="{ row }">
            <span v-if="row.type == 1">目录</span>
            <span v-if="row.type == 2">菜单</span>
            <span v-if="row.type == 3">按钮</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否启用" prop="is_show" width="100">
          <template #default="{ row }">
            <span v-if="row.is_show == 1">启用</span>
            <span v-if="row.is_show == 0">禁用</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180">
          <template #default="{ row }">
            <el-button v-if="row.status != 1" link type="primary" @click="addChildren(row)">
              添加子项
            </el-button>
            <el-button v-if="row.status != 1" link type="primary" @click="edit(row)">
              编辑
            </el-button>

            <el-button v-if="row.status != 1" link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- <pagination
      v-show="total > 0"
      :total="total"
      v-model:limit="queryParams.limit"
      v-model:page="queryParams.page"
      @pagination="getList"
    /> -->

    <HandleDialog
      v-if="isShowDialog"
      :type="rowType"
      :row="currentRow"
      :categoryList="categoryList"
      @closed="isShowDialog = false"
      @on-success="getList"
      :originData="originData"
      :current_parent_id="current_parent_id"
    />
  </div>
</template>

<script setup>
import { useTableRPC } from '@/utils/hook'
import RPC from '@/utils/rpc'
import HandleDialog from './HandleDialog.vue'

const rowType = ref('')
const currentRow = ref(null)
const add = () => {
  isShowDialog.value = true
  currentRow.value = null
  current_parent_id.value = 0
  rowType.value = 'add'
}
const addChildren = (row) => {
  isShowDialog.value = true
  currentRow.value = null
  current_parent_id.value = row.id
  rowType.value = 'add'
}
const edit = (row) => {
  isShowDialog.value = true
  rowType.value = 'edit'
  currentRow.value = row
}

const current_parent_id = ref(0)

// const {
//   loading,
//   tableData,
//   tableRef,
//   searchFormRef,
//   total,
//   queryParams,
//   getList,
//   handleQuery,
//   resetQuery,
//   handleDelete,
//   isShowDialog,
//   maxHeight,
//   tableContainerEl,
// } = useTableRPC({
//   queryParams: {},
//   remoteDataFn: '/permission/list',
//   deleteConfig: {
//     remote: '/permission/delete',
//     key: 'id',
//     message(row) {
//       return `确认删除 “${row.name}”`
//     },
//   },
// })
const loading = ref(false)
const tableData = ref([])
const queryParams = ref({})
const isShowDialog = ref(false)
const transformParams = (params) => {
  const _params = {
    page: 1,
    limit: -1,
    orderby: params.orderby || null,
    like: {},
  }
  for (const k in params) {
    if (params[k] && k !== 'page' && k !== 'limit' && k !== 'orderby') {
      _params.like[k] = [`%${params[k]}%`]
    }
  }
  return _params
}
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除 “${row.name}”`, '提醒', {
    type: 'warning',
  })
    .then(() => {
      RPC.post('/permission/delete', { id: row.id })
        .then(() => {
          getList()
          ElMessage.success('删除成功')
        })
        .catch((e) => {
          console.error(`删除失败：${e}`)
        })
    })
    .catch(() => {
      onError?.()
    })
}
const resetQuery = () => {
  queryParams.value = {}
  getList()
}
function buildTree(data, rootId = 0) {
  // 1. 建立一个 id -> 节点 的映射表，方便快速查找
  const map = {}
  data.forEach((item) => {
    map[item.id] = { ...item, children: [] }
  })

  // 2. 遍历数据，组装父子关系
  const tree = []
  data.forEach((item) => {
    const node = map[item.id]
    if (item.parent_id === rootId) {
      // 顶级节点
      tree.push(node)
    } else if (map[item.parent_id]) {
      // 非顶级，挂到父节点的 children
      map[item.parent_id].children.push(node)
    }
  })

  return tree
}
const originData = ref([{ id: 0, name: '无' }])
const getList = () => {
  loading.value = true
  RPC.post('/permission/list', transformParams(queryParams.value))
    .then((res) => {
      console.log(res)
      originData.value = [{ id: 0, name: '无' }, ...res.rows] || [{ id: 0, name: '无' }]
      tableData.value = buildTree(res.rows || [])
    })
    .finally(() => {
      loading.value = false
    })
}

getList()
</script>

<style lang="scss" scoped>
.title {
  font-size: 20px;
  font-weight: 700;
  margin-bottom: 20px;
}
</style>
