<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryRef" :inline="true" class="search-form">
        <el-form-item label="设备编码">
          <el-input v-model="queryParams.deviceCode" placeholder="请输入设备编码" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="预警类型">
          <el-select v-model="queryParams.warningType" placeholder="请选择" clearable style="width: 160px">
            <el-option v-for="opt in WARNING_TYPE_OPTIONS" :key="opt.warningType" :label="opt.warningType" :value="opt.warningType" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警编码">
          <el-input v-model="queryParams.warningCode" placeholder="请输入预警编码" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</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" v-loading="loading" border style="width: 100%">
        <el-table-column label="设备编码" prop="deviceCode" min-width="140" show-overflow-tooltip />
        <el-table-column label="设备名称" min-width="140" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getDeviceName(row.deviceCode) }}
          </template>
        </el-table-column>
        <el-table-column label="设备类型" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getDeviceType(row.deviceCode) }}
          </template>
        </el-table-column>
        <el-table-column label="预警类型" prop="warningType" min-width="120" />
        <el-table-column label="预警编码" prop="warningCode" min-width="140" />
        <el-table-column label="最小值" prop="minValue" width="90" align="center" />
        <el-table-column label="最大值" prop="maxValue" width="90" align="center" />
        <el-table-column label="备注" prop="remark" min-width="120" show-overflow-tooltip />
        <el-table-column label="创建时间" prop="createTime" width="170" />
        <el-table-column label="操作" width="160" align="center" 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]"
        @size-change="handleSizeChange" @current-change="handlePageChange"
        style="margin-top: 16px; justify-content: flex-end"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" destroy-on-close>
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="选择设备" prop="deviceCode">
          <el-select v-model="formData.deviceCode" placeholder="请选择设备" filterable clearable style="width: 100%"
            @click="loadGasDeviceOptions">
            <el-option v-for="d in deviceOptions" :key="d.equipmentCode" :label="d.equipmentCode + ' - ' + d.equipmentName" :value="d.equipmentCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警类型" prop="warningType">
          <el-select v-model="formData.warningType" placeholder="请选择预警类型" style="width: 100%" @change="onWarningTypeChange">
            <el-option v-for="opt in WARNING_TYPE_OPTIONS" :key="opt.warningType" :label="opt.warningType" :value="opt.warningType" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警编码">
          <el-input v-model="formData.warningCode" placeholder="选择预警类型后自动带出" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最小值" prop="minValue">
              <el-input-number v-model="formData.minValue" :precision="2" :min="0" style="width: 100%" placeholder="阈值最小值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大值" prop="maxValue">
              <el-input-number v-model="formData.maxValue" :precision="2" :min="0" style="width: 100%" placeholder="阈值最大值" />
            </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="handleSave" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GasThreshold">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getWarningThresholdModulePage, saveWarningThreshold, updateWarningThreshold, deleteWarningThreshold, getEquipmentByTopLevelType } from '@/api/pipeNetwork/basic'

const GAS_MODULE_TYPE = '燃气'

// ==================== 燃气模块预警类型与预警编码参考 ====================
const WARNING_TYPE_OPTIONS = [
  { warningType: '可燃气体浓度预警', warningCode: 'WARN-GAS-CONCENTRATION' },
  { warningType: '可燃气体温度预警', warningCode: 'WARN-GAS-TEMPERATURE' },
  { warningType: '可燃气体湿度预警', warningCode: 'WARN-GAS-HUMIDITY' },
  { warningType: '压力预警', warningCode: 'WARN-PRESSURE' },
  { warningType: '温度预警', warningCode: 'WARN-TEMPERATURE' },
  { warningType: '湿度预警', warningCode: 'WARN-HUMIDITY' }
]

// ==================== 搜索参数 ====================
const queryParams = reactive({
  deviceCode: '',
  warningType: '',
  warningCode: ''
})
const queryRef = ref(null)

function handleQuery() {
  pageNum.value = 1
  loadData()
}
function resetQuery() {
  queryParams.deviceCode = ''
  queryParams.warningType = ''
  queryParams.warningCode = ''
  pageNum.value = 1
  loadData()
}

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

async function loadData() {
  loading.value = true
  try {
    const params = {}
    if (queryParams.deviceCode) params.deviceCode = queryParams.deviceCode
    if (queryParams.warningType) params.warningType = queryParams.warningType
    if (queryParams.warningCode) params.warningCode = queryParams.warningCode
    const res = await getWarningThresholdModulePage(pageNum.value, pageSize.value, GAS_MODULE_TYPE, params)
    const pageData = res.data || res
    tableData.value = pageData.records || []
    total.value = pageData.total || 0
  } catch (e) {
    console.error('加载阈值列表失败', e)
    ElMessage.error('加载阈值列表失败')
  } finally {
    loading.value = false
  }
}

function handlePageChange() { loadData() }
function handleSizeChange() { pageNum.value = 1; loadData() }

// ==================== 设备名称/类型映射 ====================
const deviceInfoMap = ref({})

async function ensureDeviceMap() {
  if (Object.keys(deviceInfoMap.value).length > 0) return
  try {
    const res = await getEquipmentByTopLevelType(GAS_MODULE_TYPE)
    const list = res.data || []
    const map = {}
    list.forEach(d => { map[d.equipmentCode] = d })
    deviceInfoMap.value = map
  } catch (e) { console.error('加载燃气设备列表失败', e) }
}

function getDeviceName(deviceCode) {
  const d = deviceInfoMap.value[deviceCode]
  return d ? d.equipmentName : deviceCode
}

function getDeviceType(deviceCode) {
  const d = deviceInfoMap.value[deviceCode]
  return d ? (d.typeName || '-') : '-'
}

// ==================== 新增/编辑 ====================
const dialogVisible = ref(false)
const dialogTitle = ref('新增阈值')
const formRef = ref(null)
const submitLoading = ref(false)
const isEdit = ref(false)

const rules = {
  deviceCode: [{ required: true, message: '请选择设备', trigger: 'change' }],
  warningType: [{ required: true, message: '请选择预警类型', trigger: 'change' }]
}

const formData = reactive({
  id: '',
  deviceCode: '',
  warningType: '',
  warningCode: '',
  minValue: null,
  maxValue: null,
  remark: ''
})

const deviceOptions = ref([])

async function loadGasDeviceOptions() {
  if (deviceOptions.value.length > 0) return
  try {
    const res = await getEquipmentByTopLevelType(GAS_MODULE_TYPE)
    deviceOptions.value = res.data || []
  } catch (e) {
    console.error('加载燃气设备列表失败', e)
  }
}

function resetForm() {
  formData.id = ''
  formData.deviceCode = ''
  formData.warningType = ''
  formData.warningCode = ''
  formData.minValue = null
  formData.maxValue = null
  formData.remark = ''
  isEdit.value = false
  dialogTitle.value = '新增阈值'
}

// 选择预警类型后自动带出预警编码
function onWarningTypeChange(val) {
  const opt = WARNING_TYPE_OPTIONS.find(o => o.warningType === val)
  formData.warningCode = opt ? opt.warningCode : ''
}

async function handleAdd() {
  resetForm()
  await loadGasDeviceOptions()
  dialogVisible.value = true
}

function handleEdit(row) {
  isEdit.value = true
  dialogTitle.value = '编辑阈值'
  formData.id = row.id || ''
  formData.deviceCode = row.deviceCode
  formData.warningType = row.warningType
  formData.warningCode = row.warningCode || ''
  formData.minValue = row.minValue
  formData.maxValue = row.maxValue
  formData.remark = row.remark || ''
  dialogVisible.value = true
}

async function handleSave() {
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  submitLoading.value = true
  try {
    const data = {
      deviceCode: formData.deviceCode,
      warningType: formData.warningType,
      warningCode: formData.warningCode || undefined,
      minValue: formData.minValue,
      maxValue: formData.maxValue,
      remark: formData.remark || undefined
    }
    if (isEdit.value) {
      data.id = formData.id
      await updateWarningThreshold(data, GAS_MODULE_TYPE)
      ElMessage.success('修改成功')
    } else {
      await saveWarningThreshold(data, GAS_MODULE_TYPE)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    loadData()
    // 刷新设备映射
    deviceInfoMap.value = {}
    await ensureDeviceMap()
  } catch (e) {
    const msg = e?.response?.data?.msg || e?.message || '操作失败'
    ElMessage.error(msg)
  } finally {
    submitLoading.value = false
  }
}

// ==================== 删除 ====================
function handleDelete(row) {
  ElMessageBox.confirm('确认删除该阈值配置？', '提示', { type: 'warning' }).then(async () => {
    try {
      await deleteWarningThreshold([row.id])
      ElMessage.success('删除成功')
      loadData()
    } catch (e) {
      ElMessage.error(e?.response?.data?.msg || '删除失败')
    }
  }).catch(() => {})
}

// ==================== 生命周期 ====================
onMounted(async () => {
  await ensureDeviceMap()
  loadData()
})
</script>

<style scoped>
.app-container {
  padding: 16px;
}
.search-card {
  margin-bottom: 16px;
}
.search-form {
  display: flex;
  flex-wrap: wrap;
}
.table-card {
  min-height: 400px;
}
</style>
