<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Box, CircleClose, Download, Grid, Refresh, Search, View } 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: [] },
      { 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: '220-01', label: '[01] 第一民主组', children: [] },
          { id: '220-02', label: '[02] 第二民主组', children: [] },
          { id: '220-03', label: '[03] 第三民主组', children: [] },
          { id: '220-04', label: '[04] 第四民主组', children: [] },
          { id: '220-05', label: '[05] 第五民主组', children: [] },
          { id: '220-06', label: '[06] 第六民主组', children: [] },
          { id: '220-07', label: '[07] 第七民主组', children: [] },
          { id: '220-08', label: '[08] 第八民主组', 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 tableRef = ref(null)
const selectedRows = ref([])

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

const allRows = ref([
  {
    id: 1,
    districtId: '220-01',
    districtName: '湘乡市壶天镇合东村第一民主组',
    contractorCode: '43038110622001',
    contractorName: '彭霞冬',
    changeTime: '2025-10-19 00:14:55',
    changeContent: '从地块属性删除',
    operator: '许皓亮'
  },
  {
    id: 2,
    districtId: '220-01',
    districtName: '湘乡市壶天镇合东村第一民主组',
    contractorCode: '430381106220010007',
    contractorName: '彭霞冬',
    changeTime: '2025-10-11 15:14:26',
    changeContent: '新增地块[00200]合东村旱地0.75亩',
    operator: '许皓亮'
  },
  {
    id: 3,
    districtId: '220-01',
    districtName: '湘乡市壶天镇合东村第一民主组',
    contractorCode: '430381106220010014',
    contractorName: '刘雪华',
    changeTime: '2025-10-11 15:14:26',
    changeContent: '新增地块[00200]合东村旱地0.76亩',
    operator: '许皓亮'
  },
  {
    id: 4,
    districtId: '220-01',
    districtName: '湘乡市壶天镇合东村第一民主组',
    contractorCode: '430381106220010015',
    contractorName: '刘小华',
    changeTime: '2025-10-11 15:14:26',
    changeContent: '新增地块[00200]合东村旱地0.74亩',
    operator: '许皓亮'
  },
  {
    id: 5,
    districtId: '220-01',
    districtName: '湘乡市壶天镇合东村第一民主组',
    contractorCode: '430381106220010017',
    contractorName: '刘志华',
    changeTime: '2025-10-11 15:14:26',
    changeContent: '新增地块[00200]合东村旱地0.75亩',
    operator: '许皓亮'
  },
  {
    id: 6,
    districtId: '220-01',
    districtName: '湘乡市壶天镇合东村第一民主组',
    contractorCode: '430381106220010054',
    contractorName: '叶桂科',
    changeTime: '2025-10-11 15:14:26',
    changeContent: '新增地块[00200]合东村旱地0.77亩',
    operator: '许皓亮'
  },
  {
    id: 7,
    districtId: '220-02',
    districtName: '湘乡市壶天镇合东村第二民主组',
    contractorCode: '43038110622001',
    contractorName: '彭霞冬',
    changeTime: '2025-10-11 15:12:32',
    changeContent: '从地块属性删除',
    operator: '许皓亮'
  },
  {
    id: 8,
    districtId: '220-03',
    districtName: '湘乡市壶天镇合东村第三民主组',
    contractorCode: '430381106220010007',
    contractorName: '彭霞冬',
    changeTime: '2025-10-11 14:59:03',
    changeContent: '新增地块[00199]合东村旱地0.74亩',
    operator: '许皓亮'
  },
  {
    id: 9,
    districtId: '220-04',
    districtName: '湘乡市壶天镇合东村第四民主组',
    contractorCode: '430381106220010003',
    contractorName: '傅翼武',
    changeTime: '2025-10-11 14:59:03',
    changeContent: '新增地块[00199]合东村旱地0.75亩',
    operator: '许皓亮'
  },
  {
    id: 10,
    districtId: '220-05',
    districtName: '湘乡市壶天镇合东村第五民主组',
    contractorCode: '430381106220010006',
    contractorName: '彭秋冬',
    changeTime: '2025-10-11 14:59:03',
    changeContent: '新增地块[00199]合东村旱地0.75亩',
    operator: '许皓亮'
  },
  {
    id: 11,
    districtId: '220-06',
    districtName: '湘乡市壶天镇合东村第六民主组',
    contractorCode: '43038110622001',
    contractorName: '彭秋冬',
    changeTime: '2025-10-11 14:57:25',
    changeContent: '从地块属性删除',
    operator: '许皓亮'
  },
  {
    id: 12,
    districtId: '220-07',
    districtName: '湘乡市壶天镇合东村第七民主组',
    contractorCode: '43038110622001',
    contractorName: '彭秋冬',
    changeTime: '2025-10-11 13:44:50',
    changeContent: '从地块属性删除',
    operator: '许皓亮'
  },
  {
    id: 13,
    districtId: '220-08',
    districtName: '湘乡市壶天镇合东村第八民主组',
    contractorCode: '43038110622001',
    contractorName: '彭秋冬',
    changeTime: '2025-10-11 13:38:28',
    changeContent: '从地块属性删除',
    operator: '许皓亮'
  },
  {
    id: 14,
    districtId: '203',
    districtName: '湘乡市壶天镇大坪村',
    contractorCode: '43038110622001',
    contractorName: '彭秋冬',
    changeTime: '2025-10-11 13:37:43',
    changeContent: '从地块属性删除',
    operator: '许皓亮'
  },
  {
    id: 15,
    districtId: '206',
    districtName: '湘乡市壶天镇石狗村',
    contractorCode: '430381106220010039',
    contractorName: '叶国明',
    changeTime: '2025-10-11 13:15:11',
    changeContent: '新增地块[00188]合东村水田0.20亩',
    operator: '许皓亮'
  },
  {
    id: 16,
    districtId: '207',
    districtName: '湘乡市壶天镇壶天村',
    contractorCode: '43038110622001',
    contractorName: '叶国明',
    changeTime: '2025-10-11 12:48:59',
    changeContent: '从地块属性删除',
    operator: '许皓亮'
  },
  {
    id: 17,
    districtId: '210',
    districtName: '湘乡市壶天镇中石村',
    contractorCode: '430381106220010018',
    contractorName: '傅冬秀',
    changeTime: '2025-08-30 12:43:24',
    changeContent: '删除地块[00099]池子坵0.07亩(删除图形与信息)',
    operator: '侯清平'
  },
  {
    id: 18,
    districtId: '214',
    districtName: '湘乡市壶天镇光辉村',
    contractorCode: '430381106220010003',
    contractorName: '傅翼武',
    changeTime: '2025-08-30 12:42:46',
    changeContent: '删除地块[00102]池子坵0.01亩(删除图形与信息)',
    operator: '侯清平'
  }
])

const viewDialogOpen = ref(false)
const viewData = ref(null)
const viewActiveTab = ref('base')

const filteredRows = computed(() => {
  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 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], () => {
  currentPage.value = 1
  jumpPage.value = 1
})

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

function handleRefresh() {
  selectedRows.value = []
  tableRef.value?.clearSelection?.()
  ElMessage.success('刷新成功')
}

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

function openView(row) {
  const full = allRows.value.find((r) => r.id === row?.id) || row
  viewData.value = {
    ...full,
    reportSource: '内业平台',
    bizType: '延包变更',
    operatorDept: '湘乡市壶天镇项目组',
    operateTime: full?.changeTime || '',
    relatedParcels: [
      { code: '00188', type: '水田', area: '0.20', action: '新增' },
      { code: '00199', type: '旱地', area: '0.75', action: '新增' }
    ]
  }
  viewActiveTab.value = 'base'
  viewDialogOpen.value = true
}

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 contentWrapEl = ref(null)
let resizeObserver = null
function ensureTableLayout() {
  nextTick(() => tableRef.value?.doLayout?.())
}

onMounted(async () => {
  await nextTick()
  handleTreeNodeClick(treeData.value?.[0]?.children?.find?.((v) => v.id === '220') || treeData.value?.[0])
  treeRef.value?.setCurrentKey?.('220')
  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" clearable class="mt-2" placeholder="搜索">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </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="h-12 px-3 border-b border-gray-200 flex items-center justify-between">
          <div class="flex items-center gap-2">
            <el-button type="primary" size="small" :icon="Refresh" @click="handleRefresh">刷新</el-button>
            <el-button type="primary" size="small" :icon="Download" @click="handleExport">导出</el-button>
          </div>
          <div class="flex items-center gap-2">
            <el-button :icon="Grid" circle size="small" />
            <el-button :icon="Box" circle size="small" />
            <el-button :icon="CircleClose" circle size="small" />
          </div>
        </div>

        <div class="flex-1 p-2 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="44" 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="districtName" label="行政区划名称" min-width="240" show-overflow-tooltip />

                <el-table-column prop="contractorCode" min-width="190">
                  <template #header>
                    <div class="flex items-center gap-1">
                      <span>承包方编码</span>
                      <el-icon class="text-gray-400"><Search /></el-icon>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="contractorName" min-width="130">
                  <template #header>
                    <div class="flex items-center gap-1">
                      <span>承包方名称</span>
                      <el-icon class="text-gray-400"><Search /></el-icon>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="changeTime" label="变更时间" min-width="170" sortable />

                <el-table-column prop="changeContent" min-width="300" show-overflow-tooltip>
                  <template #header>
                    <div class="flex items-center gap-1">
                      <span>变更内容</span>
                      <el-icon class="text-gray-400"><Search /></el-icon>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="operator" label="操作人" width="120" align="center" />

                <el-table-column label="" width="110" align="center" fixed="right">
                  <template #default="{ row }">
                    <el-button type="success" size="small" :icon="View" @click="openView(row)">查看</el-button>
                  </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>

    <el-dialog v-model="viewDialogOpen" width="900px" :close-on-click-modal="false">
      <template #header>
        <div class="flex items-center justify-between pr-2">
          <div class="text-sm font-medium text-gray-800">查看记录</div>
          <div class="text-xs text-gray-500">{{ viewData?.operateTime || '' }}</div>
        </div>
      </template>

      <el-tabs v-model="viewActiveTab" class="!mt-1">
        <el-tab-pane label="基本信息" name="base">
          <div class="grid grid-cols-2 gap-3">
            <div class="border border-gray-200">
              <div class="h-9 px-3 flex items-center text-sm font-medium text-gray-800 border-b border-gray-200 bg-gray-50">对象信息</div>
              <div class="p-3 text-sm text-gray-700 space-y-2">
                <div class="flex"><div class="w-24 text-gray-500">行政区划</div><div class="flex-1">{{ viewData?.districtName || '-' }}</div></div>
                <div class="flex"><div class="w-24 text-gray-500">承包方编码</div><div class="flex-1">{{ viewData?.contractorCode || '-' }}</div></div>
                <div class="flex"><div class="w-24 text-gray-500">承包方名称</div><div class="flex-1">{{ viewData?.contractorName || '-' }}</div></div>
              </div>
            </div>

            <div class="border border-gray-200">
              <div class="h-9 px-3 flex items-center text-sm font-medium text-gray-800 border-b border-gray-200 bg-gray-50">操作信息</div>
              <div class="p-3 text-sm text-gray-700 space-y-2">
                <div class="flex"><div class="w-24 text-gray-500">业务类型</div><div class="flex-1">{{ viewData?.bizType || '-' }}</div></div>
                <div class="flex"><div class="w-24 text-gray-500">来源</div><div class="flex-1">{{ viewData?.reportSource || '-' }}</div></div>
                <div class="flex"><div class="w-24 text-gray-500">操作人</div><div class="flex-1">{{ viewData?.operator || '-' }}</div></div>
                <div class="flex"><div class="w-24 text-gray-500">所属部门</div><div class="flex-1">{{ viewData?.operatorDept || '-' }}</div></div>
              </div>
            </div>
          </div>

          <div class="mt-3 border border-gray-200">
            <div class="h-9 px-3 flex items-center text-sm font-medium text-gray-800 border-b border-gray-200 bg-gray-50">变更内容</div>
            <div class="p-3">
              <el-input :model-value="viewData?.changeContent || ''" type="textarea" :rows="4" readonly />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="关联地块" name="parcels">
          <el-table :data="viewData?.relatedParcels || []" border stripe>
            <el-table-column prop="code" label="地块编码" width="120" align="center" />
            <el-table-column prop="type" label="地类" width="120" align="center" />
            <el-table-column prop="area" label="面积(亩)" width="120" align="center" />
            <el-table-column prop="action" label="动作" width="120" align="center" />
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div class="flex items-center justify-end">
          <el-button size="small" @click="viewDialogOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

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