<template>
  <div class="param_config_card">
    <div class="param_header">
      <h3>{{ title }}</h3>
      <span class="device-type">{{ deviceTypeText }}</span>
    </div>

    <div class="param_content">
      <div class="param_item" v-for="(param, index) in params" :key="index">
        <label class="param_label">{{ param.label }}:</label>
        <input type="number" v-model.number="localParams[param.key]" :min="param.min" :max="param.max"
          class="param_input" :disabled="loading">
        <span class="param_unit">{{ param.unit }}</span>
        <el-button size="mini" type="primary" @click="saveSingleParam(param, index)" :loading="loading">
          保存
        </el-button>
      </div>
    </div>

    <div class="param_actions">
      <button @click="resetParams" :disabled="loading">重置</button>
      <button @click="saveAllParams" class="save_btn" :disabled="loading">
        <span v-if="!loading">批量保存</span>
        <span v-if="loading">保存中...</span>
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { openElWarnMessage } from '@/utils/message'
import { setValues } from '@/api/dcs/flowControl'
import { getAllParamConfigByCode } from '@/api/hnyz/param'

const props = defineProps({
  title: { type: String, required: true },
  code: { type: String, required: true },
  initialParams: { type: Array, default: () => [] }
})

const deviceType = computed(() => {
  const code = props.code.toUpperCase()
  if (code.startsWith('PH')) return 'ph'
  if (code.startsWith('PT')) return 'pressuregauge'
  if (code.startsWith('TT')) return 'thermometer'
  if (code.startsWith('FIT')) return 'flowmeter'
  if (code.startsWith('P') || code.startsWith('M')) return 'pump'
  if (code.startsWith('LT')) return 'levelmeter'
  return 'unknown'
})

const deviceTypeText = computed(() => ({
  'ph': 'PH计',
  'pressuregauge': '压力表',
  'thermometer': '温度计',
  'flowmeter': '流量计',
  'pump': '泵',
  'levelmeter': '液位计',
  'unknown': '未知设备'
}[deviceType.value]))

const paramTemplates = {
  pump: [
    { key: 'startSpeed', label: '起动转速', unit: 'rpm', min: 0 },
    { key: 'maxSpeed', label: '最大转速', unit: 'rpm', min: 0 },
    { key: 'conversionRate', label: '转换速率', unit: '%/s', min: 0 }
  ],
  pressuregauge: [
    { key: 'maxValue', label: '最大值', unit: 'MPa', min: 0, max: 1.6 },
    { key: 'minValue', label: '最小值', unit: 'MPa', min: 0, max: 1.6 },
    { key: 'calibrationValue', label: '标定值', unit: 'MPa' },
    { key: 'alarmValue', label: '报警值', unit: 'MPa' }
  ],
  flowmeter: [
    { key: 'maxFlow', label: '最大流量', unit: 'm³/h', min: 0 },
    { key: 'minFlow', label: '最小流量', unit: 'm³/h', min: 0 },
    { key: 'maxVelocity', label: '最大流速', unit: 'm/s', min: 0 },
    { key: 'minVelocity', label: '最小流速', unit: 'm/s', min: 0 },
    { key: 'conversionRate', label: '转化速率', unit: '%/s', min: 0 }
  ],
  thermometer: [
    { key: 'alarmValue', label: '报警值', unit: '℃' },
    { key: 'calibrationValue', label: '标定值', unit: '℃' }
  ],
  ph: [
    { key: 'maxValue', label: '最大值', unit: 'pH', min: 0, max: 14 },
    { key: 'minValue', label: '最小值', unit: 'pH', min: 0, max: 14 },
    { key: 'calibrationValue', label: '标定值', unit: 'pH' }
  ],
  levelmeter: [
    { key: 'maxLevel', label: '最高液位', unit: 'm', min: 0 },
    { key: 'highLevel', label: '高液位', unit: 'm', min: 0 },
    { key: 'lowLevel', label: '低液位', unit: 'm', min: 0 },
    { key: 'minLevel', label: '最低液位', unit: 'm', min: 0 },
    { key: 'calibrationValue', label: '标定值', unit: 'm' }
  ]
}

const params = computed(() => paramTemplates[deviceType.value] || [])
const paramConfigs = ref([])
const localParams = ref({})
const loading = ref(false)

const initLocalParams = () => {
  const initial = {}
  params.value.forEach((param, index) => {
    initial[param.key] = props.initialParams[index] ?? 0
  })
  localParams.value = initial
  // console.log('initLocalParams', localParams.value)
}

const loadParamConfigs = async () => {
  try {
    loading.value = true
    const res = await getAllParamConfigByCode(props.code)
    paramConfigs.value = res.data || []
  } catch (err) {
    console.error(`获取${props.code}参数配置失败`, err)
    openElWarnMessage(`获取参数配置失败: ${err.message || '未知错误'}`)
  } finally {
    loading.value = false
  }
}

const resetParams = () => {
  initLocalParams()
  openElWarnMessage('已重置为初始值')
}

const saveSingleParam = async (param, index) => {
  const paramValue = localParams.value[param.key]
  if (paramValue === undefined || paramValue === null) {
    openElWarnMessage('参数值不能为空')
    return
  }

  const config = paramConfigs.value[index]
  if (!config) {
    openElWarnMessage(`未找到${param.label}的配置信息（索引：${index}）`)
    return
  }

  try {
    loading.value = true
    const data = {
      protocol: config.protocolId,
      unitId: config.unitId,
      dataType: config.dataType,
      offsetOrIndex: config.address,
      lengthOrQos: 1,
      data: [paramValue],
      ipAddress: config.ipAddress,
      port: config.port
    }
    await setValues(data)
    openElWarnMessage(`${param.label}保存成功`)
  } catch (err) {
    console.error(`保存${param.label}失败`, err)
    openElWarnMessage(`保存失败: ${err.message || '未知错误'}`)
  } finally {
    loading.value = false
  }
}

const saveAllParams = async () => {
  if (params.value.length !== paramConfigs.value.length) {
    openElWarnMessage('参数与配置元数据数量不匹配，无法批量保存')
    return
  }

  try {
    loading.value = true
    for (let i = 0; i < params.value.length; i++) {
      const param = params.value[i]
      const config = paramConfigs.value[i]
      const paramValue = localParams.value[param.key]

      const data = {
        protocol: config.protocolId,
        unitId: config.unitId,
        dataType: config.dataType,
        offsetOrIndex: config.address,
        lengthOrQos: 1,
        data: [paramValue],
        ipAddress: config.ipAddress,
        port: config.port
      }
      await setValues(data)
    }
    openElWarnMessage('所有参数保存成功')
  } catch (err) {
    console.error('批量保存参数失败', err)
    openElWarnMessage(`批量保存失败: ${err.message || '未知错误'}`)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  initLocalParams()
  if (props.code) {
    loadParamConfigs()
  }
})

watch(() => props.code, (newCode) => {
  if (newCode) {
    initLocalParams()
    loadParamConfigs()
  }
})
</script>

<style scoped>
.param_config_card {
  background: #1e293b;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  padding: 16px;
  margin-bottom: 20px;
  border: 1px solid #72E0FF;
}

.param_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.param_header h3 {
  margin: 0;
  color: #76E1FF;
  font-size: 16px;
}

.device-type {
  font-size: 14px;
  color: #ddd;
  background: #192846;
  padding: 4px 8px;
  border-radius: 4px;
}

.param_content {
  margin-bottom: 20px;
}

.param_item {
  display: grid;
  grid-template-columns: 120px 1fr 50px 60px;
  /* 标签(固定) + 输入框(自适应) + 单位(固定) + 按钮(固定) */
  align-items: center;
  margin-bottom: 12px;
  gap: 10px;
  /* 元素间间距 */
}

.param_label {
  font-size: 14px;
  color: #63c8c7;
  text-align: left;
  /* 标签右对齐，视觉更整齐 */
}

.param_input {
  padding: 8px 12px;
  border: 1px solid #475569;
  border-radius: 4px;
  font-size: 14px;
  background: #334155;
  color: #fff;
  width: 100%;
  /* 占满网格分配的空间 */
  box-sizing: border-box;
  /* 避免padding导致宽度溢出 */
}

.param_input:focus {
  outline: none;
  border-color: #409eff;
}

.param_unit {
  font-size: 14px;
  color: #bbb;
  text-align: left;
}

/* 确保按钮不会被挤压 */
:deep(.el-button--mini) {
  width: 100%;
  min-width: 50px;
  /* 按钮最小宽度，避免文字换行 */
}

.param_actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

.param_actions button {
  padding: 8px 16px;
  border: 1px solid #475569;
  border-radius: 4px;
  background: #1e293b;
  color: #ddd;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.param_actions button:hover {
  border-color: #409eff;
  color: #409eff;
}

.save_btn {
  background: #0ea5e9 !important;
  color: white !important;
  border-color: #0ea5e9 !important;
}

.save_btn:hover {
  background: #38bdf8 !important;
  border-color: #38bdf8 !important;
}
</style>
