<template>
  <div class="pipe-network-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="设施名称">
          <el-input v-model="searchForm.networkName" placeholder="请输入设施名称" clearable />
        </el-form-item>
        <el-form-item label="管养单位">
          <el-input v-model="searchForm.managementUnit" placeholder="请输入管养单位" clearable />
        </el-form-item>
        <el-form-item label="等级">
          <el-select v-model="searchForm.networkLevel" placeholder="请选择" clearable style="width:160px">
            <el-option v-for="d in pipeNetworkLevelDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="材质">
          <el-input v-model="searchForm.material" placeholder="请输入材质" clearable style="width:160px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width:160px">
            <el-option v-for="d in pipeNetworkStatusDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
          <el-button type="warning" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table :data="tableData" border stripe v-loading="loading" style="width: 100%">
        <el-table-column prop="networkCode" label="设施编码" min-width="120" />
        <el-table-column prop="networkName" label="设施名称" min-width="150" />
        <el-table-column prop="networkType" label="设施类型" width="100">
          <template #default="{ row }">{{ getDictLabel(pipeNetworkTypeDict, row.networkType) }}</template>
        </el-table-column>
        <el-table-column prop="networkLevel" label="等级" width="90">
          <template #default="{ row }">{{ getDictLabel(pipeNetworkLevelDict, row.networkLevel) }}</template>
        </el-table-column>
        <el-table-column prop="managementUnit" label="管养单位" min-width="150" />
        <el-table-column prop="material" label="材质" width="100" />
        <el-table-column prop="length" label="长度(米)" width="100" />
        <el-table-column prop="diameter" label="管径(毫米)" width="110" />
        <el-table-column prop="location" label="位置" min-width="180" />
        <el-table-column prop="buildDate" label="建设日期" width="120" />
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="row.status === '0' ? 'success' : 'danger'">{{ getDictLabel(pipeNetworkStatusDict, row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, sizes"
        :page-sizes="[10, 20, 50]"
        @change="loadData"
        style="margin-top: 16px; justify-content: flex-end"
      />
    </el-card>

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="650px" destroy-on-close>
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="设施编码" prop="networkCode">
          <el-input v-model="formData.networkCode" placeholder="请输入设施编码" />
        </el-form-item>
        <el-form-item label="设施名称" prop="networkName">
          <el-input v-model="formData.networkName" placeholder="请输入设施名称" />
        </el-form-item>
        <el-form-item label="等级">
          <el-select v-model="formData.networkLevel">
            <el-option v-for="d in pipeNetworkLevelDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="管养单位">
          <el-input v-model="formData.managementUnit" placeholder="请输入管养单位" />
        </el-form-item>
        <el-form-item label="位置描述">
          <el-input v-model="formData.location" placeholder="请输入位置描述" />
        </el-form-item>
        <el-form-item label="材质">
          <el-input v-model="formData.material" placeholder="请输入材质" />
        </el-form-item>
        <el-form-item label="长度(米)">
          <el-input-number v-model="formData.length" :precision="2" :step="1" :min="0" placeholder="请输入长度" style="width: 100%" />
        </el-form-item>
        <el-form-item label="管径(毫米)">
          <el-input-number v-model="formData.diameter" :precision="0" :step="1" :min="0" placeholder="请输入管径" style="width: 100%" />
        </el-form-item>
        <el-form-item label="建设日期">
          <el-date-picker v-model="formData.buildDate" type="date" placeholder="请选择建设日期" value-format="YYYY-MM-DD" style="width: 100%" />
        </el-form-item>
        <el-form-item label="经度">
          <el-input-number v-model="formData.longitude" :precision="10" :step="0.0001" placeholder="请输入经度" style="width: 100%" />
        </el-form-item>
        <el-form-item label="纬度">
          <el-input-number v-model="formData.latitude" :precision="10" :step="0.0001" placeholder="请输入纬度" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.status" placeholder="请选择">
            <el-option v-for="d in pipeNetworkStatusDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { getPipeNetworkPage, getPipeNetworkById, addPipeNetwork, updatePipeNetwork, deletePipeNetwork, exportPipeNetwork } from '@/api/pipeNetwork/basic'
import { getDicts } from '@/api/system/dict/data'
import { saveAs } from 'file-saver'

const loading = ref(false)
const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const searchForm = reactive({
  networkName: '', managementUnit: '', networkLevel: '', networkType: '', material: '', status: ''
})

const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const formRef = ref(null)
const formData = reactive({
  networkId: '', networkCode: '', networkName: '', networkType: 'GAS',
  networkLevel: '', managementUnit: '', location: '', material: '',
  length: null, diameter: null, buildDate: null,
  longitude: null, latitude: null, status: '0', remark: ''
})

const rules = {
  networkCode: [{ required: true, message: '请输入设施编码', trigger: 'blur' }],
  networkName: [{ required: true, message: '请输入设施名称', trigger: 'blur' }]
}

const pipeNetworkStatusDict = ref([])
const pipeNetworkLevelDict = ref([])
const pipeNetworkTypeDict = ref([])

function getDictLabel(dict, value) {
  const item = dict.find(d => d.dictValue === value)
  return item ? item.dictLabel : value
}

async function loadDicts() {
  const [statusRes, levelRes, typeRes] = await Promise.all([
    getDicts('pipe_network_status'),
    getDicts('pipe_network_level'),
    getDicts('pipe_network_type')
  ])
  pipeNetworkStatusDict.value = statusRes.data
  pipeNetworkLevelDict.value = levelRes.data
  pipeNetworkTypeDict.value = typeRes.data
}

async function loadData() {
  loading.value = true
  try {
    const res = await getPipeNetworkPage(pageNum.value, pageSize.value, searchForm)
    tableData.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  pageNum.value = 1
  loadData()
}

function handleReset() {
  Object.assign(searchForm, { networkName: '', managementUnit: '', networkLevel: '', networkType: '', material: '', status: '' })
  handleSearch()
}

function handleAdd() {
  dialogTitle.value = '新增'
  Object.assign(formData, { networkId: '', networkCode: '', networkName: '', networkType: 'GAS', networkLevel: '', managementUnit: '', location: '', material: '', length: null, diameter: null, buildDate: null, longitude: null, latitude: null, status: '0', remark: '' })
  dialogVisible.value = true
}

function toDateStr(val) {
  // 转为 yyyy-MM-dd 字符串，供 value-format="YYYY-MM-DD" 的 date-picker 回显
  if (!val) return ''
  if (Array.isArray(val)) {
    return val[0] + '-' + String(val[1]).padStart(2, '0') + '-' + String(val[2]).padStart(2, '0')
  }
  const s = String(val)
  const m = s.match(/^(\d{4})-(\d{2})-(\d{2})/)
  if (m) return m[0]
  const d = new Date(s)
  if (!isNaN(d.getTime())) {
    return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
  }
  return ''
}

function handleEdit(row) {
  dialogTitle.value = '编辑'
  Object.assign(formData, { ...row, buildDate: toDateStr(row.buildDate), networkType: row.networkType || 'GAS' })
  dialogVisible.value = true
}

async function handleSubmit() {
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  try {
    if (formData.networkId) {
      await updatePipeNetwork(formData)
      ElMessage.success('修改成功')
    } else {
      await addPipeNetwork(formData)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    loadData()
  } catch (e) {
    console.error(e)
  }
}

function handleDelete(row) {
  ElMessageBox.confirm('确认删除该管网信息？', '提示', { type: 'warning' }).then(async () => {
    await deletePipeNetwork(row.networkId)
    ElMessage.success('删除成功')
    loadData()
  }).catch(() => {})
}

async function handleExport() {
  const loading = ElLoading.service({ text: '正在导出数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' })
  try {
    const blob = await exportPipeNetwork({ networkName: searchForm.networkName, status: searchForm.status })
    saveAs(new Blob([blob], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), `燃气管网数据_${new Date().toISOString().slice(0, 10)}.xlsx`)
    ElMessage.success('导出成功')
  } catch (e) {
    console.error(e)
    ElMessage.error('导出失败，请稍后重试')
  } finally {
    loading.close()
  }
}

onMounted(async () => { await loadDicts(); loadData() })
</script>

<style scoped>
.pipe-network-container { padding: 16px; }
.search-card { margin-bottom: 16px; }
.search-form { display: flex; flex-wrap: wrap; }
</style>
