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

// --- Layout & Tree ---
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: '107',
    label: '107翻江镇',
    children: [
       {
        id: '202',
        label: '202褒忠山村',
        children: []
       }
    ]
  },
  { 
    id: '110', 
    label: '110月山镇', 
    children: [
       {
        id: '210',
        label: '210白龙村',
        children: Array.from({ length: 15 }, (_, i) => {
            const no = String(i + 1).padStart(2, '0')
            return { id: `210-${no}`, label: `[${no}] 白龙村${i + 1}组`, children: [] }
        })
       }
    ] 
  }
])

const treeProps = { children: 'children', label: 'label' }
const selectedNodeId = ref('')

function filterTreeNode(value, data) {
  if (!value) return true
  return String(data?.label || '').includes(value)
}

function handleTreeNodeClick(data) {
  selectedNodeId.value = data?.id || ''
}

watch(districtSearch, (val) => treeRef.value?.filter?.(val))

// --- Tabs ---
const activeTab = ref('contractInfo') // contractInfo, comprehensive, land, contractor, contract

// --- Tab 1: 承包信息统计 ---
const statLevel = ref('')
const sortRule = ref('')
const currentPage1 = ref(1)
const pageSize1 = ref(20)

const tableData1 = ref(Array.from({ length: 15 }, (_, i) => ({
    id: i + 1,
    adminCode: `430381110210${String(i + 1).padStart(2, '0')}`,
    adminName: `湘乡市月山镇白龙村${['一', '二', '三', '四', '十六', '十五', '十八', '十七', '八', '七', '六', '九', '十一', '十', '十四'][i]}组`,
    contractorCount: Math.floor(Math.random() * 100) + 40,
    issuerCount: 1,
    measuredArea: (Math.random() * 500 + 100).toFixed(2),
    contractedArea: (Math.random() * 400 + 100).toFixed(2),
    nonContractedArea: (Math.random() * 50).toFixed(2),
    reservedArea: 0
})))

// --- Tab 2: 综合统计 ---
const subTab2 = ref('details') // details, chart
const summaryData = ref({
    adminCode: '430381110210',
    adminName: '白龙村',
    contractorCount: 1208,
    memberCount: 5094,
    landCount: 5874,
    nonContractedLandCount: 509,
    shareLandCount: 70,
    shareShares: 353,
    measuredArea: 6200.6,
    contractArea: 4546.04,
    origContractArea: 3532.95,
    contractQty: 1218,
    regBookQty: 1218,
    certQty: 1218,
    machineArea: 0,
    machineAreaRatio: '0.00%'
})

const tableData2 = ref(Array.from({ length: 15 }, (_, i) => {
    const contractor = Math.floor(Math.random() * 100) + 40
    const member = contractor * 3 + Math.floor(Math.random() * 20)
    return {
        id: i + 1,
        adminCode: `430381110210${String(i + 1).padStart(2, '0')}`,
        adminName: `白龙村${['一', '二', '三', '四', '十六', '十五', '十八', '十七', '八', '七', '六', '九', '十一', '十', '十四'][i]}组`,
        realArea: 0.00,
        contractorCount: contractor,
        memberCount: member,
        landCount: Math.floor(Math.random() * 300) + 100,
        nonContractedCount: Math.floor(Math.random() * 50),
        shareLandCount: Math.floor(Math.random() * 10),
        shareShares: Math.floor(Math.random() * 50),
        contractArea: (Math.random() * 50).toFixed(2),
        personAvgArea: (Math.random() * 2).toFixed(2),
        personAvgLand: (Math.random() * 1).toFixed(2),
        contractQty: contractor,
        regBookQty: contractor,
        certQty: contractor,
        selfArea: 0.00,
        machineArea: 0.00,
        devArea: 0.00,
        otherArea: 0.00
    }
}))
const currentPage2 = ref(1)
const pageSize2 = ref(20)

// --- Tab 3: 承包地块统计 ---
const subTab3 = ref('details')
const landTypeStat = ref('按土地类型统计')
const tableData3 = ref([
    { type: '水田', count: 5694, area: 5906.68, countRatio: '96.94%', areaRatio: '95.27%' },
    { type: '旱地', count: 165, area: 219.69, countRatio: '2.81%', areaRatio: '3.54%' },
    { type: '其它园地', count: 15, area: 74.23, countRatio: '0.26%', areaRatio: '1.20%' }
])

// --- Tab 4: 承包方统计 ---
const subTab4 = ref('details')
const contractorStatType = ref('按性别统计')
const tableData4 = ref([
    { type: '男', count: 2662, ratio: '52.26%' },
    { type: '女', count: 2432, ratio: '47.74%' }
])

// --- Tab 5: 承包合同统计 ---
const subTab5 = ref('details')
const contractStatType = ref('按承包方式统计')
const tableData5 = ref([
    { type: '家庭承包', count: 1218, landCount: 5644.0, area: 4547.49 }
])

// --- Charts ---
const chartRef2 = ref(null)
const chartRef3 = ref(null)
const chartRef4 = ref(null)
const chartRef5 = ref(null)
let chartInstance2 = null
let chartInstance3 = null
let chartInstance4 = null
let chartInstance5 = null

const initChart = (el, option) => {
    if (!el) return null
    const chart = echarts.init(el)
    chart.setOption(option)
    return chart
}

const updateCharts = () => {
    nextTick(() => {
        // Tab 2 Chart
        if (activeTab.value === 'comprehensive' && subTab2.value === 'chart' && chartRef2.value) {
            if (!chartInstance2) {
                chartInstance2 = initChart(chartRef2.value, {
                    title: { text: '综合统计分析', left: 'center' },
                    tooltip: { trigger: 'item' },
                    series: [{
                        type: 'pie',
                        radius: '50%',
                        data: [
                            { value: 5906.68, name: '水田' },
                            { value: 219.69, name: '旱地' },
                            { value: 74.23, name: '其它园地' }
                        ]
                    }]
                })
            }
            chartInstance2.resize()
        }
        // Tab 3 Chart
        if (activeTab.value === 'land' && subTab3.value === 'chart' && chartRef3.value) {
            if (!chartInstance3) {
                 chartInstance3 = initChart(chartRef3.value, {
                    title: { text: '地块类型分布', left: 'center' },
                    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
                    xAxis: { type: 'category', data: ['水田', '旱地', '其它园地'] },
                    yAxis: { type: 'value' },
                    series: [{
                        data: [5906.68, 219.69, 74.23],
                        type: 'bar',
                        showBackground: true,
                        backgroundStyle: { color: 'rgba(180, 180, 180, 0.2)' }
                    }]
                })
            }
            chartInstance3.resize()
        }
        // Tab 4 Chart
        if (activeTab.value === 'contractor' && subTab4.value === 'chart' && chartRef4.value) {
             if (!chartInstance4) {
                 chartInstance4 = initChart(chartRef4.value, {
                    title: { text: '性别比例', left: 'center' },
                    tooltip: { trigger: 'item' },
                    legend: { orient: 'vertical', left: 'left' },
                    series: [{
                        name: 'Access From',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
                        label: { show: false, position: 'center' },
                        emphasis: { label: { show: true, fontSize: 40, fontWeight: 'bold' } },
                        labelLine: { show: false },
                        data: [
                            { value: 2662, name: '男' },
                            { value: 2432, name: '女' }
                        ]
                    }]
                })
            }
            chartInstance4.resize()
        }
        // Tab 5 Chart
        if (activeTab.value === 'contract' && subTab5.value === 'chart' && chartRef5.value) {
             if (!chartInstance5) {
                 chartInstance5 = initChart(chartRef5.value, {
                    title: { text: '承包方式统计', left: 'center' },
                    tooltip: { trigger: 'item' },
                    series: [{
                        type: 'pie',
                        radius: '50%',
                        data: [
                            { value: 1218, name: '家庭承包' }
                        ]
                    }]
                })
            }
            chartInstance5.resize()
        }
    })
}

watch([activeTab, subTab2, subTab3, subTab4, subTab5], () => {
    updateCharts()
})

window.addEventListener('resize', () => {
    chartInstance2?.resize()
    chartInstance3?.resize()
    chartInstance4?.resize()
    chartInstance5?.resize()
})

onMounted(() => {
    // Select default tree node
    const defaultNode = treeData.value[0].children[0]
    // handleTreeNodeClick(defaultNode) // Optional: auto select
})
</script>

<template>
  <div class="h-full w-full flex overflow-hidden bg-white">
    <!-- Left Tree (Common) -->
    <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="搜索" :prefix-icon="Search"/>
      </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>

    <!-- Right Content -->
    <div class="flex-1 overflow-hidden flex flex-col bg-gray-50">
      <div class="bg-white border-b border-gray-200 px-4 pt-2">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="承包信息统计" name="contractInfo" />
          <el-tab-pane label="综合统计" name="comprehensive" />
          <el-tab-pane label="承包地块统计" name="land" />
          <el-tab-pane label="承包方统计" name="contractor" />
          <el-tab-pane label="承包合同统计" name="contract" />
        </el-tabs>
      </div>

      <div class="flex-1 overflow-hidden p-4">
        <!-- Tab 1: 承包信息统计 -->
        <div v-if="activeTab === 'contractInfo'" class="h-full flex flex-col bg-white rounded shadow-sm">
           <div class="p-3 border-b border-gray-100 flex items-center gap-3">
             <el-select v-model="statLevel" placeholder="统计级别" class="w-40">
                <el-option label="组级" value="group" />
                <el-option label="村级" value="village" />
             </el-select>
             <el-select v-model="sortRule" placeholder="排序规则" class="w-40">
                <el-option label="默认" value="default" />
             </el-select>
             <el-button type="primary" :icon="Search">查询</el-button>
             <el-button type="success">执行统计</el-button>
             <div class="flex-1"></div>
             <el-button-group>
               <el-button :icon="Grid" />
               <el-button :icon="Download" />
               <el-button :icon="Printer" />
             </el-button-group>
           </div>
           <el-table :data="tableData1" border stripe height="100%" class="flex-1">
             <el-table-column label="#" width="50" align="center">
                <template #default="scope">{{ scope.$index + 1 }}</template>
             </el-table-column>
             <el-table-column prop="adminCode" label="行政区代码" min-width="140" />
             <el-table-column prop="adminName" label="行政区名称" min-width="180" />
             <el-table-column prop="contractorCount" label="承包方数" sortable min-width="120" />
             <el-table-column prop="issuerCount" label="发包方数" sortable min-width="120" />
             <el-table-column prop="measuredArea" label="实测面积 (亩)" sortable min-width="150" />
             <el-table-column prop="contractedArea" label="承包地实测面积 (亩)" sortable min-width="180" />
             <el-table-column prop="nonContractedArea" label="非承包地实测面积 (亩)" sortable min-width="190" />
             <el-table-column prop="reservedArea" label="自留地实测面积 (亩)" sortable min-width="180" />
           </el-table>
           <div class="p-2 flex justify-end border-t border-gray-100">
             <el-pagination
               v-model:current-page="currentPage1"
               v-model:page-size="pageSize1"
               :total="19"
               :page-sizes="[20, 50, 100]"
               layout="prev, pager, next, jumper, sizes, total"
               background
             />
           </div>
        </div>

        <!-- Tab 2: 综合统计 -->
        <div v-if="activeTab === 'comprehensive'" class="h-full flex flex-col bg-white rounded shadow-sm overflow-hidden">
            <!-- Summary Grid -->
            <div class="p-4 grid grid-cols-4 gap-4 border-b border-gray-200 bg-gray-50">
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">行政区代码</span><el-input v-model="summaryData.adminCode" readonly size="small" /></div>
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">行政区名称</span><el-input v-model="summaryData.adminName" readonly size="small" /></div>
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">承包户数(户)</span><el-input v-model="summaryData.contractorCount" readonly size="small" /></div>
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">成员数(人)</span><el-input v-model="summaryData.memberCount" readonly size="small" /></div>
               
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">地块总数(块)</span><el-input v-model="summaryData.landCount" readonly size="small" /></div>
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">非承包地块(块)</span><el-input v-model="summaryData.nonContractedLandCount" readonly size="small" /></div>
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">确权地块数(块)</span><el-input v-model="summaryData.shareLandCount" readonly size="small" /></div>
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">确权份额(份)</span><el-input v-model="summaryData.shareShares" readonly size="small" /></div>

               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">实测面积(亩)</span><el-input v-model="summaryData.measuredArea" readonly size="small" /></div>
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">合同面积(亩)</span><el-input v-model="summaryData.contractArea" readonly size="small" /></div>
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">原合同面积(亩)</span><el-input v-model="summaryData.origContractArea" readonly size="small" /></div>
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">承包合同数量</span><el-input v-model="summaryData.contractQty" readonly size="small" /></div>

               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">登记簿数量</span><el-input v-model="summaryData.regBookQty" readonly size="small" /></div>
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">承包经营权证数</span><el-input v-model="summaryData.certQty" readonly size="small" /></div>
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">机动地实测面积(亩)</span><el-input v-model="summaryData.machineArea" readonly size="small" /></div>
               <div class="flex items-center gap-2"><span class="text-gray-600 w-24 text-right">机动地实测面积占比</span><el-input v-model="summaryData.machineAreaRatio" readonly size="small" /></div>
            </div>
            
            <!-- Sub Tabs -->
            <div class="border-b border-gray-200 px-4 pt-2">
                <span class="inline-block px-4 py-2 cursor-pointer border-b-2 transition-colors" :class="subTab2 === 'details' ? 'border-blue-500 text-blue-600 bg-blue-50 font-medium' : 'border-transparent text-gray-500 hover:text-blue-600'" @click="subTab2 = 'details'">详情</span>
                <span class="inline-block px-4 py-2 cursor-pointer border-b-2 transition-colors" :class="subTab2 === 'chart' ? 'border-blue-500 text-blue-600 bg-blue-50 font-medium' : 'border-transparent text-gray-500 hover:text-blue-600'" @click="subTab2 = 'chart'">图形展示</span>
            </div>

            <!-- Sub Content -->
            <div class="flex-1 overflow-hidden p-3 flex flex-col">
                <div v-if="subTab2 === 'details'" class="h-full flex flex-col">
                    <div class="mb-2">
                        <el-button type="success" size="small" :icon="Download">导出excel</el-button>
                    </div>
                    <el-table :data="tableData2" border stripe height="100%" size="small">
                        <el-table-column prop="id" label="序号" width="50" align="center" />
                        <el-table-column prop="adminCode" label="行政区代码" width="120" show-overflow-tooltip sortable />
                        <el-table-column prop="adminName" label="行政区名称" width="120" show-overflow-tooltip sortable />
                        <el-table-column prop="realArea" label="实测..." width="80" />
                        <el-table-column prop="contractorCount" label="承包..." width="80" />
                        <el-table-column prop="memberCount" label="成员..." width="80" />
                        <el-table-column prop="landCount" label="地块..." width="80" />
                        <el-table-column prop="nonContractedCount" label="非承..." width="80" />
                        <el-table-column prop="shareLandCount" label="确权..." width="80" />
                        <el-table-column prop="shareShares" label="确权..." width="80" />
                        <el-table-column prop="contractArea" label="合同..." width="80" />
                        <el-table-column prop="personAvgArea" label="人均..." width="80" />
                        <el-table-column prop="personAvgLand" label="人均..." width="80" />
                        <el-table-column prop="contractQty" label="承包..." width="80" />
                        <el-table-column prop="regBookQty" label="登记..." width="80" />
                        <el-table-column prop="certQty" label="权证..." width="80" />
                        <el-table-column prop="selfArea" label="自留..." width="80" />
                        <el-table-column prop="machineArea" label="机动..." width="80" />
                        <el-table-column prop="devArea" label="开发..." width="80" />
                        <el-table-column prop="otherArea" label="其他..." width="80" />
                    </el-table>
                    <div class="mt-2 flex justify-end">
                         <el-pagination
                            v-model:current-page="currentPage2"
                            v-model:page-size="pageSize2"
                            :total="19"
                            :page-sizes="[10, 20, 50]"
                            layout="prev, pager, next, jumper, sizes, total"
                            background
                            small
                        />
                    </div>
                </div>
                <div v-else class="h-full w-full" ref="chartRef2"></div>
            </div>
        </div>

        <!-- Tab 3: 承包地块统计 -->
        <div v-if="activeTab === 'land'" class="h-full flex flex-col bg-white rounded shadow-sm">
             <div class="p-3 border-b border-gray-100 flex items-center gap-3">
                 <el-select v-model="landTypeStat" class="w-48">
                     <el-option label="按土地类型统计" value="按土地类型统计" />
                 </el-select>
             </div>
             <div class="border-b border-gray-200 px-4 pt-2">
                <span class="inline-block px-4 py-2 cursor-pointer border-b-2 transition-colors" :class="subTab3 === 'details' ? 'border-blue-500 text-blue-600 bg-blue-50 font-medium' : 'border-transparent text-gray-500 hover:text-blue-600'" @click="subTab3 = 'details'">详情</span>
                <span class="inline-block px-4 py-2 cursor-pointer border-b-2 transition-colors" :class="subTab3 === 'chart' ? 'border-blue-500 text-blue-600 bg-blue-50 font-medium' : 'border-transparent text-gray-500 hover:text-blue-600'" @click="subTab3 = 'chart'">图形展示</span>
            </div>
            <div class="flex-1 overflow-hidden p-3">
                <el-table v-if="subTab3 === 'details'" :data="tableData3" border stripe height="100%">
                    <el-table-column prop="type" label="土地类型" />
                    <el-table-column prop="count" label="地块总数" />
                    <el-table-column prop="area" label="实测总面积(亩)" />
                    <el-table-column prop="countRatio" label="地块数占比" />
                    <el-table-column prop="areaRatio" label="实测面积占比" />
                </el-table>
                <div v-else class="h-full w-full" ref="chartRef3"></div>
            </div>
        </div>

        <!-- Tab 4: 承包方统计 -->
        <div v-if="activeTab === 'contractor'" class="h-full flex flex-col bg-white rounded shadow-sm">
             <div class="p-3 border-b border-gray-100 flex items-center gap-3">
                 <el-select v-model="contractorStatType" class="w-48">
                     <el-option label="按性别统计" value="按性别统计" />
                 </el-select>
             </div>
             <div class="border-b border-gray-200 px-4 pt-2">
                <span class="inline-block px-4 py-2 cursor-pointer border-b-2 transition-colors" :class="subTab4 === 'details' ? 'border-blue-500 text-blue-600 bg-blue-50 font-medium' : 'border-transparent text-gray-500 hover:text-blue-600'" @click="subTab4 = 'details'">详情</span>
                <span class="inline-block px-4 py-2 cursor-pointer border-b-2 transition-colors" :class="subTab4 === 'chart' ? 'border-blue-500 text-blue-600 bg-blue-50 font-medium' : 'border-transparent text-gray-500 hover:text-blue-600'" @click="subTab4 = 'chart'">图形展示</span>
            </div>
             <div class="flex-1 overflow-hidden p-3">
                <el-table v-if="subTab4 === 'details'" :data="tableData4" border stripe height="100%">
                    <el-table-column prop="type" label="性别" />
                    <el-table-column prop="count" label="人口数" />
                    <el-table-column prop="ratio" label="人口占比" />
                </el-table>
                <div v-else class="h-full w-full" ref="chartRef4"></div>
            </div>
        </div>

        <!-- Tab 5: 承包合同统计 -->
        <div v-if="activeTab === 'contract'" class="h-full flex flex-col bg-white rounded shadow-sm">
             <div class="p-3 border-b border-gray-100 flex items-center gap-3">
                 <el-select v-model="contractStatType" class="w-48">
                     <el-option label="按承包方式统计" value="按承包方式统计" />
                 </el-select>
             </div>
             <div class="border-b border-gray-200 px-4 pt-2">
                <span class="inline-block px-4 py-2 cursor-pointer border-b-2 transition-colors" :class="subTab5 === 'details' ? 'border-blue-500 text-blue-600 bg-blue-50 font-medium' : 'border-transparent text-gray-500 hover:text-blue-600'" @click="subTab5 = 'details'">详情</span>
                <span class="inline-block px-4 py-2 cursor-pointer border-b-2 transition-colors" :class="subTab5 === 'chart' ? 'border-blue-500 text-blue-600 bg-blue-50 font-medium' : 'border-transparent text-gray-500 hover:text-blue-600'" @click="subTab5 = 'chart'">图形展示</span>
            </div>
            <div class="flex-1 overflow-hidden p-3">
                <el-table v-if="subTab5 === 'details'" :data="tableData5" border stripe height="100%">
                    <el-table-column prop="type" label="承包方式" />
                    <el-table-column prop="count" label="合同总数(个)" />
                    <el-table-column prop="landCount" label="地块总数(块)" />
                    <el-table-column prop="area" label="合同总面积(亩)" />
                </el-table>
                 <div v-else class="h-full w-full" ref="chartRef5"></div>
            </div>
        </div>

      </div>
    </div>
  </div>
</template>

<style scoped>
:deep(.el-tree-node__content) {
  height: 26px;
}
:deep(.el-tabs__header) {
  margin-bottom: 0;
}
:deep(.el-tabs__nav-wrap::after) {
  height: 2px;
  background-color: transparent;
}
</style>
