<template>
  <div class="pipe-point-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="管点名称">
          <el-input v-model="searchForm.pointName" placeholder="请输入管点名称" clearable style="width:180px" />
        </el-form-item>
        <el-form-item label="管点编码">
          <el-input v-model="searchForm.pointCode" placeholder="请输入管点编码" clearable style="width:180px" />
        </el-form-item>
        <el-form-item label="所属管线">
          <el-select v-model="searchForm.networkId" placeholder="请选择" clearable style="width:200px">
            <el-option v-for="opt in networkOptions" :key="opt.networkId" :label="opt.networkName" :value="opt.networkId" />
          </el-select>
        </el-form-item>
        <el-form-item label="管点类型">
          <el-select v-model="searchForm.pointType" placeholder="请选择" clearable style="width:160px">
            <el-option v-for="d in pointTypeDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width:140px">
            <el-option v-for="d in pointStatusDict" :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-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="pointCode" label="管点编码" min-width="130" />
        <el-table-column prop="pointName" label="管点名称" min-width="150" />
        <el-table-column prop="networkName" label="所属管线" min-width="150" />
        <el-table-column prop="pointType" label="管点类型" width="110">
          <template #default="{ row }">{{ getDictLabel(pointTypeDict, row.pointType) }}</template>
        </el-table-column>
        <el-table-column prop="address" label="地址" min-width="180" />
        <el-table-column label="经度" width="110">
          <template #default="{ row }">{{ row.longitude }}</template>
        </el-table-column>
        <el-table-column label="纬度" width="110">
          <template #default="{ row }">{{ row.latitude }}</template>
        </el-table-column>
        <el-table-column prop="diameter" label="管径(mm)" width="100" />
        <el-table-column prop="material" label="材质" width="100" />
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="row.status === '0' ? 'success' : row.status === '1' ? 'danger' : 'info'">
              {{ getDictLabel(pointStatusDict, row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" size="small" @click="handleViewDevices(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-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="管点编码" prop="pointCode">
              <el-input v-model="formData.pointCode" placeholder="请输入管点编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管点名称" prop="pointName">
              <el-input v-model="formData.pointName" placeholder="请输入管点名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属管线" prop="networkId">
              <el-select v-model="formData.networkId" placeholder="请选择管线" style="width:100%">
                <el-option v-for="opt in networkOptions" :key="opt.networkId" :label="opt.networkName" :value="opt.networkId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管点类型" prop="pointType">
              <el-select v-model="formData.pointType" placeholder="请选择" style="width:100%">
                <el-option v-for="d in pointTypeDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度">
              <el-input-number v-model="formData.longitude" :precision="10" :step="0.0001" placeholder="经度" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度">
              <el-input-number v-model="formData.latitude" :precision="10" :step="0.0001" placeholder="纬度" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="管径(mm)">
              <el-input-number v-model="formData.diameter" :precision="2" :step="1" placeholder="管径" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="材质">
              <el-input v-model="formData.material" placeholder="请输入材质" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="埋深(米)">
              <el-input-number v-model="formData.depth" :precision="2" :step="0.1" placeholder="埋深" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建设日期">
              <el-date-picker v-model="formData.buildDate" type="date" placeholder="选择日期" style="width:100%" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址">
          <el-input v-model="formData.address" placeholder="请输入地址/位置描述" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="formData.status" style="width:100%">
                <el-option v-for="d in pointStatusDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <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>

    <el-dialog title="关联设备" v-model="deviceDialogVisible" width="800px" destroy-on-close>
      <div v-if="currentPoint" class="device-section">
        <div class="device-header">
          <span>管点「{{ currentPoint.pointName }}」关联的设备列表</span>
          <el-button type="primary" size="small" @click="handleAddDevice">新增设备</el-button>
        </div>
        <el-table :data="deviceList" border stripe v-loading="deviceLoading" style="margin-top:12px">
          <el-table-column prop="equipmentId" label="设备ID" width="150" />
          <el-table-column prop="equipmentName" label="设备名称" min-width="150" />
          <el-table-column prop="equipmentType" label="设备类型" width="120" />
          <el-table-column prop="status" label="状态" width="90">
            <template #default="{ row: dev }">
              <el-tag :type="dev.status === '0' ? 'success' : 'danger'" size="small">{{ dev.status === '0' ? '正常' : '异常' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row: dev }">
              <el-button type="danger" size="small" @click="handleDeleteDevice(dev)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="deviceDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getGasPipePointPage, getGasPipePointById, addGasPipePoint,
  updateGasPipePoint, deleteGasPipePoint, getGasPipePointByNetwork,
  getPipeNetworkOptions, getPipePointDevices, deletePipePointDeviceRel
} from '@/api/pipeNetwork/basic'
import { getDicts } from '@/api/system/dict/data'

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

const searchForm = reactive({
  pointName: '', pointCode: '', networkId: '', pointType: '', status: ''
})

const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const formRef = ref(null)
const formData = reactive({
  pointId: '', pointCode: '', pointName: '', networkId: '', networkName: '',
  pointType: '', longitude: null, latitude: null, address: '', diameter: null,
  material: '', depth: null, buildDate: '', status: '0', remark: ''
})

const rules = {
  pointCode: [{ required: true, message: '请输入管点编码', trigger: 'blur' }],
  pointName: [{ required: true, message: '请输入管点名称', trigger: 'blur' }],
  networkId: [{ required: true, message: '请选择所属管线', trigger: 'change' }],
  pointType: [{ required: true, message: '请选择管点类型', trigger: 'change' }]
}

const deviceDialogVisible = ref(false)
const currentPoint = ref(null)
const deviceList = ref([])
const deviceLoading = ref(false)

const pointTypeDict = ref([])
const pointStatusDict = ref([])

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

async function loadDicts() {
  const [typeRes, statusRes] = await Promise.all([
    getDicts('gas_pipe_point_type'),
    getDicts('gas_pipe_point_status')
  ])
  pointTypeDict.value = typeRes.data || []
  pointStatusDict.value = statusRes.data || []
}

async function loadNetworkOptions() {
  try {
    const res = await getPipeNetworkOptions()
    networkOptions.value = res.data || []
  } catch (e) { console.error(e) }
}

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

function handleSearch() { pageNum.value = 1; loadData() }
function handleReset() {
  Object.assign(searchForm, { pointName: '', pointCode: '', networkId: '', pointType: '', status: '' })
  handleSearch()
}

function handleAdd() {
  dialogTitle.value = '新增管点'
  Object.assign(formData, {
    pointId: '', pointCode: '', pointName: '', networkId: '', networkName: '',
    pointType: '', longitude: null, latitude: null, address: '', diameter: null,
    material: '', depth: null, buildDate: '', status: '0', remark: ''
  })
  dialogVisible.value = true
}

function handleEdit(row) {
  dialogTitle.value = '编辑管点'
  Object.assign(formData, {
    pointId: row.pointId || '', pointCode: row.pointCode || '', pointName: row.pointName || '',
    networkId: row.networkId || '', networkName: row.networkName || '',
    pointType: row.pointType || '', longitude: row.longitude, latitude: row.latitude,
    address: row.address || '', diameter: row.diameter, material: row.material || '',
    depth: row.depth, buildDate: row.buildDate || '', status: row.status || '0', remark: row.remark || ''
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  try {
    const selectedNetwork = networkOptions.value.find(o => o.networkId === formData.networkId)
    if (selectedNetwork) {
      formData.networkName = selectedNetwork.networkName
    }
    if (formData.pointId) {
      await updateGasPipePoint({ ...formData })
      ElMessage.success('修改成功')
    } else {
      await addGasPipePoint({ ...formData })
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    loadData()
  } catch (e) {
    console.error(e)
  }
}

function handleDelete(row) {
  ElMessageBox.confirm(`确认删除管点「${row.pointName}」？`, '提示', { type: 'warning' }).then(async () => {
    try {
      await deleteGasPipePoint(row.pointId)
      ElMessage.success('删除成功')
      loadData()
    } catch (e) { console.error(e) }
  }).catch(() => {})
}

async function handleViewDevices(row) {
  currentPoint.value = row
  deviceDialogVisible.value = true
  deviceLoading.value = true
  try {
    const res = await getPipePointDevices(row.pointId)
    deviceList.value = res.data || []
  } catch (e) {
    deviceList.value = []
    console.error(e)
  } finally {
    deviceLoading.value = false
  }
}

function handleAddDevice() {
  ElMessage.info('请在设备管理页面中关联管点')
}

async function handleDeleteDevice(dev) {
  ElMessageBox.confirm('确认移除该设备关联？', '提示', { type: 'warning' }).then(async () => {
    try {
      await deletePipePointDeviceRel(dev.relId)
      ElMessage.success('移除成功')
      handleViewDevices(currentPoint.value)
    } catch (e) { console.error(e) }
  }).catch(() => {})
}

onMounted(async () => {
  await Promise.all([loadDicts(), loadNetworkOptions()])
  loadData()
})
</script>

<style scoped>
.pipe-point-container { padding: 16px; }
.search-card { margin-bottom: 16px; }
.search-form { display: flex; flex-wrap: wrap; }
.device-header { display: flex; justify-content: space-between; align-items: center; }
</style>
