<template>
  <div class="bankline-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>
        <el-button type="primary" size="small" style="float:right" @click="handleAdd" v-if="!isNational">
          <el-icon><Plus /></el-icon> 新增工作方案
        </el-button>
      </div>

      <el-tabs v-model="activeTab" type="border-card">
        <!-- 工作方案 Tab -->
        <el-tab-pane label="工作方案" name="workplan">
          <el-table :data="workPlans" border @row-dblclick="handleEdit">
            <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-column label="操作" width="150" fixed="right" v-if="!isNational">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="!workPlans.length" description="暂无工作方案"/>
        </el-tab-pane>

        <!-- 制度文件 Tab -->
        <el-tab-pane label="制度文件" name="files">
          <el-form :model="fileQuery" :inline="true" style="margin-bottom:10px">
            <el-form-item label="文件名称">
              <el-input v-model="fileQuery.fileName" placeholder="请输入文件名称" clearable style="width:200px" />
            </el-form-item>
            <el-form-item label="文件类型">
              <el-select v-model="fileQuery.fileType" placeholder="请选择" clearable style="width:150px">
                <el-option label="中央文件" value="0" />
                <el-option label="国务院文件" value="1" />
                <el-option label="水利部文件" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="getFileList">搜索</el-button>
              <el-button icon="Refresh" @click="resetFileQuery">重置</el-button>
              <el-button type="success" icon="Plus" @click="handleAddFile">新增</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="fileList" border>
            <el-table-column label="文件名称" prop="fileName" show-overflow-tooltip />
            <el-table-column label="文件类型" prop="fileType" width="120">
              <template #default="scope">
                {{ fileTypeLabel(scope.row.fileType) }}
              </template>
            </el-table-column>
            <el-table-column label="文号" prop="wh" width="150" />
            <el-table-column label="日期" prop="startDate" width="120" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-link v-if="scope.row.url" :href="scope.row.url" target="_blank" type="primary">下载</el-link>
                <el-button link type="primary" size="small" @click="handleEditFile(scope.row)">编辑</el-button>
                <el-button link type="danger" size="small" @click="handleDeleteFile(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="fileTotal > 0" :total="fileTotal" v-model:page="filePageNum" v-model:limit="filePageSize" @pagination="getFileList" />
        </el-tab-pane>

        <!-- 工作动态 Tab -->
        <el-tab-pane label="工作动态" name="articles">
          <el-form :model="articleQuery" :inline="true" style="margin-bottom:10px">
            <el-form-item label="标题">
              <el-input v-model="articleQuery.title" placeholder="请输入标题" clearable style="width:200px" />
            </el-form-item>
            <el-form-item label="类型">
              <el-select v-model="articleQuery.type" placeholder="动态类型" clearable style="width:150px">
                <el-option label="水利动态" value="0" />
                <el-option label="水利要闻" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="getArticleList">搜索</el-button>
              <el-button icon="Refresh" @click="resetArticleQuery">重置</el-button>
              <el-button type="success" icon="Plus" @click="handleAddArticle">新增</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="articleList" border>
            <el-table-column label="标题" prop="title" show-overflow-tooltip />
            <el-table-column label="类型" prop="type" width="100">
              <template #default="scope">{{ scope.row.type === '0' ? '水利动态' : '水利要闻' }}</template>
            </el-table-column>
            <el-table-column label="发布人" prop="pubman" width="120" />
            <el-table-column label="发布时间" prop="pubtime" width="160" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="handleEditArticle(scope.row)">编辑</el-button>
                <el-button link type="danger" size="small" @click="handleDeleteArticle(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="articleTotal > 0" :total="articleTotal" v-model:page="articlePageNum" v-model:limit="articlePageSize" @pagination="getArticleList" />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 工作方案编辑弹窗 -->
    <el-dialog v-model="wpDialogVisible" :title="wpDialogTitle" width="700px">
      <el-form :model="wpForm" :rules="wpRules" ref="wpFormRef" label-width="100px">
        <el-form-item label="方案名称" prop="wpName">
          <el-input v-model="wpForm.wpName" placeholder="请输入方案名称" />
        </el-form-item>
        <el-form-item label="文号" prop="fileNum">
          <el-input v-model="wpForm.fileNum" placeholder="请输入文号" />
        </el-form-item>
        <el-form-item label="发布日期" prop="rlsTm">
          <el-date-picker v-model="wpForm.rlsTm" type="date" placeholder="选择日期" style="width:100%" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="发布单位" prop="releWiunName">
          <el-input v-model="wpForm.releWiunName" placeholder="请输入发布单位" />
        </el-form-item>
        <el-form-item label="附件">
          <file-upload v-model="wpForm.attc" :limit="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="wpDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitWpForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 制度文件编辑弹窗 -->
    <el-dialog v-model="fileDialogVisible" :title="fileDialogTitle" width="700px">
      <el-form :model="fileForm" :rules="fileRules" ref="fileFormRef" label-width="100px">
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="fileForm.fileName" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="文件类型" prop="fileType">
          <el-select v-model="fileForm.fileType" placeholder="请选择" style="width:100%">
            <el-option label="中央文件" value="0" />
            <el-option label="国务院文件" value="1" />
            <el-option label="水利部文件" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="文号" prop="wh">
          <el-input v-model="fileForm.wh" placeholder="请输入文号" />
        </el-form-item>
        <el-form-item label="日期" prop="startDate">
          <el-date-picker v-model="fileForm.startDate" type="date" placeholder="选择日期" style="width:100%" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="附件">
          <file-upload v-model="fileForm.url" :limit="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="fileDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFileForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 工作动态编辑弹窗 -->
    <el-dialog v-model="articleDialogVisible" :title="articleDialogTitle" width="700px">
      <el-form :model="articleForm" :rules="articleRules" ref="articleFormRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="articleForm.type" placeholder="请选择" style="width:100%">
            <el-option label="水利动态" value="0" />
            <el-option label="水利要闻" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布人" prop="pubman">
          <el-input v-model="articleForm.pubman" placeholder="请输入发布人" />
        </el-form-item>
        <el-form-item label="发布时间" prop="pubtime">
          <el-date-picker v-model="articleForm.pubtime" type="datetime" placeholder="选择时间" style="width:100%" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="articleForm.content" type="textarea" :rows="5" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="articleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitArticleForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { listWorkPlan } from '@/api/hzz/workplan'
import { listFile, addFile, updateFile, delFile, listArticle, addArticle, updateArticle, delArticle } from '@/api/hzz/rule'
import { getChildren } from '@/api/hzz/adtree'
import FileUpload from '@/components/FileUpload'

const loading = ref(false)
const activeTab = ref('workplan')

// ========== 左侧树 ========== 
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 workPlans = ref([])
const wpDialogVisible = ref(false)
const wpDialogTitle = ref('')
const wpFormRef = ref(null)
const wpForm = reactive({
  guid: '',
  wpName: '',
  fileNum: '',
  rlsTm: '',
  releWiunName: '',
  attc: '',
  adCode: ''
})
const wpRules = {
  wpName: [{ required: true, message: '方案名称不能为空', trigger: 'blur' }]
}

const loadWorkPlans = async () => {
  if (isNational.value) {
    workPlans.value = []
    return
  }
  try {
    const res = await listWorkPlan(currentAdCode.value)
    workPlans.value = res.data || []
  } catch (e) {
    console.error(e)
  }
}

const handleAdd = () => {
  wpDialogTitle.value = '新增工作方案'
  Object.assign(wpForm, { guid: '', wpName: '', fileNum: '', rlsTm: '', releWiunName: '', attc: '', adCode: currentAdCode.value })
  wpDialogVisible.value = true
}

const handleEdit = (row) => {
  wpDialogTitle.value = '编辑工作方案'
  Object.assign(wpForm, { ...row })
  wpDialogVisible.value = true
}

const submitWpForm = async () => {
  await wpFormRef.value.validate()
  // TODO: 调用后端API保存
  ElMessage.success('保存成功（待实现后端接口）')
  wpDialogVisible.value = false
  loadWorkPlans()
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该工作方案吗？', '警告', { type: 'warning' }).then(async () => {
    // TODO: 调用后端API删除
    ElMessage.success('删除成功（待实现后端接口）')
    loadWorkPlans()
  })
}

// ========== 制度文件 ==========
const fileLoading = ref(false)
const fileList = ref([])
const fileTotal = ref(0)
const filePageNum = ref(1)
const filePageSize = ref(10)
const fileQuery = reactive({ fileName: '', fileType: '' })
const fileDialogVisible = ref(false)
const fileDialogTitle = ref('')
const fileFormRef = ref(null)
const fileForm = reactive({
  guid: '',
  fileName: '',
  fileType: '',
  wh: '',
  startDate: '',
  url: ''
})
const fileRules = {
  fileName: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }],
  fileType: [{ required: true, message: '文件类型不能为空', trigger: 'change' }]
}

const getFileList = async () => {
  fileLoading.value = true
  try {
    const res = await listFile({ ...fileQuery, types: 'gzzd', pageNum: filePageNum.value, pageSize: filePageSize.value })
    fileList.value = res.rows || []
    fileTotal.value = res.total || 0
  } finally { fileLoading.value = false }
}

const resetFileQuery = () => {
  Object.assign(fileQuery, { fileName: '', fileType: '' })
  getFileList()
}

const handleAddFile = () => {
  fileDialogTitle.value = '新增制度文件'
  Object.assign(fileForm, { guid: '', fileName: '', fileType: '', wh: '', startDate: '', url: '' })
  fileDialogVisible.value = true
}

const handleEditFile = (row) => {
  fileDialogTitle.value = '编辑制度文件'
  Object.assign(fileForm, { ...row })
  fileDialogVisible.value = true
}

const submitFileForm = async () => {
  await fileFormRef.value.validate()
  try {
    if (fileForm.guid) {
      await updateFile(fileForm)
      ElMessage.success('修改成功')
    } else {
      await addFile(fileForm)
      ElMessage.success('新增成功')
    }
    fileDialogVisible.value = false
    getFileList()
  } catch (e) {
    ElMessage.error('操作失败')
  }
}

const handleDeleteFile = (row) => {
  ElMessageBox.confirm('确认删除该文件吗？', '警告', { type: 'warning' }).then(async () => {
    try {
      await delFile(row.guid)
      ElMessage.success('删除成功')
      getFileList()
    } catch (e) {
      ElMessage.error('删除失败')
    }
  })
}

const fileTypeLabel = (type) => {
  const map = { '0': '中央文件', '1': '国务院文件', '2': '水利部文件' }
  return map[type] || '其他'
}

// ========== 工作动态 ==========
const articleLoading = ref(false)
const articleList = ref([])
const articleTotal = ref(0)
const articlePageNum = ref(1)
const articlePageSize = ref(10)
const articleQuery = reactive({ title: '', type: '' })
const articleDialogVisible = ref(false)
const articleDialogTitle = ref('')
const articleFormRef = ref(null)
const articleForm = reactive({
  guid: '',
  title: '',
  type: '',
  pubman: '',
  pubtime: '',
  content: ''
})
const articleRules = {
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '类型不能为空', trigger: 'change' }]
}

const getArticleList = async () => {
  articleLoading.value = true
  try {
    const res = await listArticle({ ...articleQuery, pageNum: articlePageNum.value, pageSize: articlePageSize.value })
    articleList.value = res.rows || []
    articleTotal.value = res.total || 0
  } finally { articleLoading.value = false }
}

const resetArticleQuery = () => {
  Object.assign(articleQuery, { title: '', type: '' })
  getArticleList()
}

const handleAddArticle = () => {
  articleDialogTitle.value = '新增工作动态'
  Object.assign(articleForm, { guid: '', title: '', type: '', pubman: '', pubtime: '', content: '' })
  articleDialogVisible.value = true
}

const handleEditArticle = (row) => {
  articleDialogTitle.value = '编辑工作动态'
  Object.assign(articleForm, { ...row })
  articleDialogVisible.value = true
}

const submitArticleForm = async () => {
  await articleFormRef.value.validate()
  try {
    if (articleForm.guid) {
      await updateArticle(articleForm)
      ElMessage.success('修改成功')
    } else {
      await addArticle(articleForm)
      ElMessage.success('新增成功')
    }
    articleDialogVisible.value = false
    getArticleList()
  } catch (e) {
    ElMessage.error('操作失败')
  }
}

const handleDeleteArticle = (row) => {
  ElMessageBox.confirm('确认删除该动态吗？', '警告', { type: 'warning' }).then(async () => {
    try {
      await delArticle(row.guid)
      ElMessage.success('删除成功')
      getArticleList()
    } catch (e) {
      ElMessage.error('删除失败')
    }
  })
}

// ========== 树相关 ==========
const loadTree = async () => {
  const res = await getChildren('000000000000')
  treeData.value = (res.data || []).map(item => ({ ...item }))
}

const loadTreeNode = async (node, resolve) => {
  if (node.level === 0) {
    return resolve(treeData.value)
  }
  try {
    const res = await getChildren(node.data.adCode)
    const children = (res.data || []).map(item => ({
      ...item,
      leaf: item.adGrad >= '5'
    }))
    resolve(children)
  } catch {
    resolve([])
  }
}

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

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([loadTree(), getFileList(), getArticleList()])
  loading.value = false
})
</script>

<style scoped>
.bankline-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;
}

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