<template>
  <div class="gc-page">
    <el-card shadow="never" class="unit-card">
      <template #header>
        <div class="card-header"><span>用水单位管理</span><el-button type="primary" size="small" style="float:right" @click="handleAdd">新增单位</el-button></div>
      </template>
      <div class="unit-body">
        <el-form :model="queryParams" :inline="true" size="small">
          <el-form-item label="查询名称"><el-input v-model="queryParams.name" placeholder="请输入" clearable @keyup.enter="handleQuery" /></el-form-item>
          <el-form-item label="查询地址"><el-input v-model="queryParams.address" placeholder="请输入" clearable @keyup.enter="handleQuery" /></el-form-item>
          <el-form-item>
            <el-select v-model="queryParams.overdue" placeholder="全部数据" clearable @change="handleQuery">
              <el-option label="全部数据" value="" />
              <el-option label="已过期（超5年）" value="yes" />
              <el-option label="未过期" value="no" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 批量操作（表格上方左侧） -->
        <div class="table-toolbar">
          <el-button type="success" size="small" icon="Download" @click="handleExport">导出</el-button>
          <el-button type="success" size="small" icon="Upload" @click="importVisible = true">导入</el-button>
          <el-button type="danger" size="small" icon="Delete" :disabled="!ids.length" @click="handleBatchDelete">批量删除</el-button>
        </div>

        <el-table v-loading="loading" :data="list" stripe :row-class-name="rowClassName" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" />
          <el-table-column prop="name" label="单位名称" min-width="160" show-overflow-tooltip />
          <el-table-column prop="province" label="省" width="80" />
          <el-table-column prop="city" label="市" width="80" />
          <el-table-column prop="address" label="地址" min-width="150" show-overflow-tooltip />
          <el-table-column prop="contacts" label="联系人" width="100" />
          <el-table-column prop="telphone" label="联系电话" width="130" />
          <el-table-column prop="longitude" label="经度" width="100" />
          <el-table-column prop="latitude" label="纬度" width="100" />
          <el-table-column prop="approvalDate" label="批准日期" width="110">
            <template #default="s">{{ formatDate(s.row.approvalDate) }}</template>
          </el-table-column>
          <el-table-column label="操作" width="300" fixed="right">
            <template #default="s">
              <div class="op-group">
                <el-button type="warning" link @click="openFileDialog(s.row)">附件</el-button>
                <el-button type="primary" link @click="openRecordDialog(s.row)">复核记录</el-button>
                <el-button type="primary" link @click="handleEdit(s.row)">编辑</el-button>
                <el-button type="danger" link @click="handleDelete(s.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="gc-pagination">
          <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </div>
      </div>
    </el-card>

    <!-- ====== 编辑单位弹窗 ====== -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" label-width="100px">
        <el-row>
          <el-col :span="12"><el-form-item label="单位名称"><el-input v-model="form.name" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="联系人"><el-input v-model="form.contacts" /></el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"><el-form-item label="联系电话"><el-input v-model="form.telphone" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="传真"><el-input v-model="form.fax" /></el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"><el-form-item label="省"><el-input v-model="form.province" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="市"><el-input v-model="form.city" /></el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="24"><el-form-item label="地址"><el-input v-model="form.address" /></el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"><el-form-item label="经度"><el-input v-model="form.longitude" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="纬度"><el-input v-model="form.latitude" /></el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"><el-form-item label="批准日期"><el-date-picker v-model="form.approvalDate" type="date" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item></el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>

    <!-- ====== 复核记录弹窗 ====== -->
    <el-dialog title="复核记录" v-model="recordVisible" width="800px" append-to-body>
      <div style="margin-bottom:12px;">
        <el-button type="primary" size="small" icon="Plus" @click="handleAddRecord">添加</el-button>
        <el-button type="danger" size="small" icon="Delete" :disabled="!recordIds.length" @click="handleBatchDelRecord">批量删除</el-button>
      </div>
      <el-table :data="recordList" v-loading="recordLoading" stripe size="small" @selection-change="handleRecordSelectionChange">
        <el-table-column type="selection" width="40" />
        <el-table-column prop="id" label="ID" width="50" />
        <el-table-column prop="approvalNumber" label="复核编号" width="100" />
        <el-table-column prop="approvalDate" label="复核日期" width="120" />
        <el-table-column prop="approvalContent" label="复核内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="updateTime" label="更新时间" width="160" />
        <el-table-column label="操作" width="140" fixed="right">
          <template #default="r">
            <el-button type="primary" link icon="Edit" @click="handleEditRecord(r.row)">编辑</el-button>
            <el-button type="danger" link icon="Delete" @click="handleDeleteRecord(r.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 复核记录编辑弹窗 -->
      <el-dialog title="复核记录" v-model="recordFormVisible" width="500px" append-to-body>
        <el-form :model="recordForm" label-width="100px">
          <el-form-item label="复核编号"><el-input v-model="recordForm.approvalNumber" placeholder="请输入" /></el-form-item>
          <el-form-item label="复核日期"><el-date-picker v-model="recordForm.approvalDate" type="date" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item>
          <el-form-item label="复核内容"><el-input v-model="recordForm.approvalContent" type="textarea" :rows="4" placeholder="请输入" /></el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="submitRecordForm">确 定</el-button>
          <el-button @click="recordFormVisible = false">取 消</el-button>
        </template>
      </el-dialog>
    </el-dialog>

    <!-- ====== 附件管理弹窗 ====== -->
    <el-dialog :title="'附件管理 - ' + fileUnitName" v-model="fileVisible" width="800px" append-to-body>
      <div style="margin-bottom:12px;">
        <el-button type="primary" size="small" icon="Upload" @click="handleUploadFile">上传附件</el-button>
      </div>
      <el-table :data="fileList" v-loading="fileLoading" stripe size="small">
        <el-table-column prop="id" label="ID" width="50" />
        <el-table-column prop="fileName" label="文件名" min-width="200" show-overflow-tooltip />
        <el-table-column prop="fileSize" label="大小" width="100">
          <template #default="f">
            {{ formatFileSize(f.row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column prop="uploadTime" label="上传时间" width="160" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="f">
            <el-button type="primary" link icon="Download" @click="handleDownloadFile(f.row)">下载</el-button>
            <el-button type="danger" link icon="Delete" @click="handleDeleteFile(f.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 上传附件对话框 -->
      <el-dialog title="上传附件" v-model="uploadVisible" width="400px" append-to-body>
        <el-form label-width="80px">
          <el-form-item label="文件标题"><el-input v-model="uploadTitle" placeholder="请输入" /></el-form-item>
          <el-form-item label="选择文件">
            <el-upload ref="uploadRef" :action="uploadAction" :data="uploadData" :headers="uploadHeaders"
              :limit="1" :on-success="handleUploadSuccess" :before-upload="beforeUpload" :auto-upload="false">
              <el-button type="primary" size="small" icon="Upload">选择文件</el-button>
              <template #tip><div class="el-upload__tip">支持PDF、Word等常见文件</div></template>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="$refs.uploadRef.submit()">上 传</el-button>
          <el-button @click="uploadVisible = false">取 消</el-button>
        </template>
      </el-dialog>
    </el-dialog>
    <!-- ====== 导入单位弹窗 ====== -->
    <el-dialog title="导入单位" v-model="importVisible" width="420px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="文件">
          <el-upload
            ref="importUploadRef"
            :action="importUrl"
            :headers="uploadHeaders"
            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="Unit">
import { getToken } from '@/utils/auth'
import { getUnitList, getUnit, saveUnit, delUnit, getRecordList, saveRecord, delRecord, exportUnit, importTemplateUrl } from '@/api/slgc/unit/index'
import { getDocFileList, delDocFile } from '@/api/slgc/doc/index'

const { proxy } = getCurrentInstance()
const loading = ref(true); const total = ref(0); const open = ref(false); const title = ref('')
const list = ref([]); const ids = ref([])
const queryParams = reactive({ pageNum: 1, pageSize: 10, name: undefined, address: undefined, overdue: undefined })
const form = ref({})

// === 复核记录 ===
const recordVisible = ref(false)
const recordFormVisible = ref(false)
const recordLoading = ref(false)
const recordList = ref([])
const recordIds = ref([])
const recordUnitId = ref(null)
const recordForm = ref({})

// === 附件管理 ===
const fileVisible = ref(false)
const fileLoading = ref(false)
const fileList = ref([])
const fileUnitId = ref(null)
const fileUnitName = ref('')
const uploadVisible = ref(false)
const uploadTitle = ref('')
const uploadAction = ref('')
const uploadData = ref({})
const uploadHeaders = ref({ Authorization: 'Bearer ' + getToken() })

// === 导入导出 ===
const importVisible = ref(false)
const importUploadRef = ref(null)
const importUrl = ref('/slgc/water-unit/importData')

function formatFileSize(bytes) {
  if (!bytes) return '-'
  if (bytes < 1024) return bytes + 'B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB'
  return (bytes / 1024 / 1024).toFixed(1) + 'MB'
}

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

// === 过期判定 ===
function isOverdue(row) {
  if (!row.approvalDate) return false
  const fiveYearsAgo = new Date()
  fiveYearsAgo.setFullYear(fiveYearsAgo.getFullYear() - 5)
  return new Date(row.approvalDate) <= fiveYearsAgo
}
function rowClassName({ row }) { return isOverdue(row) ? 'overdue-row' : '' }

// === 单位列表 ===
function getList() {
  loading.value = true
  getUnitList(queryParams).then(res => {
    list.value = res.rows || []
    total.value = res.total
    loading.value = false
  }).catch(() => { loading.value = false })
}
function handleQuery() { queryParams.pageNum = 1; getList() }
function resetQuery() { queryParams.name = undefined; queryParams.address = undefined; queryParams.overdue = undefined; handleQuery() }
function handleSelectionChange(selection) { ids.value = selection.map(s => s.id) }
function handleEdit(row) { getUnit(row.id).then(res => { form.value = res.data; title.value = '编辑单位'; open.value = true }) }
function handleAdd() { form.value = {}; title.value = '新增单位'; open.value = true }
function submitForm() { saveUnit(form.value).then(() => { proxy.$modal.msgSuccess('操作成功'); open.value = false; getList() }) }
function cancel() { open.value = false }
function handleDelete(row) {
  proxy.$modal.confirm('确认删除"' + row.name + '"？').then(() => {
    delUnit(row.id).then(() => { proxy.$modal.msgSuccess('删除成功'); getList() })
  })
}
function handleBatchDelete() {
  if (!ids.value.length) return
  proxy.$modal.confirm('确认删除选中的 ' + ids.value.length + ' 条记录？').then(() => {
    delUnit(ids.value.join(',')).then(() => { proxy.$modal.msgSuccess('删除成功'); getList() })
  })
}

// === 导入导出 ===
function handleExport() {
  proxy.$modal.confirm('确认导出当前筛选条件下的全部数据？').then(() => {
    exportUnit(queryParams).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
    getList()
  } else {
    proxy.$modal.msgError(res.msg || '导入失败')
  }
  if (importUploadRef.value) importUploadRef.value.clearFiles()
}

function handleImportError() {
  proxy.$modal.msgError('导入失败，请检查文件格式')
  if (importUploadRef.value) importUploadRef.value.clearFiles()
}

// === 复核记录管理（弹窗） ===
function openRecordDialog(row) {
  recordUnitId.value = row.id
  recordVisible.value = true
  loadRecords(row.id)
}

function loadRecords(unitId) {
  recordLoading.value = true
  getRecordList({ unitId: unitId || recordUnitId.value }).then(res => {
    recordList.value = res.rows || res.data || []
    recordLoading.value = false
  }).catch(() => { recordList.value = []; recordLoading.value = false })
}

function handleAddRecord() {
  recordForm.value = {}
  recordFormVisible.value = true
}
function handleEditRecord(row) {
  recordForm.value = { ...row }
  recordFormVisible.value = true
}
function submitRecordForm() {
  const data = { ...recordForm.value, unitId: recordUnitId.value }
  saveRecord(data).then(() => {
    proxy.$modal.msgSuccess('操作成功')
    recordFormVisible.value = false
    loadRecords()
  })
}
function handleDeleteRecord(row) {
  proxy.$modal.confirm('确认删除该复核记录？').then(() => {
    delRecord(row.id).then(() => { proxy.$modal.msgSuccess('删除成功'); loadRecords() })
  })
}
function handleRecordSelectionChange(selection) { recordIds.value = selection.map(s => s.id) }
function handleBatchDelRecord() {
  if (!recordIds.value.length) return
  proxy.$modal.confirm('确认删除选中的 ' + recordIds.value.length + ' 条记录？').then(() => {
    delRecord(recordIds.value.join(',')).then(() => { proxy.$modal.msgSuccess('删除成功'); loadRecords() })
  })
}

// === 附件管理（弹窗） ===
function openFileDialog(row) {
  fileUnitId.value = row.id
  fileUnitName.value = row.name || ''
  fileVisible.value = true
  loadFiles(row.id)
}

function loadFiles(unitId) {
  fileLoading.value = true
  // 与后端约定：附件通过 fileCate 前缀 'UNIT-' + 单位ID 关联
  getDocFileList({ fileCate: 'UNIT-' + (unitId || fileUnitId.value) }).then(res => {
    fileList.value = res.rows || res.data || []
    fileLoading.value = false
  }).catch(() => { fileList.value = []; fileLoading.value = false })
}

function handleUploadFile() {
  uploadTitle.value = ''
  // 相对路径，走 vite 代理；fileCate 前缀 UNIT- 关联单位
  uploadAction.value = '/slgc/doc-file/upload'
  uploadData.value = { fileCate: 'UNIT-' + fileUnitId.value, fileTitle: '' }
  uploadVisible.value = true
}

function beforeUpload(file) {
  uploadData.value.fileTitle = uploadTitle.value || file.name
  return true
}

function handleUploadSuccess(res) {
  if (res.code === 200) {
    proxy.$modal.msgSuccess('上传成功')
    uploadVisible.value = false
    loadFiles()
  } else {
    proxy.$modal.msgError(res.msg || '上传失败')
  }
}

function handleDownloadFile(row) {
  if (row.filePath) {
    // 与上传目录一致（profile/upload），走资源下载接口
    window.open(`/common/download/resource?resource=${encodeURIComponent(row.filePath)}`, '_blank')
  }
}

function handleDeleteFile(row) {
  proxy.$modal.confirm('确认删除该附件？').then(() => {
    delDocFile(row.id).then(() => { proxy.$modal.msgSuccess('删除成功'); loadFiles() })
  })
}

onMounted(() => { getList() })
</script>

<style scoped>
.gc-page { padding: 16px; height: calc(100vh - 60px); display: flex; flex-direction: column; box-sizing: border-box; }
.unit-card { flex: 1; display: flex; flex-direction: column; min-height: 0; }
.unit-card :deep(.el-card__body) { flex: 1; display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
.unit-body { flex: 1; display: flex; flex-direction: column; min-height: 0; }
.unit-body .el-table { flex: 1; min-height: 0; }
.card-header { font-weight: 600; font-size: 16px; }
/* 表格上方工具栏（批量操作） */
.table-toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  flex-shrink: 0;
}
.gc-pagination { display: flex; justify-content: flex-end; margin-top: 16px; 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;
}
:deep(.overdue-row) { background-color: #fdf6ec !important; }
:deep(.overdue-row td) { background-color: #fdf6ec !important; }
</style>
