<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" class="search-form">
      <el-form-item label="设备名称">
        <el-input v-model="queryParams.equipmentName" placeholder="请输入" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="设备状态">
        <el-select v-model="queryParams.currentStatus" placeholder="请选择" clearable style="width: 200px">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">删除</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备名称" prop="equipmentName" min-width="140" />
      <el-table-column label="设备编号" prop="equipmentCode" min-width="130" />
      <el-table-column label="设备类型" prop="equipmentTypeName" min-width="90">
        <template #default="{ row }">
          <span>{{ row.equipmentTypeName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="安装位置" prop="equipmentLocation" min-width="150" />
      <el-table-column label="设备状态" prop="currentStatus" min-width="90" align="center">
        <template #default="{ row }">
          <el-tag :type="statusTagType(row.currentStatus)">{{ statusText(row.currentStatus) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="报警状态" prop="alarmStatus" min-width="90" align="center">
        <template #default="{ row }">
          <el-tag :type="row.alarmStatus === 1 ? 'danger' : 'success'">{{ row.alarmStatus === 1 ? '报警' : '正常' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="在线状态" prop="onlineStatus" min-width="90" align="center">
        <template #default="{ row }">
          <el-tag :type="row.onlineStatus === 1 ? 'success' : 'info'">{{ row.onlineStatus === 1 ? '在线' : '离线' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="安装时间" prop="installTime" min-width="120" />
      <el-table-column label="最近维护时间" prop="lastMaintainDate" min-width="130" />
      <el-table-column label="下次维护日期" prop="nextMaintainDate" min-width="130" />
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleView(row)">查看</el-button>
          <el-button link type="primary" @click="handleEdit(row)">修改</el-button>
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleQuery"
      @current-change="handlePageChange"
    />

    <!-- 查看详情对话框 -->
    <el-dialog v-model="dialogVisible" title="设备详情" width="700px" :before-close="handleClose">
      <div class="detail-info">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">设备名称：</span>
              <span class="info-value">{{ currentRow.equipmentName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">设备编号：</span>
              <span class="info-value">{{ currentRow.equipmentCode }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">设备类型：</span>
              <span class="info-value">{{ currentRow.equipmentTypeName || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">权属单位：</span>
              <span class="info-value">{{ currentRow.ownershipUnit || '-' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">安装位置：</span>
              <span class="info-value">{{ currentRow.equipmentLocation }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">设备状态：</span>
              <span class="info-value">
                <el-tag :type="statusTagType(currentRow.currentStatus)">{{ statusText(currentRow.currentStatus) }}</el-tag>
              </span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">安装时间：</span>
              <span class="info-value">{{ currentRow.installTime }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">最近维护时间：</span>
              <span class="info-value">{{ currentRow.lastMaintainDate }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="info-item">
              <span class="info-label">备注：</span>
              <span class="info-value">{{ currentRow.remark || '-' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 新增/修改对话框 -->
    <el-dialog v-model="editDialogVisible" :title="editDialogTitle" width="800px" :before-close="handleEditClose">
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model="editForm.equipmentName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编号" prop="equipmentCode">
              <el-input v-model="editForm.equipmentCode" placeholder="请输入设备编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备型号" prop="equipmentModel">
              <el-input v-model="editForm.equipmentModel" placeholder="请输入设备型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipmentTypeId">
              <el-select v-model="editForm.equipmentTypeId" placeholder="请选择设备类型" style="width: 100%">
                <el-option v-for="item in drainageTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备制造商" prop="manufacturer">
              <el-input v-model="editForm.manufacturer" placeholder="请输入设备制造商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产日期" prop="productionDate">
              <el-date-picker v-model="editForm.productionDate" type="date" placeholder="请选择生产日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="设备规格参数" prop="equipmentSpec">
              <el-input v-model="editForm.equipmentSpec" type="textarea" :rows="2" placeholder="请输入设备规格参数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产价值(元)" prop="assetValue">
              <el-input-number v-model="editForm.assetValue" :precision="2" :min="0" placeholder="请输入" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用年限(年)" prop="useLife">
              <el-input-number v-model="editForm.useLife" :min="0" :precision="0" placeholder="请输入" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input-number v-model="editForm.longitude" :precision="8" :min="-180" :max="180" :controls="false" placeholder="请输入经度" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input-number v-model="editForm.latitude" :precision="8" :min="-90" :max="90" :controls="false" placeholder="请输入纬度" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="安装位置" prop="equipmentLocation">
              <el-input v-model="editForm.equipmentLocation" placeholder="请输入安装位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装时间" prop="installTime">
              <el-date-picker v-model="editForm.installTime" type="date" placeholder="请选择安装时间" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="维护人员" prop="maintainer">
              <el-input v-model="editForm.maintainer" placeholder="请输入维护人员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="maintainerPhone">
              <el-input v-model="editForm.maintainerPhone" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权属单位" prop="ownershipUnit">
              <el-input v-model="editForm.ownershipUnit" placeholder="请输入权属单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="editForm.status" placeholder="请选择设备状态" style="width: 100%">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警状态" prop="alarmStatus">
              <el-select v-model="editForm.alarmStatus" placeholder="请选择报警状态" style="width: 100%">
                <el-option label="正常" :value="0" />
                <el-option label="报警" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="在线状态" prop="onlineStatus">
              <el-select v-model="editForm.onlineStatus" placeholder="请选择在线状态" style="width: 100%">
                <el-option label="离线" :value="0" />
                <el-option label="在线" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最近维护时间" prop="lastMaintenanceTime">
              <el-date-picker v-model="editForm.lastMaintenanceTime" type="date" placeholder="请选择维护时间" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="下次维护日期" prop="nextMaintenanceTime">
              <el-date-picker v-model="editForm.nextMaintenanceTime" type="date" placeholder="请选择下次维护日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="editForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleEditClose">取 消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sbjcgl">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getEquipmentPage,
  getEquipmentById,
  addEquipment,
  updateEquipment,
  deleteEquipment,
  batchDeleteEquipment,
  getEquipmentTypeList,
  addEquipmentStatus,
  updateEquipmentStatus
} from '@/api/drainage'

// ==================== 选项配置 ====================
const typeList = ref([])
const typeOptions = computed(() => {
  return typeList.value.map(item => ({ label: item.typeName, value: item.typeId }))
})

const drainageTypeOptions = computed(() => {
  // 找到排水父类记录（typeId为'drainage'且parentTypeId为'0'）
  const drainageParent = typeList.value.find(item => item.typeId === 'drainage' && item.parentTypeId === '0')
  if (!drainageParent) {
    // 如果找不到父类，返回所有非顶级的类型
    return typeList.value.filter(item => item.parentTypeId !== '0' && item.parentTypeId !== null).map(item => ({ label: item.typeName, value: item.id }))
  }
  // 返回parentTypeId等于drainage父类id的子类型
  return typeList.value.filter(item => String(item.parentTypeId) === String(drainageParent.id)).map(item => ({ label: item.typeName, value: item.id }))
})

const statusOptions = [
  { label: '在用', value: 1 },
  { label: '闲置', value: 2 },
  { label: '维修', value: 3 },
  { label: '报废', value: 4 },
  { label: '待入库', value: 5 }
]

function typeText(val) {
  const item = typeList.value.find(t => t.typeId === val)
  return item ? item.typeName : '-'
}

function statusText(val) {
  const item = statusOptions.find(s => s.value === val)
  return item ? item.label : '-'
}

function statusTagType(val) {
  const map = { 1: 'success', 2: 'info', 3: 'warning', 4: 'danger', 5: '' }
  return map[val] || 'info'
}

// ==================== 搜索参数 ====================
const queryParams = ref({
  equipmentName: '',
  equipmentTypeId: 'drainage',
  currentStatus: '',
  pageNum: 1,
  pageSize: 10
})

// ==================== 表格数据 ====================
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 多选
const selectedIds = ref([])
function handleSelectionChange(selection) {
  selectedIds.value = selection.map(item => item.equipmentId)
}

// 加载分页数据
async function loadData() {
  loading.value = true
  try {
    const { pageNum, pageSize, ...rest } = queryParams.value
    const res = await getEquipmentPage(pageNum, pageSize, rest)
    const pageData = res.code !== undefined ? res.data : res
    tableData.value = pageData.records || []
    total.value = pageData.total || 0
  } catch (error) {
    console.error('加载设备列表失败', error)
    ElMessage.error('加载设备列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
function handleQuery() {
  queryParams.value.pageNum = 1
  loadData()
}

function handlePageChange() {
  loadData()
}

onMounted(() => {
  loadTypeList()
  loadData()
})

async function loadTypeList() {
  try {
    const res = await getEquipmentTypeList()
    typeList.value = (res.code !== undefined ? res.data : res) || []
  } catch (error) {
    console.error('加载设备类型失败', error)
    ElMessage.error('加载设备类型失败')
  }
}

// ==================== 查看详情对话框 ====================
const dialogVisible = ref(false)
const currentRow = ref({})

async function handleView(row) {
  try {
    const res = await getEquipmentById(row.equipmentId)
    const detail = res.data || {}
    currentRow.value = {
      ...row,
      ...detail.equipmentInfo,
      ...detail.statusInfo,
      equipmentTypeName: detail.typeInfo ? detail.typeInfo.typeName : (row.equipmentTypeName || '-')
    }
    dialogVisible.value = true
  } catch (error) {
    console.error('获取设备详情失败', error)
    ElMessage.error('获取设备详情失败')
  }
}

function handleClose() {
  dialogVisible.value = false
}

// ==================== 新增/修改对话框 ====================
const editDialogVisible = ref(false)
const editDialogTitle = ref('新增设备')
const editFormRef = ref(null)
const isEditMode = ref(false)
const editRowId = ref(null)

const editForm = ref({
  equipmentName: '',
  equipmentCode: '',
  equipmentModel: '',
  equipmentSpec: '',
  manufacturer: '',
  productionDate: '',
  equipmentTypeId: '',
  assetValue: null,
  useLife: null,
  longitude: null,
  latitude: null,
  equipmentLocation: '',
  installTime: '',
  maintainer: '',
  maintainerPhone: '',
  ownershipUnit: '',
  remark: '',
  // 状态表字段
  status: '',
  alarmStatus: null,
  onlineStatus: null,
  lastMaintenanceTime: '',
  nextMaintenanceTime: ''
})

const editRules = {
  equipmentName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  equipmentCode: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
  equipmentTypeId: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  equipmentLocation: [{ required: true, message: '请输入安装位置', trigger: 'blur' }],
  status: [{ required: true, message: '请选择设备状态', trigger: 'change' }]
}

function handleAdd() {
  isEditMode.value = false
  editDialogTitle.value = '新增设备'
  editRowId.value = null
  editForm.value = {
    equipmentName: '',
    equipmentCode: '',
    equipmentModel: '',
    equipmentSpec: '',
    manufacturer: '',
    productionDate: '',
    equipmentTypeId: '',
    assetValue: null,
    useLife: null,
    longitude: null,
    latitude: null,
    equipmentLocation: '',
    installTime: '',
    maintainer: '',
    maintainerPhone: '',
    ownershipUnit: '',
    remark: '',
    status: '',
    alarmStatus: null,
    onlineStatus: null,
    lastMaintenanceTime: '',
    nextMaintenanceTime: ''
  }
  editDialogVisible.value = true
}

function handleEdit(row) {
  isEditMode.value = true
  editDialogTitle.value = '修改设备'
  editRowId.value = row.equipmentId
  editForm.value = {
    equipmentName: row.equipmentName || '',
    equipmentCode: row.equipmentCode || '',
    equipmentModel: row.equipmentModel || '',
    equipmentSpec: row.equipmentSpec || '',
    manufacturer: row.manufacturer || '',
    productionDate: row.productionDate || '',
    equipmentTypeId: row.equipmentTypeId || '',
    assetValue: row.assetValue || null,
    useLife: row.useLife || null,
    longitude: row.longitude || null,
    latitude: row.latitude || null,
    equipmentLocation: row.equipmentLocation || '',
    installTime: row.installTime ? row.installTime.split(' ')[0] : '',
    maintainer: row.maintainer || '',
    maintainerPhone: row.maintainerPhone || '',
    ownershipUnit: row.ownershipUnit || '',
    remark: row.remark || '',
    status: row.currentStatus || '',
    alarmStatus: row.alarmStatus != null ? row.alarmStatus : null,
    onlineStatus: row.onlineStatus != null ? row.onlineStatus : null,
    lastMaintenanceTime: row.lastMaintainDate || '',
    nextMaintenanceTime: row.nextMaintainDate || ''
  }
  editDialogVisible.value = true
}

function handleEditClose() {
  editDialogVisible.value = false
}

function handleEditSubmit() {
  editFormRef.value.validate(async valid => {
    if (!valid) return

    const formData = {
      equipmentName: editForm.value.equipmentName,
      equipmentCode: editForm.value.equipmentCode,
      equipmentModel: editForm.value.equipmentModel,
      equipmentSpec: editForm.value.equipmentSpec,
      manufacturer: editForm.value.manufacturer,
      productionDate: editForm.value.productionDate || null,
      equipmentTypeId: editForm.value.equipmentTypeId,
      equipmentType: 'drainage',
      assetValue: editForm.value.assetValue,
      useLife: editForm.value.useLife,
      longitude: editForm.value.longitude,
      latitude: editForm.value.latitude,
      equipmentLocation: editForm.value.equipmentLocation,
      installTime: editForm.value.installTime ? editForm.value.installTime + ' 00:00:00' : null,
      maintainer: editForm.value.maintainer,
      maintainerPhone: editForm.value.maintainerPhone,
      ownershipUnit: editForm.value.ownershipUnit,
      remark: editForm.value.remark
    }

    try {
      if (isEditMode.value) {
        formData.equipmentId = editRowId.value
        const res = await updateEquipment(formData)
        if (res.code === 0 || res.code === 200) {
          // 更新设备状态
          if (editForm.value.status) {
            try {
              await updateEquipmentStatus({
                equipmentId: editRowId.value,
                currentStatus: editForm.value.status,
                alarmStatus: editForm.value.alarmStatus,
                onlineStatus: editForm.value.onlineStatus,
                installationAddr: editForm.value.equipmentLocation,
                lastMaintainDate: editForm.value.lastMaintenanceTime || null,
                nextMaintainDate: editForm.value.nextMaintenanceTime || null
              })
            } catch (e) {
              console.warn('更新设备状态失败', e)
            }
          }
          ElMessage.success('修改成功')
        } else {
          ElMessage.error(res.msg || '修改失败')
          return
        }
      } else {
        const res = await addEquipment(formData)
        if (res.code === 0 || res.code === 200) {
          // 新增成功后，创建设备状态记录
          const newEquipmentId = res.data ? (res.data.equipmentId || null) : null
          if (newEquipmentId && editForm.value.status) {
            try {
              await addEquipmentStatus({
                equipmentId: newEquipmentId,
                currentStatus: editForm.value.status,
                alarmStatus: editForm.value.alarmStatus,
                onlineStatus: editForm.value.onlineStatus,
                installationAddr: editForm.value.equipmentLocation,
                lastMaintainDate: editForm.value.lastMaintenanceTime || null,
                nextMaintainDate: editForm.value.nextMaintenanceTime || null
              })
            } catch (e) {
              console.warn('创建设备状态失败', e)
            }
          }
          ElMessage.success('新增成功')
        } else {
          ElMessage.error(res.msg || '新增失败')
          return
        }
      }
      editDialogVisible.value = false
      loadData()
    } catch (error) {
      console.error('提交失败', error)
      ElMessage.error('操作失败')
    }
  })
}

// ==================== 删除功能 ====================
function handleDelete(row) {
  ElMessageBox.confirm(`确认删除设备"${row.equipmentName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteEquipment(row.equipmentId)
      if (res.code === 0 || res.code === 200) {
        ElMessage.success('删除成功')
        loadData()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

function handleBatchDelete() {
  if (selectedIds.value.length === 0) return
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await batchDeleteEquipment(selectedIds.value)
      if (res.code === 0 || res.code === 200) {
        selectedIds.value = []
        ElMessage.success('删除成功')
        loadData()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 16px;
}

.toolbar {
  margin-bottom: 16px;
}

.detail-info {
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  line-height: 32px;
}

.info-label {
  color: #909399;
  font-size: 14px;
  white-space: nowrap;
}

.info-value {
  color: #303133;
  font-size: 14px;
}
</style>
