<template>
  <div class="equipment-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="设备编码">
          <el-input v-model="searchForm.equipmentCode" placeholder="请输入设备编码" clearable style="width:180px" />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.equipmentName" placeholder="请输入设备名称" clearable style="width:180px" />
        </el-form-item>
        <el-form-item label="设备型号">
          <el-input v-model="searchForm.equipmentModel" placeholder="请输入设备型号" clearable style="width:160px" />
        </el-form-item>
        <el-form-item label="制造商">
          <el-input v-model="searchForm.manufacturer" placeholder="请输入制造商" clearable style="width:160px" />
        </el-form-item>
        <el-form-item label="所属片区">
          <el-select v-model="searchForm.district" placeholder="请选择所属片区" clearable style="width:120px">
            <el-option v-for="opt in districtOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </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="equipmentCode" label="设备编码" min-width="130" />
        <el-table-column prop="district" label="所属片区" min-width="100">
          <template #default="{ row }">
            <span>{{ row.district || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设备图片" width="100">
          <template #default="{ row }">
            <div v-if="row.equipmentImage" class="table-image-cell">
              <el-image
                :src="row.equipmentImage"
                fit="cover"
                :preview-src-list="[row.equipmentImage]"
                preview-teleported
                hide-on-click-pdf
                class="equipment-table-image"
              />
            </div>
            <el-tag v-else type="info" size="small">无图</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="equipmentName" label="设备名称" min-width="160" />
        <el-table-column prop="equipmentModel" label="设备型号" width="110" />
        <el-table-column prop="manufacturer" label="制造商" width="110" />
        <el-table-column prop="networkName" label="所属管线" min-width="150">
          <template #default="{ row }">
            <span v-if="row.networkName">{{ row.networkName }}</span>
            <el-tag v-else type="info" size="small">未关联</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pointName" label="所属管点" min-width="150">
          <template #default="{ row }">
            <span v-if="row.pointName">{{ row.pointName }}</span>
            <el-tag v-else type="info" size="small">未关联</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="运行状态" width="90">
          <template #default="{ row }">
            <el-tag v-if="row.currentStatus === 1" type="success" size="small">在用</el-tag>
            <el-tag v-else-if="row.currentStatus === 2" type="warning" size="small">闲置</el-tag>
            <el-tag v-else-if="row.currentStatus === 3" type="danger" size="small">维修</el-tag>
            <el-tag v-else-if="row.currentStatus === 4" type="info" size="small">报废</el-tag>
            <el-tag v-else-if="row.currentStatus === 5" type="warning" size="small">待入库</el-tag>
            <el-tag v-else type="info" size="small">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="报警" width="70">
          <template #default="{ row }">
            <el-tag :type="row.alarmStatus === 1 ? 'danger' : 'success'" size="small">
              {{ row.alarmStatus === 1 ? '报警' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="在线" width="70">
          <template #default="{ row }">
            <el-tag :type="row.onlineStatus === 1 ? 'success' : 'info'" size="small">
              {{ row.onlineStatus === 1 ? '在线' : '离线' }}
            </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="info" size="small" @click="handleDetail(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="设备详情" v-model="detailVisible" width="1100px">
      <el-descriptions v-if="detailData" :column="2" border>
        <el-descriptions-item label="设备编码" :span="1">{{ detailData.equipmentCode }}</el-descriptions-item>
        <el-descriptions-item label="设备名称" :span="1">{{ detailData.equipmentName }}</el-descriptions-item>
        <el-descriptions-item label="设备型号">{{ detailData.equipmentModel }}</el-descriptions-item>
        <el-descriptions-item label="设备类别">{{ detailData.typeName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="规格参数">{{ detailData.equipmentSpec }}</el-descriptions-item>
        <el-descriptions-item label="制造商">{{ detailData.manufacturer }}</el-descriptions-item>
        <el-descriptions-item label="生产日期">{{ detailData.productionDate }}</el-descriptions-item>
        <el-descriptions-item label="所属管线">{{ detailData.networkName || '未关联' }}</el-descriptions-item>
        <el-descriptions-item label="管线等级">{{ detailData.networkLevel || '-' }}</el-descriptions-item>
        <el-descriptions-item label="所属管点">{{ detailData.pointName || '未关联' }}</el-descriptions-item>
        <el-descriptions-item label="管点类型">{{ detailData.pointType || '-' }}</el-descriptions-item>
        <el-descriptions-item label="安装位置">{{ detailData.equipmentLocation }}</el-descriptions-item>
        <el-descriptions-item label="安装时间">{{ detailData.installTime }}</el-descriptions-item>
        <el-descriptions-item label="运行状态">
          <el-tag v-if="detailData.currentStatus === 1" type="success" size="small">在用</el-tag>
          <el-tag v-else-if="detailData.currentStatus === 2" type="warning" size="small">闲置</el-tag>
          <el-tag v-else-if="detailData.currentStatus === 3" type="danger" size="small">维修</el-tag>
          <el-tag v-else-if="detailData.currentStatus === 4" type="info" size="small">报废</el-tag>
          <el-tag v-else-if="detailData.currentStatus === 5" type="warning" size="small">待入库</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="报警状态">
          <el-tag :type="detailData.alarmStatus === 1 ? 'danger' : 'success'" size="small">
            {{ detailData.alarmStatus === 1 ? '报警' : '正常' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="在线状态">
          <el-tag :type="detailData.onlineStatus === 1 ? 'success' : 'info'" size="small">
            {{ detailData.onlineStatus === 1 ? '在线' : '离线' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="维护人员">{{ detailData.maintainer || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ detailData.maintainerPhone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="所属片区">{{ detailData.district || '-' }}</el-descriptions-item>
        <el-descriptions-item label="经度">{{ detailData.longitude || '-' }}</el-descriptions-item>
        <el-descriptions-item label="纬度">{{ detailData.latitude || '-' }}</el-descriptions-item>
        <el-descriptions-item label="设备图片" :span="2">
          <el-image
            v-if="detailData.equipmentImage"
            :src="detailData.equipmentImage"
            fit="cover"
            :preview-src-list="[detailData.equipmentImage]"
            preview-teleported
            class="detail-equipment-image"
          />
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="1100px" destroy-on-close>
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="110px" size="default">
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item label="所属片区" prop="district">
              <el-select v-model="formData.district" placeholder="请选择所属片区" style="width:100%" @change="onDistrictChange">
                <el-option v-for="opt in districtOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编码" prop="equipmentCode">
              <el-input v-model="formData.equipmentCode" placeholder="保存时自动生成" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model="formData.equipmentName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号">
              <el-input v-model="formData.equipmentModel" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item label="规格参数">
              <el-input v-model="formData.equipmentSpec" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制造商">
              <el-input v-model="formData.manufacturer" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item label="设备类别" prop="equipmentTypeId">
              <el-select v-model="formData.equipmentTypeId" placeholder="请选择设备类别" style="width:100%">
                <el-option v-for="t in equipmentTypeOptions" :key="t.id" :label="t.typeName" :value="t.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装位置">
              <el-input v-model="formData.equipmentLocation" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item label="维护人员">
              <el-input v-model="formData.maintainer" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属管线">
              <el-select v-model="formData.networkId" placeholder="请选择管线" clearable style="width:100%" @change="onNetworkChange">
                <el-option v-for="n in networkOptions" :key="n.networkId" :label="`${n.networkName}（${n.networkCode}）`" :value="n.networkId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item label="关联管点">
              <el-select v-model="formData.pointId" placeholder="请先选择管线" clearable style="width:100%">
                <el-option v-for="p in pointOptions" :key="p.pointId" :label="`${p.pointName}（${p.pointCode}）`" :value="p.pointId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度">
              <el-input-number v-model="formData.longitude" :precision="10" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item label="纬度">
              <el-input-number v-model="formData.latitude" :precision="10" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式">
              <el-input v-model="formData.maintainerPhone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="设备图片">
          <el-upload
            class="image-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :http-request="handleUploadRequest"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            accept="image/jpeg,image/png,image/jpg"
          >
            <div v-if="formData.equipmentImage || equipmentImagePreview">
              <img :src="equipmentImagePreview || formData.equipmentImage" alt="设备图片" class="preview-image" />
              <div class="image-uploader-cover">
                <el-icon><Plus /></el-icon>
              </div>
            </div>
            <div v-else class="image-uploader-placeholder">
              <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
              <div>点击上传图片</div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, UploadFilled } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { getEquipmentFullPage, addEquipment, updateEquipment, deleteEquipment, getEquipmentTypeList, getPipeNetworkOptions, getGasPipePointPage } from '@/api/pipeNetwork/basic'

const baseApi = import.meta.env.VITE_APP_BASE_API

const loading = ref(false)
const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchForm = reactive({ equipmentCode: '', equipmentName: '', equipmentModel: '', manufacturer: '', district: '' })
const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const formRef = ref(null)

const rules = {
  equipmentName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  equipmentTypeId: [{ required: true, message: '请选择设备类别', trigger: 'change' }],
  district: [{ required: true, message: '请选择所属片区', trigger: 'change' }]
}

const detailVisible = ref(false)
const detailData = ref(null)
const equipmentTypeOptions = ref([])
const networkOptions = ref([])
const pointOptions = ref([])
const equipmentImagePreview = ref('')
let equipmentImageFile = null

const districtOptions = [
  { label: '城南', value: '城南', prefix: 'CN' },
  { label: '城北', value: '城北', prefix: 'CB' },
  { label: '太常', value: '太常', prefix: 'TC' }
]

const generateEquipmentCode = () => {
  if (!formData.district) return ''
  const opt = districtOptions.find(o => o.value === formData.district)
  if (opt && opt.prefix) {
    const now = new Date()
    const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`
    const timeStr = `${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`
    return `${opt.prefix}-GAS-${dateStr}${timeStr}`
  }
  return ''
}

const formData = reactive({
  district: '',
  equipmentCode: '',
  equipmentName: '', equipmentModel: '',
  equipmentSpec: '', manufacturer: '', equipmentLocation: '', equipmentTypeId: '',
  networkId: '', pointId: '',
  longitude: null, latitude: null, maintainer: '', maintainerPhone: '', remark: '',
  equipmentImage: ''
})

async function loadData() {
  loading.value = true
  try {
    const res = await getEquipmentFullPage(pageNum.value, pageSize.value, searchForm)
    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, { equipmentCode: '', equipmentName: '', equipmentModel: '', manufacturer: '', district: '' })
  handleSearch()
}
async function loadEquipmentTypes() {
  if (equipmentTypeOptions.value.length > 0) return
  try {
    const res = await getEquipmentTypeList()
    const all = res.data || []
    equipmentTypeOptions.value = all.filter(t => t.parentTypeId === '3')
  } catch (e) { console.error(e) }
}
async function loadNetworkOptions() {
  if (networkOptions.value.length > 0) return
  try { const res = await getPipeNetworkOptions(); networkOptions.value = res.data || [] } catch (e) { console.error(e) }
}
async function loadPointOptions(networkId) {
  try {
    const params = networkId ? { networkId } : {}
    const res = await getGasPipePointPage(1, 200, params)
    pointOptions.value = (res.data && res.data.records) ? res.data.records : []
  } catch (e) { console.error(e) }
}
function onNetworkChange(val) {
  formData.pointId = ''
  if (val) { loadPointOptions(val) } else { pointOptions.value = [] }
}
function onDistrictChange() {
  // 当片区变更时，如果正在新增模式下，自动生成设备编码
  if (!formData.equipmentId && formData.district) {
    formData.equipmentCode = generateEquipmentCode()
  }
}
/** 覆盖 el-upload 默认上传行为，不做任何请求 */
function handleUploadRequest() {
  // 空函数，阻止 el-upload 默认的 action 请求
}

/** 图片选择后处理（验证 + 预览） */
function handleImageChange(file) {
  if (!file.raw) return
  const isImage = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png' || file.raw.type === 'image/jpg'
  if (!isImage) {
    ElMessage.error('只能上传图片文件 (JPG/PNG)!')
    return
  }
  const isLt5M = file.raw.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return
  }
  equipmentImageFile = file.raw
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    equipmentImagePreview.value = reader.result
  }
}

/** 图片删除 */
function handleImageRemove() {
  equipmentImageFile = null
  equipmentImagePreview.value = ''
  formData.equipmentImage = ''
}

function handleAdd() {
  dialogTitle.value = '新增'
  const template = { 
    equipmentCode: '', 
    equipmentName: '', 
    equipmentModel: '', 
    equipmentSpec: '', 
    manufacturer: '', 
    equipmentLocation: '', 
    equipmentTypeId: '', 
    networkId: '', 
    pointId: '', 
    longitude: null, 
    latitude: null, 
    maintainer: '', 
    maintainerPhone: '', 
    remark: '',
    district: '',
    equipmentImage: ''
  }
  if (formData.equipmentId) delete formData.equipmentId
  Object.assign(formData, template)
  equipmentImageFile = null
  equipmentImagePreview.value = ''
  dialogVisible.value = true
  loadEquipmentTypes(); loadNetworkOptions()
}
function handleEdit(row) {
  dialogTitle.value = '编辑'
  Object.assign(formData, row)
  // 如果有已有图片，直接使用返回的 URL 生成预览
  if (row.equipmentImage) {
    equipmentImagePreview.value = row.equipmentImage
  } else {
    equipmentImagePreview.value = ''
  }
  equipmentImageFile = null
  dialogVisible.value = true
  loadEquipmentTypes(); loadNetworkOptions()
  if (row.networkId) loadPointOptions(row.networkId)
}
async function handleSave() {
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  
  try {
    // 如果有新图片，先通过 MinIO 通用接口上传到 MinIO
    if (equipmentImageFile) {
      const uploadFormData = new FormData()
      uploadFormData.append('file', equipmentImageFile)
      uploadFormData.append('dir', 'upload') // 指定存储目录（可选）
      const uploadResponse = await request({
        url: '/minio/upload',
        method: 'post',
        data: uploadFormData
      })
      formData.equipmentImage = uploadResponse.url || uploadResponse.fileName
      // 上传完成后清空文件，避免重复上传
      equipmentImageFile = null
    }
    
    const isEdit = !!formData.equipmentId
    if (isEdit) {
      await updateEquipment(formData)
    } else {
      const res = await addEquipment(formData)
      formData.equipmentId = res.data // 后端 saveWithCheck 返回实体 UUID
      if (!formData.equipmentId) {
        ElMessage.error('新增失败，未获取到设备 ID')
        return
      }
    }
    ElMessage.success(isEdit ? '修改成功' : '新增成功')
    dialogVisible.value = false
    loadData()
  } catch (e) {
    const msg = e?.response?.data?.msg || e?.message || '操作失败'
    ElMessage.error(msg)
  }
}
function handleDelete(row) {
  ElMessageBox.confirm('确认删除该设备信息？', '提示', { type: 'warning' }).then(async () => {
    await deleteEquipment(row.equipmentId); ElMessage.success('删除成功'); loadData()
  }).catch(() => {})
}
async function handleDetail(row) {
  detailData.value = row
  detailVisible.value = true
}

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

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

/* 表格图片样式 */
.table-image-cell {
  width: 80px;
}

.equipment-table-image {
  width: 64px;
  height: 64px;
  border-radius: 4px;
  cursor: pointer;
  object-fit: cover;
}

/* 详情图片样式 */
.detail-equipment-image {
  width: 200px;
  height: 200px;
  border-radius: 6px;
  cursor: pointer;
  object-fit: cover;
}

/* 图片上传样式 */
.image-uploader {
  position: relative;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 200px;
  height: 200px;
}

.image-uploader:hover {
  border-color: #409eff;
}

.image-uploader .preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  border-radius: 6px;
}

.image-uploader-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

.image-uploader-placeholder .el-icon--upload {
  font-size: 28px;
  margin-bottom: 8px;
}

.image-uploader-cover {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 6px;
}

.image-uploader:hover .image-uploader-cover {
  opacity: 1;
}

.image-uploader-cover .el-icon {
  color: #fff;
  font-size: 28px;
}
</style>
