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

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

const treeData = ref([
  {
    id: '106',
    label: '106壶天镇',
    children: []
  },
  {
    id: '107',
    label: '107翻江镇',
    children: []
  },
  {
    id: '110',
    label: '110月山镇',
    children: [
      { id: '202', label: '202蔡虫山村', children: [] },
      {
        id: '210',
        label: '210白龙村',
        children: Array.from({ length: 31 }, (_, i) => {
          const no = String(i + 1).padStart(2, '0')
          return { id: `210-${no}`, label: `[${no}] 白龙村${no}组`, children: [] }
        })
      },
      { id: '215', label: '215马龙村', children: [] },
      { id: '216', label: '216田心村', children: [] },
      { id: '218', label: '218龙洞村', children: [] },
      { id: '226', label: '226红日村', children: [] },
      { id: '230', label: '230月山村', children: [] },
      { id: '236', label: '236洪湾村', children: [] },
      { id: '238', label: '238云南村', children: [] },
      { id: '241', label: '241青草村', children: [] },
      { id: '244', label: '244新桥村', children: [] },
      { id: '247', label: '247江田村', children: [] },
      { id: '253', label: '253石柱村', children: [] },
      { id: '258', label: '258石机村', children: [] },
      { id: '259', label: '259两头塘村', children: [] },
      { id: '260', label: '260先锋村', children: [] },
      { id: '262', label: '262紫云村', 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) {
  return true
}

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

watch(scopeSelect, (v) => {
  if (v === 'all') selectedSubtreeIds.value = null
})

const codeFilterOpen = ref(false)
const nameFilterOpen = ref(false)
const codeFilter = ref('')
const nameFilter = ref('')

function buildRows() {
  const groups = Array.from({ length: 31 }, (_, i) => {
    const no = String(i + 1).padStart(2, '0')
    return { id: `210-${no}`, no, address: `湘乡市月山镇白龙村${no}组` }
  })

  const people = [
    '曾光明',
    '曾光耀',
    '陈光辉',
    '陈光耀',
    '陈中建',
    '陈建平',
    '陈光明',
    '吴爱萍',
    '陈哲宇',
    '贺房根',
    '贺桥生',
    '廖建超',
    '廖凤良',
    '成国清',
    '廖建华',
    '廖建平',
    '廖泽阳',
    '廖余良'
  ]

  const changeTemplates = [
    (name) => `新增1名家庭成员：[${name}]，删除2名家庭成员：[周南秀、曾惠林]，承包方联系电话从[无]变更为[173xxxxxxx]`,
    (name) => `新增6名家庭成员：[${name}、袁小丰、陈呈昊、陈妍薇、冯雅妮、陈鸿毅]，删除1名家庭成员：[陈光耀]`,
    (name) => `修改1名家庭成员：[成员${name}: 成员证件号变更]，承包方姓名变更为[${name}]`,
    (name) => `修改1名家庭成员：[成员${name}: 与户主关系变更为(父亲)]，承包方联系电话变更`,
    (name) => `承包方联系电话从[无]变更为[1570xxxxxxx]`,
    (name) => `删除1名家庭成员：[${name}]，承包方联系电话从[无]变更为[1303xxxxxxx]`
  ]

  return Array.from({ length: 905 }, (_, idx) => {
    const g = groups[idx % groups.length]
    const contractorName = people[idx % people.length]
    const contractorCodeSuffix = String(idx + 36).padStart(3, '0')
    const contractorCode = `430381110210010${contractorCodeSuffix}`
    const changeContent = changeTemplates[idx % changeTemplates.length](contractorName)
    return {
      id: idx + 1,
      districtId: g.id,
      contractorCode,
      contractorName,
      contractorAddress: g.address,
      changeContent
    }
  })
}

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 c = String(codeFilter.value || '').trim()
  const n = String(nameFilter.value || '').trim()
  return filteredByTree.value.filter((r) => {
    const codeOk = c ? String(r.contractorCode || '').includes(c) : true
    const nameOk = n ? String(r.contractorName || '').includes(n) : true
    return codeOk && nameOk
  })
})

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, codeFilter, nameFilter, scopeSelect], () => {
  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 handleExport() {
  ElMessage.success('导出任务已提交')
}

function handleToggleGrid() {
  ElMessage.success('已切换显示')
}

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

onMounted(async () => {
  await nextTick()
  const defaultNode = treeData.value?.find?.((v) => v.id === '110') || 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>
      </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-end gap-2 px-2 py-2 border-b border-gray-200">
          <el-button :icon="Grid" circle size="small" @click="handleToggleGrid" />
          <el-button :icon="Download" circle size="small" @click="handleExport" />
          <el-button :icon="Refresh" circle size="small" @click="handleRefresh" />
        </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="contractorCode" width="190">
                  <template #header>
                    <div class="flex items-center justify-between gap-2">
                      <span>承包方编码</span>
                      <el-popover v-model:visible="codeFilterOpen" 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="codeFilter" size="small" clearable placeholder="输入编码关键字" @keyup.enter="codeFilterOpen = false" />
                          <div class="flex justify-end gap-2">
                            <el-button size="small" @click="codeFilter = ''">清空</el-button>
                            <el-button size="small" type="primary" @click="codeFilterOpen = false">确定</el-button>
                          </div>
                        </div>
                      </el-popover>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="contractorName" width="140">
                  <template #header>
                    <div class="flex items-center justify-between gap-2">
                      <span>承包方名称</span>
                      <el-popover v-model:visible="nameFilterOpen" 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="nameFilter" size="small" clearable placeholder="输入名称关键字" @keyup.enter="nameFilterOpen = false" />
                          <div class="flex justify-end gap-2">
                            <el-button size="small" @click="nameFilter = ''">清空</el-button>
                            <el-button size="small" type="primary" @click="nameFilterOpen = false">确定</el-button>
                          </div>
                        </div>
                      </el-popover>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="contractorAddress" label="承包方地址" min-width="220" show-overflow-tooltip />
                <el-table-column prop="changeContent" label="变更内容" min-width="420" show-overflow-tooltip />
              </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>
