<template>
  <div class="permission-page art-full-height">
    <!-- 搜索栏 -->
    <ArtSearchBar
      v-model="formFilters"
      :items="formItems"
      @search="handleSearch"
      @reset="handleReset"
    />

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="handleRefresh">
        <template #left>
          <ElRadioGroup v-model="viewMode" size="default">
            <ElRadioButton label="tree">树形模式</ElRadioButton>
            <ElRadioButton label="list">列表模式</ElRadioButton>
          </ElRadioGroup>
        </template>
      </ArtTableHeader>

      <!-- 列表视图 -->
      <ArtTable
        ref="listTableRef"
        :loading="loading"
        :columns="columns"
        :data="tableData"
        :pagination="viewMode === 'list' ? pagination : undefined"
        row-key="_uniqueId"
        :default-expand-all="viewMode === 'tree'"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
        @sort-change="handleSortChange"
      />
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, h, watch, watchEffect } from 'vue'
  import { ElTag, ElRadioGroup, ElRadioButton, ElCard } from 'element-plus'
  import { useTableColumns } from '@/hooks/core/useTableColumns'
  import { fetchGetPermissionTree } from '@/api/permission'

  defineOptions({ name: 'Permission' })

  // 类型定义
  interface TreePermission extends Api.Permission.PermissionDto {
    children?: TreePermission[]
    isGroup?: boolean
    _uniqueId: string // 前端生成的唯一ID，用于解决后端ID精度丢失或重复问题
  }

  // 状态
  const loading = ref(false)
  const viewMode = ref<'tree' | 'list'>('tree') // 默认为树形模式
  const treeData = ref<TreePermission[]>([]) // 树形数据
  const flatData = ref<TreePermission[]>([]) // 扁平数据

  // 分页 (仅用于列表模式)
  const pagination = reactive({
    current: 1,
    size: 20,
    total: 0
  })

  // 搜索表单
  const formFilters = ref({
    keyword: '',
    sortBy: '' as string | undefined,
    sortDescending: undefined as boolean | undefined
  })

  const formItems = [
    { type: 'input', key: 'keyword', label: '关键词', placeholder: '搜索权限名称或代码' }
  ]

  // 扁平化树结构 helper
  const flattenTree = (tree: TreePermission[]): TreePermission[] => {
    let res: TreePermission[] = []
    tree.forEach((node) => {
      const { children, ...rest } = node
      res.push(rest as TreePermission)
      if (children && children.length > 0) {
        res = res.concat(flattenTree(children))
      }
    })
    return res
  }

  // 搜索过滤 logic
  const filteredTreeData = computed(() => {
    if (!formFilters.value.keyword) return treeData.value

    const keyword = formFilters.value.keyword.toLowerCase()
    const filter = (nodes: TreePermission[]): TreePermission[] => {
      return nodes.reduce((acc, node) => {
        const match =
          (node.name && node.name.toLowerCase().includes(keyword)) ||
          (node.code && node.code.toLowerCase().includes(keyword))

        let children: TreePermission[] = []
        if (node.children) {
          children = filter(node.children)
        }

        if (match || children.length > 0) {
          acc.push({ ...node, children: children.length > 0 ? children : undefined })
        }
        return acc
      }, [] as TreePermission[])
    }

    return filter(treeData.value)
  })

  const filteredFlatData = computed(() => {
    let data = [...flatData.value]

    // 关键词过滤
    if (formFilters.value.keyword) {
      const keyword = formFilters.value.keyword.toLowerCase()
      data = data.filter(
        (item) =>
          (item.name && item.name.toLowerCase().includes(keyword)) ||
          (item.code && item.code.toLowerCase().includes(keyword))
      )
    }

    // 排序
    if (formFilters.value.sortBy) {
      data.sort((a, b) => {
        const valA = a[formFilters.value.sortBy as keyof TreePermission]
        const valB = b[formFilters.value.sortBy as keyof TreePermission]
        if (valA === valB) return 0
        // 处理空值
        if (valA == null) return 1
        if (valB == null) return -1

        const compare = String(valA).localeCompare(String(valB))
        return formFilters.value.sortDescending ? -compare : compare
      })
    }

    return data
  })

  const listTotal = computed(() => filteredFlatData.value.length)

  // 1. 同步分页总数（树形模式使用树长度，列表模式使用扁平长度）
  watchEffect(() => {
    pagination.total = viewMode.value === 'list' ? listTotal.value : filteredTreeData.value.length
  })

  // 最终表格数据
  const tableData = computed(() => {
    if (viewMode.value === 'tree') {
      return filteredTreeData.value
    } else {
      // 列表模式下的分页处理
      const start = (pagination.current - 1) * pagination.size
      const end = start + pagination.size
      return filteredFlatData.value.slice(start, end)
    }
  })

  // 列定义
  const { columns, columnChecks } = useTableColumns<TreePermission>(() => [
    { prop: 'name', label: '权限名称', minWidth: 180, fixed: 'left', align: 'left' },
    {
      prop: 'code',
      label: '权限标识',
      minWidth: 200,
      formatter: (row) => {
        if (row.isGroup) return '' // 分组不显示代码
        return row.code || '-'
      }
    },
    { prop: 'description', label: '描述', minWidth: 200, showOverflowTooltip: true },
    {
      prop: 'type',
      label: '类型',
      width: 100,
      align: 'center',
      formatter: (row) => {
        return h(
          ElTag,
          {
            type: row.isGroup ? 'primary' : 'success',
            effect: 'plain'
          },
          () => (row.isGroup ? '权限分组' : '具体权限')
        )
      }
    }
  ])

  // API Actions
  const fetchData = async () => {
    // 1. 设置加载状态
    loading.value = true

    try {
      // 2. 获取权限树数据
      const treeRes = await fetchGetPermissionTree()
      const safeList = Array.isArray(treeRes) ? treeRes : []

      // 3. 生成唯一ID并标记分组
      let uniqueIdCounter = 0
      const generateUniqueId = () => `node_${Date.now()}_${uniqueIdCounter++}`
      const processData = (nodes: Api.Permission.PermissionDto[]): TreePermission[] => {
        return nodes.map((node) => ({
          ...node,
          isGroup: node.type === 'group' || !!(node.children && node.children.length > 0),
          _uniqueId: generateUniqueId(), // 生成前端唯一Key
          children: node.children ? processData(node.children) : undefined
        }))
      }

      treeData.value = processData(safeList)
      flatData.value = flattenTree(treeData.value)
    } catch (error) {
      console.error('fetch permission tree failed', error)
      treeData.value = []
      flatData.value = []
    } finally {
      loading.value = false
    }
  }

  // Event Handlers
  const handleSearch = () => {
    pagination.current = 1
  }

  const handleReset = () => {
    formFilters.value.keyword = ''
    formFilters.value.sortBy = undefined
    formFilters.value.sortDescending = undefined
    handleSearch()
  }

  const handleRefresh = () => {
    fetchData()
  }

  const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1
  }

  const handleCurrentChange = (page: number) => {
    pagination.current = page
  }

  const handleSortChange = (data: { prop: string; order: string }) => {
    if (!data.order) {
      formFilters.value.sortBy = undefined
      formFilters.value.sortDescending = undefined
    } else {
      formFilters.value.sortBy = data.prop
      formFilters.value.sortDescending = data.order === 'descending'
    }
  }

  // 监听模式切换，重置分页
  watch(viewMode, () => {
    pagination.current = 1
  })

  onMounted(() => {
    fetchData()
  })
</script>
