<template>
  <div class="app-container">
    <el-row :gutter="16">
      <el-col :span="6">
        <el-card shadow="never" class="cate-card">
          <template #header><div class="card-header"><span>法规分类</span><el-button size="small" circle @click="handleAddCate" v-hasRole="['admin']">+</el-button></div></template>
          <el-tree :data="cateTree" :props="{label:'cateName'}" default-expand-all highlight-current
            @node-click="handleCateClick" :expand-on-click-node="false">
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span class="tree-actions">
                  <el-button type="primary" link size="small" @click.stop="handleEditCate(data)" v-hasRole="['admin']">编辑</el-button>
                  <el-button type="danger" link size="small" @click.stop="handleDeleteCate(data)" v-hasRole="['admin']">删除</el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card shadow="never" class="content-card">
          <template #header>
            <div class="card-header">
              <span>法规列表</span>
              <div class="header-actions">
                <el-button size="small" icon="Download" @click="handleExport">导出</el-button>
                <el-button size="small" icon="Upload" @click="openImportDialog">导入</el-button>
                <el-button type="primary" size="small" @click="handleAdd" v-hasRole="['admin']">新增法规</el-button>
              </div>
            </div>
          </template>
          <el-form :inline="true" size="small" style="margin-bottom:10px;">
            <el-form-item label="标题">
              <el-input v-model="searchTitle" placeholder="请输入标题" clearable @keyup.enter="handleSearch" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
              <el-button icon="Refresh" @click="searchTitle = ''; handleSearch()">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="lawList" stripe v-loading="loading">
            <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
            <el-table-column prop="subtitle" label="副标题" min-width="150" show-overflow-tooltip />
            <el-table-column prop="cateId" label="分类" width="110">
              <template #default="s">{{ getCateName(s.row.cateId) }}</template>
            </el-table-column>
            <el-table-column prop="pubDate" label="发布日期" width="110">
              <template #default="s">{{ formatDate(s.row.pubDate) }}</template>
            </el-table-column>
            <el-table-column prop="pubUser" label="发布人" width="100" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="s"><el-tag size="small">{{ s.row.status === '1' ? '已发布' : '草稿' }}</el-tag></template>
            </el-table-column>
            <el-table-column prop="viewCount" label="点击量" width="70" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="s">
                <div class="op-group">
                  <el-button type="primary" link @click="handleView(s.row)">查看</el-button>
                  <el-button type="primary" link @click="handleEdit(s.row)" v-hasRole="['admin']">编辑</el-button>
                  <el-button type="danger" link @click="handleDelete(s.row)" v-hasRole="['admin']">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="pagination-wrap"
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="loadLawList"
            @current-change="loadLawList"
          />
        </el-card>
      </el-col>
    </el-row>
    <!-- 法规新增/编辑对话框 -->
    <el-dialog v-model="open" :title="title" width="800px" top="5vh">
      <el-form :model="form" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12"><el-form-item label="法规标题"><el-input v-model="form.title" placeholder="请输入标题" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="副标题"><el-input v-model="form.subtitle" placeholder="请输入副标题" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12"><el-form-item label="分类">
            <el-tree-select v-model="form.cateId" :data="cateTree" :props="{ label:'cateName', value:'cateId' }" check-strictly placeholder="请选择分类" style="width:100%" />
          </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="发布人"><el-input v-model="form.pubUser" placeholder="请输入发布人" /></el-form-item></el-col>
        </el-row>
        <el-form-item label="法规内容">
          <Editor v-model="form.content" :height="300" />
        </el-form-item>
      </el-form>
      <template #footer><el-button type="primary" @click="submitForm">确 定</el-button><el-button @click="open=false">取 消</el-button></template>
    </el-dialog>
    <!-- 法规详情对话框 -->
    <el-dialog v-model="viewOpen" title="法规详情" width="800px" top="5vh">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="标题" :span="2">{{ viewData.title }}</el-descriptions-item>
        <el-descriptions-item label="副标题" :span="2">{{ viewData.subtitle }}</el-descriptions-item>
        <el-descriptions-item label="分类ID">{{ viewData.cateId }}</el-descriptions-item>
        <el-descriptions-item label="发布人">{{ viewData.pubUser }}</el-descriptions-item>
        <el-descriptions-item label="发布日期">{{ viewData.pubDate }}</el-descriptions-item>
        <el-descriptions-item label="状态"><el-tag size="small">{{ viewData.status === '1' ? '已发布' : '草稿' }}</el-tag></el-descriptions-item>
      </el-descriptions>
      <div class="law-content" v-html="viewData.content"></div>
    </el-dialog>
    <!-- 分类编辑对话框 -->
    <el-dialog v-model="cateOpen" :title="cateTitle" width="400px">
      <el-form :model="cateForm" label-width="80px">
        <el-form-item label="分类名称"><el-input v-model="cateForm.cateName" placeholder="请输入分类名称" /></el-form-item>
        <el-form-item label="分类说明"><el-input v-model="cateForm.cateMemo" type="textarea" :rows="3" placeholder="请输入分类说明" /></el-form-item>
        <el-form-item label="排序"><el-input-number v-model="cateForm.cateSeq" :min="0" :max="9999" style="width:100%" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitCateForm">确 定</el-button>
        <el-button @click="cateOpen=false">取 消</el-button>
      </template>
    </el-dialog>
    <!-- 导入法规弹窗 -->
    <el-dialog title="导入法规" v-model="importVisible" width="420px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="目标分类">
          <el-select v-model="importCateId" placeholder="请选择分类" style="width:100%">
            <el-option v-for="c in cateTree" :key="c.cateId" :label="c.cateName" :value="c.cateId" />
          </el-select>
        </el-form-item>
        <el-form-item label="文件">
          <el-upload
            ref="importUploadRef"
            :action="importUrl"
            :headers="uploadHeaders"
            :data="{ cateId: importCateId }"
            accept=".xlsx,.xls"
            :limit="1"
            :on-success="handleImportSuccess"
            :on-error="handleImportError"
            :show-file-list="true"
          >
            <el-button type="primary" size="small" icon="Upload">选择Excel文件</el-button>
            <template #tip>
              <div class="el-upload__tip">仅支持 .xlsx/.xls 格式</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" type="primary" icon="Download" @click="handleDownloadTemplate">下载模板</el-button>
        <el-button @click="importVisible = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Law">
import { getLawCateList, getLawCateTree, getLawCate, addLawCate, updateLawCate, delLawCate, getLawList, getLawDetail, saveLaw, delLaw, exportLaw, importTemplateUrl } from '@/api/slgc/law/index'
import { getToken } from '@/utils/auth'
import Editor from '@/components/Editor/index'
const { proxy } = getCurrentInstance()
// 导入导出
const importVisible = ref(false)
const importUploadRef = ref(null)
const importUrl = ref('/slgc/cms-article/importData')
const importCateId = ref('')
const uploadHeaders = ref({ Authorization: 'Bearer ' + getToken() })
const loading = ref(true); const open = ref(false); const title = ref('')
const viewOpen = ref(false); const viewData = ref({})
const cateTree = ref([]); const lawList = ref([]); const form = ref({})
const currentCateId = ref('')
const cateOpen = ref(false); const cateTitle = ref(''); const cateForm = ref({ cateId: '', cateName: '', cateMemo: '', cateSeq: 0 })
const pageNum = ref(1); const pageSize = ref(20); const total = ref(0)
const searchTitle = ref('')

function handleSearch() { pageNum.value = 1; loadLawList() }

// 打开导入弹窗：默认选中当前分类（或第一个分类）
function openImportDialog() {
  importCateId.value = currentCateId.value || (cateTree.value && cateTree.value[0] ? cateTree.value[0].cateId : '')
  importVisible.value = true
}

// === 导入导出 ===
function handleExport() {
  proxy.$modal.confirm('确认导出当前筛选条件下的全部数据？').then(() => {
    exportLaw({ title: searchTitle.value }).then(res => {
      const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = '法规数据.xlsx'
      link.click()
      window.URL.revokeObjectURL(url)
    })
  })
}
function handleDownloadTemplate() {
  window.open(importTemplateUrl(), '_blank')
}
function handleImportSuccess(res) {
  if (res.code === 200) {
    proxy.$modal.msgSuccess(res.msg || '导入成功')
    importVisible.value = false
    loadLawList()
  } else {
    proxy.$modal.msgError(res.msg || '导入失败')
  }
  if (importUploadRef.value) importUploadRef.value.clearFiles()
}
function handleImportError() {
  proxy.$modal.msgError('导入失败，请检查文件格式')
  if (importUploadRef.value) importUploadRef.value.clearFiles()
}

// 分类ID → 分类名称（遍历左侧树）
function getCateName(cateId) {
  if (!cateId) return '-'
  const walk = (list) => {
    for (const item of list || []) {
      if (String(item.cateId) === String(cateId)) return item.cateName
      const sub = walk(item.children)
      if (sub) return sub
    }
    return ''
  }
  return walk(cateTree.value) || cateId
}

// 只显示年月日 YYYY-MM-DD
function formatDate(val) {
  if (!val) return '-'
  return String(val).slice(0, 10)
}

function handleCateClick(d) { currentCateId.value = d.cateId; searchTitle.value = ''; pageNum.value = 1; loadLawList() }
function loadLawList() {
  const params = { pageNum: pageNum.value, pageSize: pageSize.value }
  if (currentCateId.value) params.cateId = currentCateId.value
  if (searchTitle.value) params.title = searchTitle.value
  getLawList(params).then(r => { lawList.value = r.rows; total.value = r.total || 0; loading.value = false })
    .catch(() => { loading.value = false })
}
function handleAdd() { form.value = {}; title.value = '新增法规'; open.value = true }
function handleView(r) {
  getLawDetail(r.aid).then(res => { viewData.value = res.data; viewOpen.value = true })
}
function handleEdit(r) {
  getLawDetail(r.aid).then(res => { form.value = res.data; title.value = '编辑法规'; open.value = true })
}
function handleDelete(r) { proxy.$modal.confirm('确认删除?').then(() => { delLaw(r.aid).then(() => { ElMessage.success('删除成功'); loadLawList() }) }) }
function submitForm() { saveLaw(form.value).then(() => { proxy.$modal.msgSuccess('操作成功'); open.value = false; loadLawList() }) }

function handleAddCate() { cateForm.value = { cateId: '', cateName: '', cateMemo: '', cateSeq: 0 }; cateTitle.value = '新增分类'; cateOpen.value = true }
function handleEditCate(data) {
  getLawCate(data.cateId).then(res => {
    cateForm.value = { cateId: res.data.cateId, cateName: res.data.cateName, cateMemo: res.data.cateMemo || '', cateSeq: res.data.cateSeq || 0 }
    cateTitle.value = '编辑分类'; cateOpen.value = true
  })
}
function handleDeleteCate(data) {
  proxy.$modal.confirm('确认删除分类"' + data.cateName + '"？').then(() => {
    delLawCate(data.cateId).then(() => { ElMessage.success('删除成功'); loadCateTree() })
  })
}
function submitCateForm() {
  if (!cateForm.value.cateName) { ElMessage.warning('请输入分类名称'); return }
  const action = cateForm.value.cateId ? updateLawCate(cateForm.value) : addLawCate(cateForm.value)
  action.then(() => { ElMessage.success('操作成功'); cateOpen.value = false; loadCateTree() })
}
function loadCateTree() { getLawCateTree().then(r => { cateTree.value = r.data || r.rows || [] }) }
onMounted(() => {
  loadCateTree()
  loadLawList()
})
</script>
<style scoped>
/* 页面撑满高度 */
.app-container {
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  padding: 16px;
  box-sizing: border-box;
  overflow: hidden;
}
.app-container > .el-row {
  flex: 1;
  min-height: 0;
}
.app-container > .el-row > .el-col {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.app-container > .el-row > .el-col > .content-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}
.app-container > .el-row > .el-col > .content-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}
/* 表格撑开 */
.app-container > .el-row > .el-col > .content-card :deep(.el-table) {
  flex: 1;
  min-height: 0;
}
/* 左侧分类树卡片撑满 */
.cate-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}
.cate-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}
.cate-card :deep(.el-tree) {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
}
.card-header { font-weight:600;font-size:16px;display:flex;justify-content:space-between;align-items:center; }
.header-actions { display: flex; align-items: center; gap: 8px; }
.custom-tree-node { flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px; }
.tree-actions { display: none; }
.custom-tree-node:hover .tree-actions { display: inline; }
.law-content { margin-top: 16px; padding: 16px; border: 1px solid #e5e5e5; border-radius: 4px; line-height: 1.8; max-height: 400px; overflow-y: auto; }
.pagination-wrap { margin-top: 12px; display: flex; justify-content: flex-end; flex-shrink: 0; }
/* 操作栏不换行 */
.op-group {
  display: flex;
  align-items: center;
  white-space: nowrap;
}
.op-group .el-button {
  margin-left: 0;
  margin-right: 8px;
}
.op-group .el-button + .el-button {
  margin-left: 0;
}
</style>
