<template>
  <div>
    <!-- <div class="eqData_title">
            <div class="eqData_title_center"> 设备数据展示 </div>
            <div class="eqData_title_right">

                <img :src="searchImg" class="eqData_title_right_icon" />

                <input type="text" v-model="searchText" placeholder="搜索" class="eqData_title_right_input"></input>
            </div>
        </div> -->
    <div id="main" style="width: 1200px; height: 800px;" />
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'DynamicChart',
  data() {
    return {
      chart: null, // ECharts 实例
      dataKD: [], // 开度数据数组
      dataWD: [], // 温度数据数组
      now: new Date(2025, 1, 13), // 初始日期
      oneDay: 24 * 3600 * 1000, // 一天的毫秒数
      valueKD: Math.random() * 90 + 10, // 开度初始随机值
      valueWD: Math.random() * 90 + 10, // 温度初始随机值

      searchImg: require('@/assets/dcs/eqData/search.svg'), // 搜索图标
      searchText: '', // 搜索框输入值

      ws: null,
      wsUrl: 'ws://10.147.17.240:9000' // 替换为你的 WebSocket 服务器地址
    }
  },
  mounted() {
    // this.connect(); // 连接 WebSocket 服务器
    this.initChart() // 初始化图表
    //   this.generateInitialData(); // 生成初始数据
    setInterval(() => this.updateData(), 1000) // 每秒更新数据
  },

  beforeDestroy() {
    this.disconnect()
  },
  methods: {
    // 初始化 ECharts 实例并设置初始选项
    initChart() {
      this.chart = echarts.init(this.$el, 'dark')
      const option = {
        title: {
          text: '1号阀门的温度开度数据' // 标题
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const date = new Date(params[0].name)
            return (
              date.getFullYear() +
              '/' +
              (date.getMonth() + 1) +
              '/' +
              date.getDate() +
              '<br/>' +
              params.map(item => item.seriesName + ': ' + item.value[1]).join('<br/>')
            )
          },
          axisPointer: {
            animation: false
          }
        },
        legend: {
          data: ['KD', 'WD'] // 图例
        },
        xAxis: {
          type: 'time',
          splitLine: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '100%'],
          splitLine: {
            show: false
          }
          // axisLabel: {
          //     // formatter: '{value}' // 默认情况下，ECharts 会自动处理浮点数
          //     formatter: function (value) {
          //         return value.toFixed(1);
          //     }
          // }
        },
        series: [
          {
            name: 'KD',
            type: 'line',
            showSymbol: false, // 取消显示标记点
            data: this.dataKD
          },
          {
            name: 'WD',
            type: 'line',
            showSymbol: false,
            data: this.dataWD
          }
        ]
      }
      this.chart.setOption(option)
    },

    // 生成初始数据点
    // generateInitialData() {
    //     for (let i = 0; i < 1000; i++) {
    //         this.dataKD.push(this.randomData('KD'));
    //         this.dataWD.push(this.randomData('WD'));
    //     }
    // },

    // 更新数据，移除旧的数据点并添加新的数据点
    updateData() {
      if (this.dataKD.length > 1000) {
        // for (let i = 0; i < 5; i++) {
        this.dataKD.shift()
        this.dataKD.push(this.randomData('KD'))

        this.dataWD.shift()
        this.dataWD.push(this.randomData('WD'))
        // }
      } else {
        // for (let i = 0; i < 5; i++) {
        //   this.dataKD.shift();
        this.dataKD.push(this.randomData('KD'))

        //   this.dataWD.shift();
        this.dataWD.push(this.randomData('WD'))
        // }
      }

      this.chart.setOption({
        series: [
          {
            data: this.dataKD
          },
          {
            data: this.dataWD
          }
        ]
      })
    },

    // 生成随机数据点
    randomData(type) {
      this.now = new Date(+this.now + this.oneDay)
      let value
      if (type === 'KD') {
        this.valueKD = this.valueKD + Math.random() * 21 - 10
        value = this.valueKD
      } else if (type === 'WD') {
        this.valueWD = this.valueWD + Math.random() * 21 - 10
        value = this.valueWD
      }
      return {
        name: this.now.toString(),
        value: [
          [this.now.getFullYear(), this.now.getMonth() + 1, this.now.getDate()].join('/'),
          Math.round(value).toFixed(1)
        ]
      }
    },

    // 连接 WebSocket 服务器
    connect() {
      // const that = this.chart;
      this.ws = new WebSocket(this.wsUrl)
      this.ws.onopen = () => {
        console.log('WebSocket connection opened')
      }

      this.ws.onmessage = (event) => {
        const arrData = JSON.parse(event.data)
        console.log('接收到数据', arrData.data[0])

        // this.now = new Date(+this.now + this.oneDay);
        // if (arrData.code == "0001") {
        //     if (this.dataKD.length > 1000) {
        //         this.dataKD.shift();
        //         this.dataKD.push(arrData.data[0]);
        //     } else {
        //         this.dataKD.push({
        //             name: this.now.toString(),
        //             value: [
        //                 [this.now.getFullYear(), this.now.getMonth() + 1, this.now.getDate()].join('/'),
        //                 arrData.data[0],
        //             ],
        //         });
        //     }

        // }
        // else if (arrData.code == "0201") {
        //     if (this.dataWD.length > 1000) {
        //         this.dataWD.shift();
        //         this.dataWD.push(arrData.data[0]);
        //     } else {
        //         this.dataWD.push(this.dataKD.push({
        //             name: this.now.toString(),
        //             value: [
        //                 [this.now.getFullYear(), this.now.getMonth() + 1, this.now.getDate()].join('/'),
        //                 arrData.data[0],
        //             ],
        //         }));
        //     }

        // }
      }

      this.ws.onclose = () => {
        console.log('WebSocket connection closed')
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket error:', error)
      }
    },
    sendMessage(msg) {
      if (this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(msg)
      } else {
        console.warn('WebSocket 连接未打开，无法发送消息。')
      }
    },

    disconnect() {
      if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
        this.ws.close()
      } else {
        console.warn('WebSocket 已经关闭或正在关闭，无法再关闭。')
      }
    }
  }
}
</script>

<style scoped lang="scss">
.eqData_title {
  background-image: url('~@/assets/dcs/eqData/header.svg');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  width: 1919.5px;
  height: 74.5px;
  flex-shrink: 0;
  position: relative;

  .eqData_title_center {
    font-family: PangMenZhengDao;
    font-size: 36px;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
    letter-spacing: 7.2px;
    background: linear-gradient(180deg, #FFF 32.33%, #00ABFF 130.49%);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    text-align: center;
    margin-top: 10px;
  }

  .eqData_title_right {
    position: absolute;
    right: 220px;
    top: 10px;
    display: inline-flex;
    padding: 4px 8px;
    justify-content: center;
    align-items: center;
    gap: 4px;
    border-radius: 5px;
    background: #446094;

    .eqData_title_right_icon {
      width: 16px;
      height: 16px;
    }

    .eqData_title_right_input {
      width: 196px;
      border: none;
      background-color: transparent;
      color: #B4C7D9 !important;
      font-family: "PingFang SC";
      font-size: 14px;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
    }

    input:focus {
      outline: none;
    }

  }
}
</style>
