<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Download, Grid, Plus, Printer, 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 codeFilterOpen = ref(false)
const nameFilterOpen = ref(false)
const codeFilter = ref('')
const nameFilter = ref('')

const editEnabled = ref(false)

function buildRows() {
  const villageMap = new Map([
    ['203', { village: '大坪村', base: '430381106203' }],
    ['206', { village: '石狗村', base: '430381106206' }],
    ['222', { village: '南岳坪村', base: '430381106222' }],
    ['224', { village: '上新桥村', base: '430381106224' }],
    ['229', { village: '潭桥村', base: '430381106229' }]
  ])

  const rows = []
  let id = 1

  for (const [villageId, meta] of villageMap.entries()) {
    const { village, base } = meta
    rows.push({
      id: id++,
      districtId: villageId,
      ownerCode: `${base}00`,
      ownerName: `湘乡市壶天镇${village}`,
      ownerShortCode: base,
      ownerAbbr: village
    })
    for (let i = 1; i <= 12; i++) {
      const suffix = String(i).padStart(2, '0')
      const code = `${base}${suffix}`
      rows.push({
        id: id++,
        districtId: villageId,
        ownerCode: code,
        ownerName: `湘乡市壶天镇${village}${village}第${i}村民组`.replace(`${village}${village}`, village),
        ownerShortCode: code,
        ownerAbbr: `${village}第${i}村民组`
      })
    }
  }

  const dup = rows.filter((r) => r.districtId === '203' && r.ownerCode.endsWith('03')).slice(0, 1)
  if (dup.length) {
    rows.splice(5, 0, { ...dup[0], id: id++ })
  }
  return rows
}

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 code = String(codeFilter.value || '').trim()
  const name = String(nameFilter.value || '').trim()
  return filteredByTree.value.filter((r) => {
    if (code && !String(r.ownerCode || '').includes(code)) return false
    if (name && !String(r.ownerName || '').includes(name)) return false
    return 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, codeFilter, nameFilter], () => {
  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
}

const selectedRows = ref([])
function handleSelectionChange(rows) {
  selectedRows.value = rows || []
}

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

function handleDownloadMapping() {
  ElMessage.success('下载任务已提交')
}

async function handleDeleteSelected() {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先勾选要删除的记录')
    return
  }
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录？`, '提示', { type: 'warning' })
    const ids = new Set(selectedRows.value.map((r) => r.id))
    allRows.value = allRows.value.filter((r) => !ids.has(r.id))
    selectedRows.value = []
    ElMessage.success('已删除')
  } catch {
    //
  }
}

function handleAdd() {
  ElMessage.success('已新增一条记录')
  const nextId = Math.max(0, ...allRows.value.map((r) => Number(r.id) || 0)) + 1
  allRows.value = [
    {
      id: nextId,
      districtId: selectedNodeId.value || '203',
      ownerCode: '43038110620399',
      ownerName: '湘乡市壶天镇大坪村示例权属单位',
      ownerShortCode: '43038110620399',
      ownerAbbr: '示例权属单位'
    },
    ...allRows.value
  ]
}

function handleClearDuplicates() {
  const seen = new Set()
  const before = allRows.value.length
  allRows.value = allRows.value.filter((r) => {
    const key = String(r.ownerCode || '')
    if (!key) return true
    if (seen.has(key)) return false
    seen.add(key)
    return true
  })
  const removed = before - allRows.value.length
  ElMessage.success(removed ? `已清除重复记录：${removed} 条` : '未发现重复记录')
}

function handlePrint() {
  ElMessage.success('打印任务已提交')
}

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-3 py-2 border-b border-gray-200">
          <div class="flex items-center gap-2">
            <el-button :icon="Refresh" circle size="small" @click="handleRefresh" />
            <el-button :icon="Plus" circle size="small" @click="handleAdd" />
            <el-button :icon="Delete" circle size="small" @click="handleDeleteSelected" />
            <el-button type="success" size="small" @click="handleClearDuplicates">清除重复行政区</el-button>
            <el-button type="primary" size="small" @click="handleDownloadMapping">下载合村对照表</el-button>
            <el-checkbox v-model="editEnabled" class="ml-2">开启编辑</el-checkbox>
          </div>
          <div class="flex items-center gap-2">
            <el-button :icon="Grid" circle size="small" />
            <el-button :icon="Download" circle size="small" @click="handleDownloadMapping" />
            <el-button :icon="Printer" circle size="small" @click="handlePrint" />
          </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
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="46" align="center" />
                <el-table-column label="#" width="56" align="center">
                  <template #default="{ $index }">
                    {{ (currentPage - 1) * pageSize + $index + 1 }}
                  </template>
                </el-table-column>

                <el-table-column prop="ownerCode" label="权属单位代码" min-width="190" show-overflow-tooltip>
                  <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="ownerName" label="权属单位名称" min-width="320" show-overflow-tooltip>
                  <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>
                  <template #default="{ row }">
                    <el-input v-if="editEnabled" v-model="row.ownerName" size="small" />
                    <span v-else>{{ row.ownerName }}</span>
                  </template>
                </el-table-column>

                <el-table-column prop="ownerShortCode" label="权属单位简码" min-width="190" show-overflow-tooltip />

                <el-table-column prop="ownerAbbr" label="权属单位简称" min-width="180" show-overflow-tooltip>
                  <template #default="{ row }">
                    <el-input v-if="editEnabled" v-model="row.ownerAbbr" size="small" />
                    <span v-else>{{ row.ownerAbbr }}</span>
                  </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>
