<template>
  <div class="pressure-container">
    <!-- 顶部状态栏 -->
    <div class="status-bar card-shadow">
      <div class="status-group">
        <div class="status-item">
          <span class="label">传感器</span>
          <div :class="['status-tag', sensorStatus.sensorConnected ? 'success' : 'error']">
            {{ sensorStatus.sensorConnected ? '已连接' : '未连接' }}
          </div>
        </div>
        <div class="status-item">
          <span class="label">PLC</span>
          <div :class="['status-tag', sensorStatus.plcConnected ? 'success' : 'error']">
            {{ sensorStatus.plcConnected ? '已连接' : '未连接' }}
          </div>
        </div>
        <div class="status-item">
          <span class="label">记录状态</span>
          <div :class="['status-tag', sensorStatus.recordStatus === 'Recording' ? 'processing' : 'default']">
            {{ sensorStatus.recordStatus === 'Recording' ? '记录中' : '空闲' }}
          </div>
        </div>
        <div class="status-item">
          <span class="label">MQTT</span>
          <div :class="['status-tag', mqttConnected ? 'success' : 'error']">
             {{ mqttConnected ? '已连接' : '未连接' }}
          </div>
        </div>
      </div>
      <div class="update-time">
        <i class="el-icon-time"></i>
        <span>数据更新: {{ lastUpdateTime }}</span>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧：实时数据 -->
      <div class="realtime-panel card-shadow">
        <div class="panel-header">
          <span class="title">实时压力监测</span>
          <div v-if="sensorStatus.recordStatus === 'Recording'" class="recording-badge">
            <span class="dot"></span> REC
          </div>
        </div>
        
        <div class="gauge-container">
          <div class="pressure-display">
            <span class="value">{{ displayValue }}</span>
            <span class="unit">{{ sensorStatus.unit || 'kN' }}</span>
          </div>
          <div class="data-meta">
            <div class="meta-item">
               <span class="label">已记录点数</span>
               <span class="count">{{ sensorStatus.dataPointCount }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：历史查询和曲线 -->
      <div class="history-panel card-shadow">
        <div class="panel-header">
          <span class="title">历史数据分析</span>
        </div>
        
        <!-- 查询区域 -->
        <div class="control-bar">
          <el-date-picker
            v-model="queryDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            class="custom-date-picker"
            :clearable="false"
          />
          <el-button type="primary" icon="el-icon-search" @click="queryHistory">查询记录</el-button>
        </div>

        <div class="content-split">
          <!-- 历史记录列表 -->
          <div class="list-section">
            <div class="list-header">记录列表 ({{ historyList.length }})</div>
             <div class="history-list custom-scrollbar">
              <div
                v-for="item in historyList"
                :key="item.ID"
                :class="['history-card', { active: selectedRecord && selectedRecord.ID === item.ID }]"
                @click="viewCurve(item)"
              >
                <div class="card-icon">
                  <i class="el-icon-document"></i>
                </div>
                <div class="card-info">
                  <div class="name">{{ item.记录名称 }}</div>
                  <div class="time">{{ formatTime(item.操作时间) }}</div>
                </div>
                <div class="card-arrow">
                  <i class="el-icon-arrow-right"></i>
                </div>
              </div>
              <div v-if="historyList.length === 0" class="empty-state">
                <i class="el-icon-document-remove"></i>
                <p>暂无当天的记录数据</p>
              </div>
            </div>
          </div>

          <!-- 曲线图 -->
          <div class="chart-section">
            <div ref="chartContainer" class="chart-container"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Mqtt } from '@/utils/mqtt'
import * as echarts from 'echarts'

export default {
  name: 'PressureSensor',
  data() {
    return {
      mqttClient: null,
      mqttConnected: false,
      mqttConnection: {
        host: window.g.mqttIP,
        port: window.g.mqttPortNumber,
        endpoint: '/mqtt',
        clean: true,
        connectTimeout: 4000,
        reconnectPeriod: 4000,
        clientId: 'PressureSensorWeb_' + Math.random().toString(16).substr(2, 8),
        username: 'admin',
        password: '123456'
      },
      sensorStatus: {
        currentValue: null,
        unit: 'kN',
        sensorConnected: false,
        plcConnected: false,
        recordStatus: 'Idle',
        timestamp: null,
        dataPointCount: 0
      },
      lastUpdateTime: '--:--:--',
      queryDateRange: [],
      historyList: [],
      selectedRecord: null,
      chart: null
    }
  },
  computed: {
    displayValue() {
      if (this.sensorStatus.currentValue == null) return '--'
      return this.sensorStatus.currentValue.toFixed(3)
    }
  },
  mounted() {
    this.initMqtt()
    this.initChart()
    const today = new Date().toISOString().split('T')[0]
    this.queryDateRange = [today, today]
  },
  beforeDestroy() {
    if (this.mqttClient) {
      this.mqttClient.destroyConnection()
    }
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    initMqtt() {
      try {
        this.mqttClient = new Mqtt(this.mqttConnection)
        this.mqttClient.createConnection()

        this.mqttClient.client.on('connect', () => {
          console.log('压力传感器MQTT连接成功')
          this.mqttConnected = true
          this.mqttClient.doSubscribe({
            topic: window.g.pressureSensorTopic,
            qos: 0
          })
        })

        this.mqttClient.client.on('error', (error) => {
          console.error('MQTT连接错误', error)
          this.mqttConnected = false
        })

        this.mqttClient.client.on('close', () => {
          this.mqttConnected = false
        })

        this.mqttClient.client.on('message', (topic, message) => {
          if (topic === window.g.pressureSensorTopic) {
            console.log('收到压力传感器数据', message.toString())
            this.handleSensorData(message.toString())
          }
        })
      } catch (error) {
        console.error('MQTT初始化失败', error)
      }
    },

    handleSensorData(message) {
      try {
        const data = JSON.parse(message)
        this.sensorStatus = {
          currentValue: data.CurrentValue,
          unit: data.Unit || 'kN',
          sensorConnected: data.SensorConnected,
          plcConnected: data.PlcConnected,
          recordStatus: data.RecordStatus,
          timestamp: data.Timestamp,
          dataPointCount: data.DataPointCount
        }
        this.lastUpdateTime = new Date().toLocaleTimeString('zh-CN')
      } catch (error) {
        console.error('解析数据失败', error)
      }
    },

    initChart() {
      this.$nextTick(() => {
        if (this.$refs.chartContainer) {
          this.chart = echarts.init(this.$refs.chartContainer)
          this.chart.setOption({
            grid: {
              left: 50,
              right: 40,
              top: 30,
              bottom: 40
            },
            xAxis: {
              type: 'category',
              name: '时间',
              data: [],
              axisLabel: { fontSize: 10 }
            },
            yAxis: {
              type: 'value',
              name: '压力(kN)',
              axisLabel: { fontSize: 10 }
            },
            series: [{
              type: 'line',
              data: [],
              smooth: true,
              lineStyle: { color: '#1890ff', width: 2 },
              areaStyle: { color: 'rgba(24, 144, 255, 0.1)' }
            }],
            tooltip: {
              trigger: 'axis'
            }
          })
        }
      })
    },

    queryHistory() {
      if (!this.queryDateRange || this.queryDateRange.length !== 2) {
        this.$message.warning('请选择日期范围')
        return
      }
      const param = []
      param[0] = ['开始日期', this.queryDateRange[0]]
      param[1] = ['结束日期', this.queryDateRange[1]]
      const Data = this.CreateData('11', '压力记录_索引_查询', param)
      this.ExecDatabase(Data).then(response => {
        this.historyList = response.data || []
        this.selectedRecord = null
        if (this.chart) {
          this.chart.setOption({
            xAxis: { data: [] },
            series: [{ data: [] }]
          })
        }
      }).catch(error => {
        console.error('查询失败', error)
        this.$message.error('查询失败')
      })
    },

    viewCurve(record) {
      this.selectedRecord = record
      const param = []
      param[0] = ['索引ID', record.ID]
      const Data = this.CreateData('11', '压力记录_查询', param)
      this.ExecDatabase(Data).then(response => {
        const curveData = response.data || []
        this.updateChart(curveData, record.记录名称)
      }).catch(error => {
        console.error('查询曲线失败', error)
        this.$message.error('查询曲线失败')
      })
    },

    updateChart(data, title) {
      // if (!this.chart || data.length === 0) return

      // 存储时间戳数据用于tooltip
      const timeData = data.map(item => {
        if (item.记录时间) {
          const d = new Date(item.记录时间)
          return d.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          })
        }
        return '--'
      })
      const xData = data.map((item, index) => index + 1)
      const yData = data.map(item => item.值)

      this.chart.setOption({
        title: {
          text: title || '',
          left: 'center',
          textStyle: { fontSize: 14, color: '#303133', fontWeight: 'bold' }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(50, 50, 50, 0.9)',
          borderColor: '#409eff',
          borderWidth: 1,
          textStyle: { color: '#fff', fontSize: 14 },
          formatter: function(params) {
            const index = params[0].dataIndex
            const value = params[0].value
            const time = timeData[index] || '--'
            return `<div style="padding: 4px 8px;">
              <div style="font-weight: bold; margin-bottom: 6px;">数据点 #${index + 1}</div>
              <div>时间: ${time}</div>
              <div>压力: <span style="color: #67c23a; font-weight: bold;">${value} kN</span></div>
            </div>`
          }
        },
        xAxis: { data: xData },
        series: [{ data: yData }]
      })
    },

    formatTime(dateStr) {
      if (!dateStr) return '--'
      const date = new Date(dateStr)
      return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.pressure-container {
  height: 100%;
  width: 100%;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  padding: 24px;
  box-sizing: border-box;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

.card-shadow {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #ebeef5;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 32px;
  height: 80px;
  margin-bottom: 24px;
}

.status-group {
  display: flex;
  gap: 48px;
}

.status-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.status-item .label {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.status-tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 4px 16px;
  border-radius: 20px;
  font-size: 16px;
  font-weight: 600;
  min-width: 80px;
}

.status-tag.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.status-tag.error {
  background-color: #fef0f0;
  color: #f56c6c;
}

.status-tag.processing {
  background-color: #ecf5ff;
  color: #409eff;
  animation: pulse 2s infinite;
}

.status-tag.default {
  background-color: #f4f4f5;
  color: #909399;
}

.update-time {
  font-size: 14px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* Main Content */
.main-content {
  flex: 1;
  display: flex;
  gap: 24px;
  min-height: 0;
}

.panel-header {
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header .title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  border-left: 4px solid #409eff;
  padding-left: 12px;
}

/* Realtime Panel */
.realtime-panel {
  width: 380px;
  display: flex;
  flex-direction: column;
}

.gauge-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px;
  position: relative;
}

.pressure-display {
  text-align: center;
  margin-bottom: 60px;
}

.pressure-display .value {
  display: block;
  font-size: 80px;
  font-weight: bold;
  color: #409eff;
  font-family: 'DIN Alternate', 'Oswald', sans-serif;
  line-height: 1.2;
  text-shadow: 2px 2px 4px rgba(64, 158, 255, 0.2);
}

.pressure-display .unit {
  font-size: 24px;
  color: #909399;
  font-weight: 500;
  margin-top: 10px;
  display: block;
}

.recording-badge {
  background: #f56c6c;
  color: white;
  padding: 6px 16px;
  border-radius: 16px;
  font-size: 14px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.4);
}

.recording-badge .dot {
  width: 8px;
  height: 8px;
  background: white;
  border-radius: 50%;
  animation: blink 1s infinite;
}

.data-meta {
  width: 100%;
  padding-top: 30px;
  border-top: 2px dashed #ebeef5;
}

.meta-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  color: #606266;
}

.meta-item .count {
  font-weight: bold;
  color: #303133;
  font-size: 20px;
}

/* History Panel */
.history-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.control-bar {
  padding: 20px 24px;
  display: flex;
  gap: 16px;
  background: #fafafa;
  border-bottom: 1px solid #ebeef5;
}

.custom-date-picker {
  width: 340px !important;
}

.content-split {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

.list-section {
  height: 200px;
  min-height: 200px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.list-header {
  padding: 12px 16px;
  font-size: 14px;
  font-weight: 600;
  color: #909399;
  background: #fafafa;
  border-bottom: 1px solid #ebeef5;
  flex-shrink: 0;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.history-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  border: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 16px;
}

.history-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: #c6e2ff;
}

.history-card.active {
  background-color: #ecf5ff;
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.card-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 20px;
}

.history-card.active .card-icon {
  background: #409eff;
  color: white;
}

.card-info {
  flex: 1;
  overflow: hidden;
}

.card-info .name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-info .time {
  font-size: 13px;
  color: #909399;
}

.card-arrow {
  color: #c0c4cc;
}

.history-card.active .card-arrow {
  color: #409eff;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #dcdfe6;
}

.chart-section {
  flex: 1;
  padding: 16px;
  background-color: #fff;
  min-height: 0;
  overflow: hidden;
}

.chart-container {
  width: 100%;
  height: 100%;
}

.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}
.custom-scrollbar::-webkit-scrollbar-track {
  background: #f5f7fa;
}

@keyframes pulse {
  0% { box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4); }
  70% { box-shadow: 0 0 0 10px rgba(64, 158, 255, 0); }
  100% { box-shadow: 0 0 0 0 rgba(64, 158, 255, 0); }
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.4; }
}
</style>
