<template>
  <div class="gzfa-page">
    <!-- 左侧行政区划树 -->
    <div class="left-tree">
      <div class="tree-title">行政区划</div>
      <el-input v-model="treeFilter" placeholder="搜索" size="small" clearable style="margin:8px"/>
      <el-tree
          :data="treeData" :props="treeProps" node-key="adCode"
          :filter-node-method="filterNode" ref="treeRef"
          highlight-current lazy :load="loadTreeNode"
          @node-click="onNodeClick"
      />
    </div>

    <!-- 右侧内容 -->
    <div class="right-content" v-loading="loading">
      <!-- 当前选中区域 -->
      <div class="current-area" v-if="currentAdName">
        当前区域：<strong>{{ currentAdName }}</strong>
      </div>

      <!-- 全国视图：中央/国务院/水利部文件 -->
      <template v-if="isNational">
        <div class="file-section" v-for="cat in fileCategories" :key="cat.title">
          <h3 class="section-title">{{ cat.title }}</h3>
          <el-table :data="cat.data" border size="small">
            <el-table-column label="文件名称" prop="fileName" show-overflow-tooltip>
              <template #default="{row}">
                <el-link type="primary" @click="showDetail(row)">{{ row.fileName || row.FILE_NAME }}</el-link>
              </template>
            </el-table-column>
            <el-table-column label="文号" prop="wh" width="200">
              <template #default="{row}">{{ row.wh || row.WH }}</template>
            </el-table-column>
            <el-table-column label="出台时间" width="140">
              <template #default="{row}">{{ fmtDate(row.startDate || row.START_DATE) }}</template>
            </el-table-column>
          </el-table>
        </div>
      </template>

      <!-- 地区视图：工作方案 + 工作制度 -->
      <template v-else>
        <div class="file-section">
          <h3 class="section-title">工作方案</h3>
          <el-table :data="workPlans" @row-click="showDetail">
            <el-table-column label="方案名称" prop="wpName" show-overflow-tooltip/>
            <el-table-column label="文号" prop="fileNum" width="200"/>
            <el-table-column label="发布日期" prop="rlsTm" width="140"/>
            <el-table-column label="发布单位" prop="releWiunName" width="180"/>
          </el-table>
          <el-empty v-if="!workPlans.length" description="暂无工作方案"/>
        </div>

        <div class="file-section" style="margin-top:20px">
          <h3 class="section-title">工作制度</h3>
          <el-table :data="ruleData">
            <el-table-column label="制度类别" prop="sysType" width="160">
              <template #default="scope">
                {{ sysTypeFilter(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column label="制度名称" prop="sysName" show-overflow-tooltip/>
            <el-table-column label="状态" prop="ruleProgress" width="100">
              <template #default="scope">
                {{ ruleProgressFilter(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column label="文号" prop="fileNum" width="200"/>
            <el-table-column label="出台时间" prop="rlsTm" width="140"/>
          </el-table>
          <el-empty v-if="!ruleData.length" description="暂无工作制度"/>
        </div>
      </template>
    </div>

    <!-- 文件详情弹窗 -->
    <el-dialog v-model="detailVisible" :title="detailItem?.fileName || detailItem?.wpName || detailItem?.sysName"
               width="700px">
      <i-frame :src="detailItem?.url" style="height: 79vh;"></i-frame>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref, watch} from 'vue'
import {listFile, listRule} from '@/api/hzz/rule'
import {getChildren} from '@/api/hzz/adtree'
import {listWorkPlan} from '@/api/hzz/workplan'
import iFrame from '@/components/iFrame'

const loading = ref(false)
const treeRef = ref(null)
const treeFilter = ref('')
const treeData = ref([])
const treeProps = {label: 'adName', children: 'children'}

const currentAdCode = ref('000000000000')
const currentAdName = ref('太湖流域')
const isNational = computed(() => currentAdCode.value === '000000000000')

const fileCategories = reactive([
  {title: '中央文件', key: '0', data: []},
  {title: '国务院文件', key: '1', data: []},
  {title: '水利部文件', key: '2', data: []},
])

const workPlans = ref([])
const ruleData = ref([])
const detailVisible = ref(false)
const detailItem = ref(null)

const fmtDate = (d) => d ? String(d).substring(0, 10) : '-'

// 加载文件列表
const loadFiles = async () => {
  try {
    const res = await listFile({types: 'gzzd', pageNum: 1, pageSize: 500})
    const rows = res.rows || []
    fileCategories[0].data = rows.filter(r => (r.FILE_TYPE || r.fileType) === '0')
    fileCategories[1].data = rows.filter(r => (r.FILE_TYPE || r.fileType) === '1')
    fileCategories[2].data = rows.filter(r => (r.FILE_TYPE || r.fileType) === '2')
  } catch { /* ok */
  }
}

// 加载工作方案 + 制度
const loadAreaData = async () => {
  workPlans.value = []
  ruleData.value = []
  if (isNational.value) return
  try {
    const [wpRes, ruleRes] = await Promise.all([
      listWorkPlan(currentAdCode.value),
      listRule(currentAdCode.value, '')
    ])
    workPlans.value = wpRes.data || []
    ruleData.value = ruleRes.data || []
  } catch { /* ok */
  }
}

// 加载行政区划树
const loadTree = async () => {
  // 根节点从数据库加载
  const res = await getChildren('000000000000')
  treeData.value = (res.data || []).map(item => ({
    ...item,
    adName: item.adName, adCode: item.adCode
  }))
}

// 懒加载子节点（逐级下钻）
const loadTreeNode = async (node, resolve) => {
  if (node.level === 0) {
    // 根节点已在 loadTree 中加载
    return resolve(treeData.value)
  }
  try {
    const res = await getChildren(node.data.adCode)
    const children = (res.data || []).map(item => ({
      ...item,
      adName: item.adName,
      adCode: item.adCode,
      leaf: item.adGrad >= '5' // 村级为叶子节点
    }))
    resolve(children)
  } catch {
    resolve([])
  }
}

const onNodeClick = (node) => {
  currentAdCode.value = node.adCode
  currentAdName.value = node.adName
  if (!isNational.value) loadAreaData()
}

const sysTypeFilter = (item) => {
  switch (item.sysType) {
    case '1':
      return '河长会议制度'
    case '2':
      return '信息报送制度'
    case '3':
      return '工作督察制度'
    case '4':
      return '考核问责与激励制度'
    case '5':
      return '验收制度'
    case '6':
      return '信息共享制度'
    default:
      return '其他'
  }
}

const ruleProgressFilter = (item) => {
  switch (item.ruleProgress) {
    case '1':
      return '研讨'
    case '2':
      return '起草'
    case '3':
      return '征求意见'
    case '4':
      return '报批'
    case '5':
      return '印发'
    default:
      return ''
  }
}

const showDetail = (item) => {
  detailVisible.value = true
  detailItem.value = item
  // if (item.url.substring(item.url.length - 3) === 'doc' || item.url.substring(item.url.length - 4) === 'docx') {
  //   detailVisible.value = false;
  //   window.open(item.url);
  // } else if (item.url.substring(item.url.length - 3) === 'pdf') {
  //   detailVisible.value = true
  //   detailItem.value = item
  // }
}

const filterNode = (value, data) => {
  if (!value) return true
  return data.adName?.includes(value)
}

watch(treeFilter, (val) => {
  treeRef.value?.filter(val)
})

onMounted(async () => {
  loading.value = true
  await Promise.all([loadFiles(), loadTree()])
  loading.value = false
})
</script>

<style scoped>
.gzfa-page {
  display: flex;
  height: calc(100vh - 60px);
}

.left-tree {
  width: 260px;
  flex-shrink: 0;
  border-right: 1px solid #e8e8e8;
  overflow-y: auto;
  background: #fafbfc;
}

.tree-title {
  padding: 12px 16px;
  font-weight: 600;
  font-size: 15px;
  color: #333;
  border-bottom: 1px solid #eee;
}

.right-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.file-section {
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  color: #0d4b80;
  padding: 8px 0;
  margin: 0 0 8px 0;
  border-bottom: 2px solid #6baed6;
}

.current-area {
  margin-bottom: 20px;
  padding: 10px;
  background: #f0f7ff;
  border-radius: 6px;
  font-size: 13px;
  color: #555;
}

.detail-info p {
  margin: 8px 0;
  font-size: 14px;
}
</style>
