<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Download, Grid, Refresh, Search } from '@element-plus/icons-vue'

const scopeSelect = ref('selected')
const districtSearch = ref('')
const treeRef = ref(null)

const treeData = ref([
  {
    id: '106',
    label: '106壶天镇',
    children: [
      {
        id: '203',
        label: '203大坪村',
        children: Array.from({ length: 12 }, (_, i) => {
          const no = String(i + 1).padStart(2, '0')
          return { id: `203-${no}`, label: `[${no}] 大坪第${i + 1}村民组`, children: [] }
        })
      },
      { id: '206', label: '206石狗村', children: [] },
      { id: '207', label: '207壶天村', children: [] },
      { id: '210', label: '210中石村', children: [] },
      { id: '214', label: '214光辉村', children: [] },
      { id: '218', label: '218直东村', children: [] },
      { id: '220', label: '220合东村', children: [] },
      { id: '222', label: '222南岳坪村', children: [] },
      { id: '224', label: '224上新桥村', children: [] },
      { id: '229', label: '229潭桥村', children: [] },
      { id: '230', label: '230双坪村', children: [] },
      { id: '235', label: '235山坪村', children: [] },
      { id: '238', label: '238大塘村', children: [] },
      { id: '239', label: '239山竹村', children: [] },
      { id: '242', label: '242渠溪村', children: [] },
      { id: '244', label: '244雄辉村', children: [] },
      { id: '247', label: '247井湾村', children: [] },
      { id: '248', label: '248背冲村', children: [] }
    ]
  },
  { id: '107', label: '107翻江镇', children: [] },
  { id: '110', label: '110月山镇', children: [] }
])

const treeProps = { children: 'children', label: 'label' }

const selectedNodeId = ref('')
const selectedSubtreeIds = ref(null)

function walkSubtreeIds(node, set) {
  if (!node) return
  set.add(node.id)
  const children = Array.isArray(node.children) ? node.children : []
  for (const child of children) walkSubtreeIds(child, set)
}

function filterTreeNode(value, data) {
  if (!value) return true
  if (scopeSelect.value === 'selected' && selectedSubtreeIds.value && !selectedSubtreeIds.value.has(data?.id)) {
    return false
  }
  return String(data?.label || '').includes(value)
}

function handleTreeNodeClick(data) {
  selectedNodeId.value = data?.id || ''
  const set = new Set()
  walkSubtreeIds(data, set)
  selectedSubtreeIds.value = set
  if (districtSearch.value) treeRef.value?.filter?.(districtSearch.value)
}

watch(districtSearch, (val) => treeRef.value?.filter?.(val))

const operatorFilterOpen = ref(false)
const operatorFilter = ref('')

function buildRows() {
  const districtList = [
    { id: '203-01', code: '430381106203010001', name: '湘乡市壶天镇大坪村第一村民组' },
    { id: '203-02', code: '430381106203010002', name: '湘乡市壶天镇大坪村第二村民组' },
    { id: '203-03', code: '430381106203010003', name: '湘乡市壶天镇大坪村第三村民组' },
    { id: '203-04', code: '430381106203010004', name: '湘乡市壶天镇大坪村第四村民组' },
    { id: '206', code: '430381106206000000', name: '湘乡市壶天镇石狗村' }
  ]
  const operators = ['周玺', '许皓亮', '侯清平', '陈菊珍']
  const types = ['承包方附件', '承包合同附件', '网签数据包']
  const times = [
    '2025-08-14 20:36:07',
    '2025-08-14 18:12:21',
    '2025-08-13 09:22:48',
    '2025-08-12 15:04:31'
  ]

  return Array.from({ length: 18 }, (_, i) => {
    const d = districtList[i % districtList.length]
    const op = operators[i % operators.length]
    const type = types[i % types.length]
    const t = times[i % times.length]
    return {
      id: i + 1,
      districtId: d.id,
      districtCode: d.code,
      districtName: d.name,
      operator: op,
      operateTime: t,
      operateType: type,
      status: 'success'
    }
  })
}

const allRows = ref(buildRows())

const filteredByTree = computed(() => {
  if (scopeSelect.value === 'all') return allRows.value
  const ids = selectedSubtreeIds.value
  if (!ids || ids.size === 0) return allRows.value
  return allRows.value.filter((r) => ids.has(r.districtId) || ids.has(r.districtId?.split?.('-')?.[0]))
})

const filteredRows = computed(() => {
  const op = String(operatorFilter.value || '').trim()
  return filteredByTree.value.filter((r) => (op ? String(r.operator || '').includes(op) : true))
})

const tableRef = ref(null)
const pageSize = ref(20)
const currentPage = ref(1)
const jumpPage = ref(1)

const total = computed(() => filteredRows.value.length)
const pageRows = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredRows.value.slice(start, start + pageSize.value)
})

watch([pageSize, selectedNodeId, scopeSelect, operatorFilter], () => {
  currentPage.value = 1
  jumpPage.value = 1
})

function doJump() {
  const maxPage = Math.max(1, Math.ceil(total.value / pageSize.value))
  const next = Math.min(Math.max(1, Number(jumpPage.value || 1)), maxPage)
  currentPage.value = next
}

function handleRefresh() {
  ElMessage.success('已刷新')
}

function handleDownload(row) {
  ElMessage.success(`开始下载：${row?.operateType || '附件'}`)
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm('确认删除文件和记录？', '提示', { type: 'warning' })
    allRows.value = allRows.value.filter((r) => r.id !== row.id)
    ElMessage.success('已删除')
  } catch {
    //
  }
}

function handleIconAction(name) {
  ElMessage.success(name)
}

const contentWrapEl = ref(null)
let resizeObserver = null
function ensureTableLayout() {
  nextTick(() => tableRef.value?.doLayout?.())
}

onMounted(async () => {
  await nextTick()
  const defaultNode = treeData.value?.[0]?.children?.find?.((v) => v.id === '203') || treeData.value?.[0]
  handleTreeNodeClick(defaultNode)
  treeRef.value?.setCurrentKey?.(defaultNode?.id)
  ensureTableLayout()
  if (contentWrapEl.value && !resizeObserver) {
    resizeObserver = new ResizeObserver(() => ensureTableLayout())
    resizeObserver.observe(contentWrapEl.value)
  }
})

onBeforeUnmount(() => {
  resizeObserver?.disconnect?.()
  resizeObserver = null
})
</script>

<template>
  <div class="h-full w-full flex overflow-hidden bg-white">
    <div class="w-72 border-r border-gray-200 bg-white flex flex-col">
      <div class="p-2 border-b border-gray-200">
        <el-select v-model="scopeSelect" size="small" class="w-full" placeholder="选中的节点中搜索">
          <el-option label="选中的节点中搜索" value="selected" />
          <el-option label="全部" value="all" />
        </el-select>
        <el-input v-model="districtSearch" size="small" class="w-full mt-2" clearable placeholder="搜索行政区" />
      </div>
      <el-scrollbar class="flex-1">
        <div class="p-2">
          <el-tree
            ref="treeRef"
            :data="treeData"
            node-key="id"
            :props="treeProps"
            :filter-node-method="filterTreeNode"
            default-expand-all
            highlight-current
            :expand-on-click-node="false"
            @node-click="handleTreeNodeClick"
          />
        </div>
      </el-scrollbar>
    </div>

    <div ref="contentWrapEl" class="flex-1 overflow-hidden">
      <div class="h-full flex flex-col">
        <div class="flex items-center justify-between px-2 py-2 border-b border-gray-200">
          <el-button :icon="Refresh" circle @click="handleRefresh" />
          <div class="flex items-center gap-2">
            <el-button :icon="Grid" circle size="small" @click="handleIconAction('已切换显示')" />
            <el-button :icon="Download" circle size="small" @click="handleIconAction('导出任务已提交')" />
            <el-button :icon="Refresh" circle size="small" @click="handleIconAction('已刷新')" />
          </div>
        </div>

        <div class="flex-1 p-3 overflow-hidden">
          <div class="h-full border border-gray-200 flex flex-col">
            <div class="flex-1 overflow-hidden">
              <el-table ref="tableRef" :data="pageRows" height="100%" border stripe>
                <el-table-column label="#" width="56" align="center">
                  <template #default="{ $index }">
                    {{ (currentPage - 1) * pageSize + $index + 1 }}
                  </template>
                </el-table-column>
                <el-table-column prop="districtCode" label="行政区代码" min-width="190" show-overflow-tooltip />
                <el-table-column prop="districtName" label="行政区名称" min-width="240" show-overflow-tooltip />
                <el-table-column prop="operator" width="120">
                  <template #header>
                    <div class="flex items-center justify-between gap-2">
                      <span>操作人</span>
                      <el-popover v-model:visible="operatorFilterOpen" trigger="click" placement="bottom" width="260">
                        <template #reference>
                          <el-button :icon="Search" circle size="small" />
                        </template>
                        <div class="space-y-2">
                          <el-input v-model="operatorFilter" size="small" clearable placeholder="输入操作人关键字" @keyup.enter="operatorFilterOpen = false" />
                          <div class="flex justify-end gap-2">
                            <el-button size="small" @click="operatorFilter = ''">清空</el-button>
                            <el-button size="small" type="primary" @click="operatorFilterOpen = false">确定</el-button>
                          </div>
                        </div>
                      </el-popover>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="operateTime" label="操作时间" width="180" show-overflow-tooltip />
                <el-table-column prop="operateType" label="操作类型" width="140" show-overflow-tooltip />
                <el-table-column label="状态" width="120" align="center">
                  <template #default="{ row }">
                    <el-tag v-if="row.status === 'success'" type="success">生成成功</el-tag>
                    <el-tag v-else type="info">未知</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="220" align="center">
                  <template #default="{ row }">
                    <div class="flex items-center justify-center gap-2">
                      <el-button size="small" type="success" :icon="Download" @click="handleDownload(row)">下载</el-button>
                      <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(row)">删除文件和记录</el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div class="h-12 px-2 border-t border-gray-200 flex items-center justify-between">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="prev, pager, next"
                background
                small
              />
              <div class="flex items-center gap-2 text-sm text-gray-700">
                <div>到第</div>
                <el-input-number v-model="jumpPage" :min="1" :max="Math.max(1, Math.ceil(total / pageSize))" size="small" controls-position="right" class="!w-24" />
                <div>页</div>
                <el-button size="small" type="primary" @click="doJump">确定</el-button>
                <div class="ml-2">共 {{ total }} 条</div>
                <el-select v-model="pageSize" size="small" class="!w-24">
                  <el-option :label="`10条/页`" :value="10" />
                  <el-option :label="`20条/页`" :value="20" />
                  <el-option :label="`50条/页`" :value="50" />
                  <el-option :label="`100条/页`" :value="100" />
                </el-select>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
:deep(.el-tree-node__content) {
  height: 26px;
}
</style>
