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

const dimension = ref('town')

const metrics = ref([
  { label: '台历耕园地总面积和亩', value: '817526.1' },
  { label: '已确权面积和亩', value: '904830.49' },
  { label: '整体任务完成比例', value: '110.68 %' },
  { label: '未确权耕园地总面积和亩', value: '216880.72' },
  { label: '耕园地中已确权面积', value: '191111.89' },
  { label: '耕园确权完成率', value: '88.12 %' },
  { label: '未确权耕园地地块总数', value: '145107' },
  { label: '已确权地块数', value: '122555' },
  { label: '完成地块数百分比', value: '84.46 %' }
])

function buildRows() {
  const names = [
    { code: '430381001', name: '望春门街道' },
    { code: '430381002', name: '新湘路街道' },
    { code: '430381003', name: '昆仑桥街道' },
    { code: '430381004', name: '东山街道' },
    { code: '430381106', name: '壶天镇' },
    { code: '430381107', name: '翻江镇' },
    { code: '430381110', name: '月山镇' }
  ]

  return Array.from({ length: 42 }, (_, i) => {
    const base = names[i % names.length]
    const seed = i + 1
    const u = Number(((seed * 17.23) % 600).toFixed(2))
    const u1 = Number(((seed * 2.13) % 60).toFixed(2))
    const u2 = Number(((seed * 1.19) % 50).toFixed(2))
    const doneArea = Number(((seed * 19.31) % 650).toFixed(2))
    const doneParcelArea = Number(((seed * 18.97) % 620).toFixed(2))
    const doneParcelGarden = Number(((seed * 3.11) % 70).toFixed(2))
    const doneParcels = (seed * 37) % 980
    const undoneParcels = (seed * 13) % 120
    const arriveArea = Number(((seed * 11.17) % 260).toFixed(2))
    const arriveParcel = (seed * 7) % 220
    const arriveCollective = Number(((seed * 9.21) % 420).toFixed(2))
    const arriveCollectiveCount = (seed * 11) % 320

    return {
      id: i + 1,
      regionCode: base.code,
      regionName: base.name,
      unconfirmCultivatedArea: u,
      unconfirmGardenArea: u1,
      unfinishConfirmArea: u2,
      finishConfirmArea: doneArea,
      confirmCultivatedArea: doneParcelArea,
      confirmGardenArea: doneParcelGarden,
      confirmParcels: doneParcels,
      unconfirmParcels: undoneParcels,
      arriveArea,
      arriveParcels: arriveParcel,
      arriveCollectiveArea: arriveCollective,
      arriveCollectiveParcels: arriveCollectiveCount
    }
  })
}

const allRows = ref(buildRows())

const pageSize = ref(20)
const currentPage = ref(1)
const jumpPage = ref(1)
const total = computed(() => allRows.value.length)
const pageRows = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return allRows.value.slice(start, start + pageSize.value)
})

watch([pageSize, dimension], () => {
  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 handleExport(name) {
  ElMessage.success(`${name}导出任务已提交`)
}

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

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

onMounted(async () => {
  await nextTick()
  ensureTableLayout()
  if (contentWrapEl.value && !resizeObserver) {
    resizeObserver = new ResizeObserver(() => ensureTableLayout())
    resizeObserver.observe(contentWrapEl.value)
  }
})

onBeforeUnmount(() => {
  resizeObserver?.disconnect?.()
  resizeObserver = null
})
</script>

<template>
  <div ref="contentWrapEl" class="h-full w-full bg-white overflow-hidden flex flex-col">
    <div class="grid grid-cols-9 gap-2 p-2 border-b border-gray-200">
      <div v-for="m in metrics" :key="m.label" class="border border-gray-200 rounded bg-white px-2 py-2">
        <div class="text-xs text-gray-600 truncate">{{ m.label }}</div>
        <div class="text-2xl text-blue-700 mt-1">{{ m.value }}</div>
      </div>
    </div>

    <div class="px-2 py-2 flex items-center justify-between">
      <div class="flex items-center gap-2">
        <el-button :type="dimension === 'parcel' ? 'success' : 'primary'" @click="dimension = 'parcel'">按村统计</el-button>
        <el-button :type="dimension === 'town' ? 'success' : 'primary'" @click="dimension = 'town'">按乡镇统计</el-button>
        <el-button type="primary" @click="handleExport('分析数据已确权明细')">分析数据已确权明细导出</el-button>
        <el-button type="primary" @click="handleExport('分析数据未确权明细')">分析数据未确权明细导出</el-button>
      </div>
      <div class="flex items-center gap-2">
        <el-button :icon="Grid" circle size="small" />
        <el-button :icon="Download" circle size="small" @click="handleExport('当前列表')" />
        <el-button :icon="Printer" circle size="small" @click="handleExport('打印')" />
      </div>
    </div>

    <div class="flex-1 px-2 pb-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>
            <el-table-column label="#" width="56" align="center">
              <template #default="{ $index }">
                {{ (currentPage - 1) * pageSize + $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="regionCode" label="行政区代码" min-width="160" show-overflow-tooltip />
            <el-table-column prop="regionName" label="行政区名称" min-width="160" show-overflow-tooltip />
            <el-table-column prop="unconfirmCultivatedArea" label="未确权耕地面积" min-width="140" />
            <el-table-column prop="unconfirmGardenArea" label="未确权园地面积" min-width="140" />
            <el-table-column prop="unfinishConfirmArea" label="未完成确权面积" min-width="140" />
            <el-table-column prop="finishConfirmArea" label="已完成确权面积" min-width="140" />
            <el-table-column prop="confirmCultivatedArea" label="已确权耕地面积" min-width="140" />
            <el-table-column prop="confirmGardenArea" label="已确权园地面积" min-width="140" />
            <el-table-column prop="confirmParcels" label="已确权地块数" min-width="120" />
            <el-table-column prop="unconfirmParcels" label="未确权地块数" min-width="120" />
            <el-table-column prop="arriveArea" label="确权到户面积" min-width="120" />
            <el-table-column prop="arriveParcels" label="确权到户地块数" min-width="140" />
            <el-table-column prop="arriveCollectiveArea" label="确权到集体面积" min-width="140" />
            <el-table-column prop="arriveCollectiveParcels" label="确权到集体地块数" min-width="160" />
          </el-table>
        </div>

        <div class="h-12 px-2 border-t border-gray-200 flex items-center justify-between">
          <div class="flex items-center gap-2">
            <el-button :icon="Refresh" circle @click="handleRefresh" />
          </div>
          <div class="flex items-center gap-2">
            <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>
              <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>
</template>
