<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Box, CircleClose, 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) => ({
          id: `203-${String(i + 1).padStart(2, '0')}`,
          label: `[${String(i + 1).padStart(2, '0')}] 大坪第${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 codeInput = ref('')

const checkOptions = [
  { code: '1', label: '承包方不在成员内' },
  { code: '2', label: '性别错误' },
  { code: '3', label: '姓名错误' },
  { code: '4', label: '户主关系错误' },
  { code: '5', label: '承包方名称警告' },
  { code: '6', label: '发包方、承包方证件号错误' },
  { code: '7', label: '成员证件号码错误' },
  { code: '8', label: '承包方证件号重复' },
  { code: '9', label: '成员证件号重复' },
  { code: '10', label: '承包合同内承包地块数量错误' },
  { code: '11', label: '家庭成员成员数备注错误' },
  { code: '12', label: '时间逻辑错误' },
  { code: '13', label: '地块图形错误' },
  { code: '14', label: '地块四至错误' },
  { code: '15', label: '承包信息错误' },
  { code: '16', label: '发包方名称与农局单位名称不一致' },
  { code: '17', label: '承包关系错误' },
  { code: '18', label: '发包方编码与承包方编码前14位不一致' },
  { code: '19', label: '地块编码与承包方编码前14位不一致' },
  { code: '20', label: '发包方缺失' },
  { code: '21', label: '证件号码为空' },
  { code: '22', label: '地块名称为空' }
]

const selectedCodes = ref([])
const checkAll = ref(false)
const indeterminate = computed(() => selectedCodes.value.length > 0 && selectedCodes.value.length < checkOptions.length)

watch(selectedCodes, (val) => {
  checkAll.value = val.length === checkOptions.length
})

function toggleAll(val) {
  selectedCodes.value = val ? checkOptions.map((o) => o.code) : []
}

const tableRef = ref(null)
const selectedRows = ref([])

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

const errorDescMap = Object.fromEntries(checkOptions.map((o) => [o.code, o.label]))

function buildRows() {
  const districts = [
    { id: '203-01', name: '湘乡市壶天镇大坪村第一村民组' },
    { id: '203-02', name: '湘乡市壶天镇大坪村第二村民组' },
    { id: '203-03', name: '湘乡市壶天镇大坪村第三村民组' },
    { id: '203-04', name: '湘乡市壶天镇大坪村第四村民组' },
    { id: '206', name: '湘乡市壶天镇石狗村' },
    { id: '207', name: '湘乡市壶天镇壶天村' },
    { id: '210', name: '湘乡市壶天镇中石村' },
    { id: '214', name: '湘乡市壶天镇光辉村' },
    { id: '220', name: '湘乡市壶天镇合东村' },
    { id: '222', name: '湘乡市壶天镇南岳坪村' },
    { id: '224', name: '湘乡市壶天镇上新桥村' },
    { id: '230', name: '湘乡市壶天镇双坪村' }
  ]

  const contractors = [
    { name: '彭霞冬', code: '430381106220010007' },
    { name: '刘雪华', code: '430381106220010014' },
    { name: '刘小华', code: '430381106220010015' },
    { name: '叶桂科', code: '430381106220010054' },
    { name: '傅翼武', code: '430381106220010003' },
    { name: '彭秋冬', code: '430381106220010006' },
    { name: '侯清平', code: '430381106220010018' },
    { name: '陈国福', code: '430381106220010046' },
    { name: '王桂花', code: '430381106220010019' }
  ]

  const errorCodes = checkOptions.map((o) => o.code)

  return Array.from({ length: 58 }, (_, idx) => {
    const district = districts[idx % districts.length]
    const contractor = contractors[idx % contractors.length]
    const errorCode = errorCodes[idx % errorCodes.length]
    return {
      id: idx + 1,
      districtId: district.id,
      districtName: district.name,
      contractorName: contractor.name,
      contractorCode: contractor.code,
      errorCode,
      errorDesc: errorDescMap[errorCode] || '未知错误'
    }
  })
}

const allRows = ref(buildRows())

const filteredByTree = 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 filteredRows = computed(() => {
  const codes = selectedCodes.value
  const rawInput = String(codeInput.value || '').trim()
  const inputCodes = rawInput
    ? rawInput
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean)
        .slice(0, 300)
    : []

  return filteredByTree.value.filter((r) => {
    const codeOk = codes.length ? codes.includes(String(r.errorCode)) : true
    const inputOk = inputCodes.length ? inputCodes.includes(String(r.contractorCode || '')) : true
    return codeOk && inputOk
  })
})

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

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

function handleCheck() {
  ElMessage.success(`检查完成，共 ${total.value} 条`)
  ensureTableLayout()
}

function handleClear() {
  codeInput.value = ''
  selectedCodes.value = []
  selectedRows.value = []
  tableRef.value?.clearSelection?.()
  ElMessage.success('已清空')
}

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

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

function handleBatchAction(name) {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先选择数据')
    return
  }
  ElMessage.success(`${name} 已处理 ${selectedRows.value.length} 条`)
}

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

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 === '203') || treeData.value?.[0])
  treeRef.value?.setCurrentKey?.('203')
  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 gap-3">
            <el-input
              v-model="codeInput"
              maxlength="300"
              show-word-limit
              clearable
              placeholder="筛选承包方编码(多个用,分隔) 最多输入300个字符"
              class="flex-1"
            />
            <el-button class="!bg-gray-200 !text-gray-700 !border-gray-200" @click="handleExportParcelRemark">导出地块备注信息</el-button>
            <el-button class="!bg-orange-500 !text-white !border-orange-500" @click="handleClear">清空</el-button>
            <el-button type="success" @click="handleExportNetSignPack">导出网签数据包</el-button>
          </div>

          <div class="mt-3 flex items-center justify-between">
            <div class="flex-1 flex items-center gap-4 overflow-hidden">
              <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="toggleAll">全选</el-checkbox>
              <el-checkbox-group v-model="selectedCodes" class="flex-1 overflow-hidden">
                <div class="flex flex-wrap gap-x-4 gap-y-2">
                  <el-checkbox v-for="o in checkOptions" :key="o.code" :label="o.code">
                    {{ o.code }}.{{ o.label }}
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
            <el-button type="success" class="!ml-3" :icon="Search" @click="handleCheck">检查</el-button>
          </div>

          <div class="mt-4 flex items-center justify-between">
            <div class="flex flex-wrap gap-2">
              <el-button size="small" @click="handleBatchAction('驳回证件号码错误、重复记录')">驳回证件号码错误、重复记录</el-button>
              <el-button size="small" @click="handleSimpleAction('默认设置')">默认设置</el-button>
              <el-button size="small" @click="handleSimpleAction('设置发包方信息')">设置发包方信息</el-button>
              <el-button size="small" @click="handleSimpleAction('设置承包方信息')">设置承包方信息</el-button>
              <el-button size="small" @click="handleBatchAction('更新合同')">更新合同</el-button>
              <el-button size="small" @click="handleBatchAction('更新承包经营权证、登记簿')">更新承包经营权证、登记簿</el-button>
              <el-button size="small" @click="handleSimpleAction('质检更新')">质检更新</el-button>
              <el-button size="small" @click="handleSimpleAction('证件号码重复清单')">证件号码重复清单</el-button>
              <el-button size="small" @click="handleBatchAction('刷新地块')">刷新地块</el-button>
              <el-button size="small" @click="handleBatchAction('恢复空包户')">恢复空包户</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>

        <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="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="contractorName" label="承包方名称" width="140" show-overflow-tooltip />
                <el-table-column prop="contractorCode" label="承包方编码" min-width="190" show-overflow-tooltip />
                <el-table-column prop="errorDesc" label="错误说明" min-width="260" 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" :icon="Refresh" @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>
