<template>
  <!-- 曲线监控 -->
  <div style="width: 100%; height: 100%">
    <div class="echartitem" style="width: 100%; height: 100%">
      <!-- <h3 class="selcal">{{ props.selval }}</h3> -->
      <div
        id="line-left"
        ref="chartContainer"
        style="width: 100%; height: 100%"
      ></div>
      
    </div>
  </div>
</template>
  <script setup>
import { ref, onMounted, reactive, markRaw, inject, watch, nextTick } from "vue"
import { RouterView, RouterLink } from "vue-router"
import { request, uploadFile } from "@/utils/request"
import { ElMessage, ElButton, ElDialog, ElSelect } from "element-plus"
import * as echarts from "echarts"
let vars = ref([])
let vals = ref([])
let series = ref([
  
])
let xdata = ref([])
let chartContainer = ref()
let myChart
let chartDom = ref()
let option = ref(null)
let convergeDate = ref([])
let curvedata = ref("")
let state = reactive({
  instance: null
})
const props = defineProps({
  echartdata: {
    type: String
  },
  curvedata: {
    type: String
  }
})
let emit = defineEmits([""])
onMounted(() => {
  myChart = echarts.init(chartContainer.value)
  linechart()
  myChart.resize()

  window.addEventListener('resize', () => {
    myChart.resize()
  })
})
//初始化
const echatinit = () => {
  convergeDate.value = []
  series.value = []
  xdata.value = []
}
// 从websocket取数据
// const getsockechart = (data) => {
//   curvedata.value = data
//   series.value = []
//   let rows = curvedata.value
//   for (let i = 0; i < rows.length; i++) {
//     vars.value = rows[i].vars.split(",")
//     vals.value = rows[i].vals.split(" ")
//     let data = vals.value.map((str) => Number(str))
//     convergeDate.value.push(data)
//     xdata.value.push(rows[i].step)
//   }
//   for (let j = 0; j < vars.value.length; j++) {
//     let firstColumn = convergeDate.value.map((row) => row[j])
//     let item = {
//       name: vars.value[j],
//       type: "line",
//       stack: "Total",
//       data: firstColumn
//     }
//     series.value.push(item)
//   }
//   myChart.setOption({
//     legend: {
//       data: vars.value
//     },
//     xAxis: {
//       data: xdata.value
//     },
//     series: series.value
//   })
//   // linechart();
// }

const getsockechart = (data) => {
  console.log("曲线数据1：", data);

  curvedata.value = data;
  
  let rows = curvedata.value;

  vars = rows[0].vars.split(" ");
  vals = rows[0].vals.split(" ");

  console.log("vars:", vars);
  console.log("vals:", vals);

  xdata.value.push(parseFloat(vals[0]));

  let existingSeries = series.value.find((s) => s.name === vars[1]);

  if (existingSeries) {
    existingSeries.data.push([parseFloat(vals[0]), parseFloat(vals[1])]);
  } else {
    series.value.push({
      name: vars[1],
      type: "line",
      showSymbol: false,
      data: [[parseFloat(vals[0]), parseFloat(vals[1])]], 
    });
  }

  myChart.setOption({
    legend: {
      data: [vars[1]],  // 图例数据
    },
    xAxis: {
      type: "value",  
      min: 0,         
      max: 1,       
    },
    yAxis: {
      type: "value"  // Y 轴也是数值轴
    },
    series: series.value  
  });

  console.log("更新后的 xdata1:", xdata.value);
  console.log("更新后的 series1:", series.value);
};

// 数据转化废弃
// const getshuju = (data) => {
//   curvedata.value = data
//   convergeDate.value = []
//   series.value = []
//   xdata.value = []
//   let rows = JSON.parse(curvedata.value)
//   let num = 0
//   for (let i = 0; i < rows.length; i++) {
//     num += 1
//     vars.value = rows[i].vars.split(",")
//     vals.value = rows[i].vals.split(" ")
//     let data = vals.value.map((str) => Number(str))
//     convergeDate.value.push(data)
//     xdata.value.push(num)
//   }
//   console.log(convergeDate.value)
//   // console.log( convergeDate.value);
//   for (let j = 0; j < vars.value.length; j++) {
//     let firstColumn = convergeDate.value.map((row) => row[j])
//     let item = {
//       name: vars.value[j],
//       type: "line",
//       stack: "Total",
//       data: firstColumn
//     }
//     series.value.push(item)
//   }
//   myChart.setOption({
//     legend: {
//       data: vars.value
//     },
//     xAxis: {
//       data: xdata.value
//     },
//     series: series.value
//   })
// }

const getshuju = (data) => {
  // console.log("曲线数据1：", data);

  curvedata.value = data;
  convergeDate.value = [];
  series.value = [];
  xdata.value = [];
  
  // 解析传入的 JSON 数据
  let rows = JSON.parse(curvedata.value);

  vars = rows[0].vars.split(" ");

  for (let i = 0; i < rows.length; i++) {
    let vals = rows[i].vals.split(" ");
    let existingSeries = series.value.find((s) => s.name === vars[1]);

    if (existingSeries) {
      existingSeries.data.push([parseFloat(vals[0]), parseFloat(vals[1])]);
    } else {
      series.value.push({
        name: vars[1],
        type: "line",
        showSymbol: false,
        data: [[parseFloat(vals[0]), parseFloat(vals[1])]], 
      });
    }
  }

  console.log("vars:", vars);
  console.log("vals:", vals);

  myChart.setOption({
    legend: {
      data: [vars[1]],  // 图例数据
    },
    xAxis: {
      type: "value",  
      min: 0,         
      max: 1,       
    },
    yAxis: {
      type: "value"  // Y 轴也是数值轴
    },
    series: series.value  
  });

  console.log("初始化后的 xdata1:", xdata.value);
  console.log("初始化后的 series1:", series.value);
};

const linechart = () => {
  //  let chartDom = document.getElementById('line');
  //  let  myChart= echarts.init(chartDom);
  option.value = {
    title: {
      text: "几何外形",
      left: "12%",
      top: "5%",
      textStyle: {
        color: "#333333",
        fontSize: 16,
        fontWeight: "normal",
        fontFamily:'Microsoft YaHei'
      },
    },
    tooltip: {
      trigger: "axis", //item
      backgroundColor: "rgba(0,0,0,.6)",
      borderColor: "rgba(147, 235, 248, .8)",
      textStyle: {
        color: "#333333"
      }
    },
    legend: {
      data: vars.value,
      orient: "vertical", // 图例方向 (horizontal水平, vertical垂直)
      right: '4%',
      top: '2%'
    },
    grid: {
      show: false,
      left: "10%",
      right: "5%",
      bottom: "10%",
      containLabel: true
    },
    // toolbox: {
    //   feature: {
    //     saveAsImage: {}
    //   }
    // },
    xAxis: {
      type: "value",
      boundaryGap: false,
      name: "x/c",
      nameGap:40,
      nameTextStyle:{
        fontSize: 16,
        color:'#333333',
        fontFamily:'Microsoft YaHei'
      },
      nameLocation: 'middle',
      data: xdata.value,
      axisLine: {
        //X轴线
        show: true,
        lineStyle: {
          color: "#333333", // 线的颜色
          width: 1, // 线宽
          type: "solid" // 线的类型，默认为实线，可选：'solid', 'dashed', 'dotted'
        }
      },
      splitLine: {
        show: true // 如果不需要网格线，可以设置为 false
      }
    },
    yAxis: {
      type: "value",
      name: "y/c",
      nameGap:40,
      nameTextStyle:{
        fontSize: 16,
        color:'#333333',
        fontFamily:'Microsoft YaHei'
      },
      nameLocation: 'middle',
      axisLine: {
        //Y轴线
        show: true,
        lineStyle: {
          color: "#333333", // 线的颜色
          width: 1, // 线宽
          type: "solid" // 线的类型，默认为实线，可选：'solid', 'dashed', 'dotted'
        }
      },
      axisTick: {
        // Y轴刻度线
        show:true,
      }
    },
    dataZoom: [
      {
        type: "inside", // 鼠标滚轮缩放
        xAxisIndex: [0], // 针对 X 轴
      },
      {
        type: "slider", // 滑动条缩放
        xAxisIndex: [0],
        show: false,
      }
    ],
    series: series.value
  }
  option.value && myChart.setOption(option.value)
  window.onresize = function () {
    // 让图表自适应大小
    myChart.resize()
  }
}
// 监听数据变化，重绘图表
//   watch( myChart.value, () => {
//     console.log(11111)
//     window.onresize = function() {
//           // 让图表自适应大小
//           myChart.value.resize();
//       };
// });
//window.addEventListener('resize', handleResize);
// watch(series, () => {
//   linechart();
// }, { deep: true });
// watch(() =>props.echartdata, (newValue, oldValue) => {
//   // 这里处理 echartData 变化的逻辑
//   console.log(11111)
//   console.log('echartData changed:', newValue);
// //  console.log(optmonitor1.value);
// }, {deep: true ,immediate: true });
defineExpose({ linechart, getshuju, getsockechart, echatinit })
</script>
  <style lang="scss" scoped>
.selcal {
  position: absolute;
  top: 37%;
  width: 26px;
  color: #000;
  font-size: 14px;
  font-weight: bold;
  left: 5px;
}

</style>
 
  