<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, Grid, Refresh } 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)
const selectedLabel = ref('')

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 || ''
  selectedLabel.value = data?.label || ''
  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))

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

const activeTab = ref('add')
const tabOptions = [
  { key: 'add', label: '新增承包方清单' },
  { key: 'split', label: '分户清单' },
  { key: 'merge', label: '合户清单' },
  { key: 'cancel', label: '销户清单' },
  { key: 'memberAdd', label: '新增家庭成员清单' },
  { key: 'memberDel', label: '删除家庭成员清单' }
]

function buildRows() {
  const townName = '壶天镇'
  const villageList = [
    { id: '203', name: '大坪村', groups: 12 },
    { id: '206', name: '石狗村', groups: 0 },
    { id: '207', name: '壶天村', groups: 0 },
    { id: '210', name: '中石村', groups: 0 },
    { id: '214', name: '光辉村', groups: 0 }
  ]

  const people = [
    '李菊香',
    '罗兴华',
    '彭霞冬',
    '刘雪华',
    '刘小华',
    '叶桂科',
    '傅翼武',
    '彭秋冬',
    '廖建华',
    '陈国福',
    '王桂花',
    '吴爱萍',
    '侯清平'
  ]

  const idCards = [
    '430322199506126067',
    '430322196201216011',
    '430381199201011234',
    '430381198812123456',
    '430381197611223344',
    '430381198009091234',
    '430381196512031234',
    '430381199903231234'
  ]

  const types = ['add', 'split', 'merge', 'cancel', 'memberAdd', 'memberDel']

  const list = []
  let id = 1
  for (let i = 0; i < 160; i++) {
    const v = villageList[i % villageList.length]
    const groupNo = v.groups ? String((i % v.groups) + 1).padStart(2, '0') : ''
    const districtId = groupNo ? `${v.id}-${groupNo}` : v.id
    const type = types[i % types.length]
    const contractorName = people[i % people.length]
    const contractorCode = `430381106${String(200 + (i % 90)).padStart(3, '0')}0100${String(31 + (i % 120)).padStart(3, '0')}`
    const idCard = idCards[i % idCards.length]
    const address = `湘乡市${townName}${v.name}${groupNo ? `第${Number(groupNo)}组` : ''}`

    const reportContent =
      type === 'add'
        ? `新增承包方：[${contractorName}]`
        : type === 'split'
          ? `分户：从原户拆分出承包方[${contractorName}]`
          : type === 'merge'
            ? `合户：合并承包方信息至[${contractorName}]`
            : type === 'cancel'
              ? `销户：承包方[${contractorName}]办理销户`
              : type === 'memberAdd'
                ? `新增家庭成员：[${contractorName}]`
                : `删除家庭成员：[${contractorName}]`

    const remark = i % 7 === 0 ? '承包方地址从[null]补录' : ''

    list.push({
      id,
      districtId,
      townName,
      villageName: v.name,
      groupName: groupNo ? `大坪第${Number(groupNo)}组` : '',
      contractorCode,
      contractorName,
      contractorIdCard: idCard,
      contractorAddress: address,
      reportContent,
      contractorRemark: remark,
      changeType: type,
      addMembers: type === 'memberAdd' ? (i % 5) + 1 : 0,
      delMembers: type === 'memberDel' ? (i % 4) + 1 : 0
    })
    id++
  }
  return list
}

const allRows = ref(buildRows())

const filteredByTree = computed(() => {
  const ids = selectedSubtreeIds.value
  if (scopeSelect.value === 'all') return allRows.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 stats = computed(() => {
  const list = filteredByTree.value
  const baseMap = {
    '203': 380,
    '206': 152,
    '207': 98,
    '210': 132,
    '214': 121
  }
  const baseKey = String(selectedNodeId.value || '').split('-')[0]
  const currentContractor = baseMap[baseKey] ?? 256

  return {
    currentContractor,
    addContractor: list.filter((r) => r.changeType === 'add').length,
    splitContractor: list.filter((r) => r.changeType === 'split').length,
    mergeContractor: list.filter((r) => r.changeType === 'merge').length,
    cancelContractor: list.filter((r) => r.changeType === 'cancel').length,
    addMembers: list.reduce((sum, r) => sum + (r.addMembers || 0), 0),
    delMembers: list.reduce((sum, r) => sum + (r.delMembers || 0), 0)
  }
})

const filteredRows = computed(() => filteredByTree.value.filter((r) => r.changeType === activeTab.value))

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, activeTab, selectedNodeId, 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 handleExportTown() {
  ElMessage.success('按乡镇导出任务已提交')
}

function handleExportVillage() {
  ElMessage.success('按村导出任务已提交')
}

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="px-3 pt-3">
          <div class="flex items-center justify-between gap-3">
            <div class="text-sm text-gray-900">
              承包方上报统计(湘乡市{{ selectedLabel || '壶天镇大坪村' }})
            </div>
            <div class="flex items-center gap-2">
              <el-button type="primary" @click="handleExportTown">按乡镇导出回头看数据</el-button>
              <el-button type="primary" @click="handleExportVillage">按村导出回头看数据</el-button>
            </div>
          </div>

          <div class="mt-3">
            <el-form label-width="140px">
              <el-row :gutter="12">
                <el-col :span="24">
                  <el-form-item label="现承包方数量：">
                    <el-input :model-value="stats.currentContractor" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="新增承包方数量：">
                    <el-input :model-value="stats.addContractor" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="分户承包方数量：">
                    <el-input :model-value="stats.splitContractor" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="合户承包方数量：">
                    <el-input :model-value="stats.mergeContractor" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="销户数量：">
                    <el-input :model-value="stats.cancelContractor" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="新增家庭成员数量：">
                    <el-input :model-value="stats.addMembers" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="删除家庭成员数量：">
                    <el-input :model-value="stats.delMembers" readonly />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <div class="mt-2">
            <el-tabs v-model="activeTab">
              <el-tab-pane v-for="t in tabOptions" :key="t.key" :label="t.label" :name="t.key" />
            </el-tabs>
          </div>
        </div>

        <div class="flex-1 p-3 overflow-hidden">
          <div class="h-full border border-gray-200 flex flex-col">
            <div class="px-2 py-2 flex items-center justify-between border-b border-gray-200">
              <el-button type="primary" :icon="Refresh" @click="handleRefresh">刷新</el-button>
              <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 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="townName" label="乡镇" width="100" show-overflow-tooltip />
                <el-table-column prop="villageName" label="村" width="120" show-overflow-tooltip />
                <el-table-column prop="groupName" label="组" width="140" show-overflow-tooltip />
                <el-table-column prop="contractorCode" label="承包方编码" min-width="200" show-overflow-tooltip />
                <el-table-column prop="contractorName" label="承包方名称" width="140" show-overflow-tooltip />
                <el-table-column prop="contractorIdCard" label="承包方证件号码" min-width="200" show-overflow-tooltip />
                <el-table-column prop="contractorAddress" label="承包方地址" min-width="220" show-overflow-tooltip />
                <el-table-column prop="reportContent" label="上报内容" min-width="260" show-overflow-tooltip />
                <el-table-column prop="contractorRemark" label="承包方备注" min-width="180" 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>
