<template>

  <div class="elbutton" style="width: 100% ;max-height: 50px;">
    <el-button class="plotbutton">求导</el-button>
    <el-checkbox v-model="Prameter.smooth" @change="singleshowclicked($event,'Smooth')">平滑</el-checkbox>
    <el-checkbox @change="singleshowclicked($event,'single')">单条显示</el-checkbox>
    <el-checkbox @change="singleshowclicked($event,'Radiance')">Radiance</el-checkbox>

    <el-button class="plotbutton" @click="onsavetcliked">导出数据</el-button>

  </div>

  <div class="echartbox">

    <div class="chart-container" ref="chart"></div>
  </div>


</template>

<script>
import * as echarts from 'echarts';
import 'zrender/lib/svg/svg';

export default {
  name: "GuiForPlotShow",

  data() {
    return {
      Prameter: {
        smooth: false,
        singleshow: false,
        Radiance: "DN",
        Data: null,
        zoomLock: false
      },
      //chart: null
    };
  },
  methods: {

    singleshowclicked(event, slots) {
      if (slots == 'Radiance') {
        if (event) {
          this.Prameter.Radiance = "Radiance";
        } else {
          this.Prameter.Radiance = "DN";
        }
        if (this.Prameter.Data) {
          this.onloaddata(this.Prameter.Data);
        }

      }


      // const customText = event.target.getAttribute('custom-text');
      if (slots == 'single') {
        if (event) {
          this.option.legend.selectedMode = 'single';
        } else {
          this.option.legend.selectedMode = 'multiple';
          let lenthofseries = this.option.series.length;
          this.option.legend.selected = [];
          for (let i = 0; i < lenthofseries; i++) {
            this.option.legend.selected.push(true);
          }
        }
      }
      if (slots == 'Smooth') {
        let lenthofseries = this.option.series.length;
        this.option.legend.selected = [];
        for (let i = 0; i < lenthofseries; i++) {
          this.option.series[i].smooth = event;
        }
      }
      this.flushplot();
    },
    onsavetcliked(){
      let data=this.option;
      var lenthofseries = data.series.length;
      let xdata = [];
      let xbegin = data.xAxis.min;
      let xend = data.xAxis.max;
      for (let i = xbegin; i <= xend; i++) {
        xdata.push(i);
      }
      var datalenth=data.series[0].data.length;
      let content = "weavelength,";
      for (let i = 0; i < lenthofseries; i++) {
        content += data.series[i].name +",";

      }
      content += "\n";
      for (let i = 0; i < datalenth; i++) {
        content += xdata[i] + ",";
        for (let j = 0; j < lenthofseries; j++) {
          content += data.series[j].data[i][1] + ",";
        }
        content += "\n";
      }

      let orgdata=this.Prameter.Data;
      if (!orgdata){
        alert("没有数据")
        return;
      }
      let dateget=orgdata["Date"];
      // dataget 是"2024-05-11 12:01:31" 格式 转换成2024_05_11_12_01_31
      let dataname=dateget.replace(/-/g,"_");
      dataname=dataname.replace(/:/g,"_");
      dataname=dataname.replace(" ","_");
      dataname=dataname+"_"+this.Prameter.Radiance+".csv";

     // alert(dateget1);


      createAndDownloadFile(dataname, content);


    },
    flushplot() {
      const chartDom = this.$refs.chart;
      let chart = echarts.getInstanceByDom(chartDom);
      chart.setOption(this.option);
    },
    onloaddata(data) {
      this.Prameter.Data = data;
      const chartDom = this.$refs.chart;
      let chart = echarts.getInstanceByDom(chartDom);
      this.option.series = [];
      // console.log(data);
      let jsonfiletem = data;
      let lenthofpint = jsonfiletem["Data"].length;
      ;
      this.option.legend.data = [];
      //this.option.legend.selected=[];
      for (let j = lenthofpint - 1; j >= 0; j--) {
        let lenthofpointdata = jsonfiletem["Data"][j]["PointData"].length;

        let bandsumnow = 0;
        if (jsonfiletem["Data"][j]["OptimizeResult"]["bandsum"]) {
          bandsumnow = jsonfiletem["Data"][j]["OptimizeResult"]["bandsum"];
        } else {
          bandsumnow = 2151;
        }

        for (let k = 0; k < lenthofpointdata; k++) {
          let serilatemp = {
            type: 'line',
            //type: 'custom',
            //  minInterval:0.0000000001,

            symbol: 'none', // 不显示数据点
            smooth: true, // 不使用平滑处理
            //step: 'start' // 设置 step 类型的起始位置
          };
          if (this.Prameter.smooth) {
            serilatemp.smooth = true;
          }
          let temp = [];
          for (let ii = 0; ii < bandsumnow; ii++) {
            if (this.Prameter.Radiance == "Radiance")
              temp.push([ii + 350, jsonfiletem["Data"][j]["PointData"][k][this.Prameter.Radiance][ii] * 1000]);
            if (this.Prameter.Radiance == "DN")
              temp.push([ii + 350, jsonfiletem["Data"][j]["PointData"][k][this.Prameter.Radiance][ii]]);
            //temp.push([ii+350, jsonfiletem["Data"][j]["PointData"][k]["DN"][ii]]);


          }
          serilatemp.data = temp;
          //serilatemp.renderItem=baoluo,
          serilatemp.large = true;
          serilatemp.name = jsonfiletem["Data"][j]["PointData"][k]["PointName"];
          this.option.legend.data.push(jsonfiletem["Data"][j]["PointData"][k]["PointName"]);
          this.option.series.push(serilatemp);


        }


      }
      chart.setOption(this.option);
      var aaa = chart.getOption();
      aaa = {};
    },
    initChart() {
      const chartDom = this.$refs.chart;
      let chart = echarts.init(chartDom, null, {renderer: 'svg'});

      this.option = {

        toolbox: {
          left: 'center',
          itemSize: 25,
          top: 55,
          feature: {
            dataZoom: {},
            restore: {}
          }
        },
        // ECharts 配置选项
        xAxis: {
          type: 'value',
          boundaryGap: false,// 显示连续的刻度
          min: 350,
          max: 2500,
          dataZoom: [
            {
              type: 'inside', // 内置数据区域缩放
              start: 0, // 初始缩放范围的起始位置（0%）
              end: 100 // 初始缩放范围的结束位置（100%）
            }
          ]
        },
        animation: false,
        yAxis: {
          type: 'value',
          // minInterval: 1//只显示整数
          dataZoom: [
            {
              type: 'inside', // 内置数据区域缩放
              start: 0, // 初始缩放范围的起始位置（0%）
              end: 100 // 初始缩放范围的结束位置（100%）
            }
          ]
          //min:0,
        },
        dataZoom: [
          {
            type: 'inside', // 内置数据区域缩放，包括滚轮缩放
            xAxisIndex: [0], // 对应 x 轴
            filterMode: 'none' // 不过滤数据
          },
          {
            type: 'inside', // 内置数据区域缩放，包括滚轮缩放
            yAxisIndex: [0], // 对应 y 轴
            filterMode: 'none' // 不过滤数据
          }
        ],


        legend: {
          data: ['曲线'], // 图例名称
          show: true,// 显示图例
          selectedMode: 'multiple', // 图例的选择模式。默认开启图例开关，可选single，multiple
        },
        series: [
          {
            data: [[1, 150], [2, 230], [3, 224], [4, 218], [5, 135], [6, 147], [7, 260]], // 使用二维数组表示数据点的坐标
            type: 'line',
            //minInterval:0.0000000001,
            symbol: 'none', // 不显示数据点
            smooth: true, // 不使用平滑处理
            //step: 'start' // 设置 step 类型的起始位置
          }
        ]
      };

      chart.setOption(this.option);
            let that = this;
      window.addEventListener('resize', function () {
        that.echartresize();
      });

    },

    getDataURL(chart) {
      // 获取图表数据 URL
      var url = chart.getDataURL({
        type: 'csv'
      });
      // 创建 XMLHttpRequest 对象
      var xhr = new XMLHttpRequest();
      xhr.open('GET', url);
      xhr.setRequestHeader('Content-Type', 'application/csv');
      xhr.onload = function () {
        if (xhr.status === 200) {
          // 下载数据
          exportCSV(chart, 'data.csv', function () {
            return xhr.responseText;
          });
        }
      };
      xhr.send();
    },

    handleKeyDown(event) {
      // 按下 Ctrl 键
      if (event.ctrlKey) {
        this.Prameter.zoomLock = true;
      }
    },
    handleKeyUp(event) {
      // 释放 Ctrl 键
      if (!event.ctrlKey) {
        this.Prameter.zoomLock = false;
      }
    },
    handleClickOutside(event) {
      // 点击图表外部
      if (this.Prameter.zoomLock) {
        this.getDataURL(this.chart);
      }
    } ,
       echartresize(){
            console.log("resize")
      const chartDom = this.$refs.chart;
      let chart = echarts.getInstanceByDom(chartDom);
          
            chart.resize();
            let width=chartDom.clientWidth;
            // if (width<800)
            // {
            //     let option =this.option;
            //     option.grid.left="10%";
            //     chart.setOption(option);
            // }else{
            //     let option =this.option;
            //     option.grid.left="5%";
            //     chart.setOption(option);
            // }
        },





  },


  mounted() {
    this.initChart();
    window.addEventListener('keydown', this.handleKeyDown);
    window.addEventListener('keyup', this.handleKeyUp);
    window.addEventListener('click', this.handleClickOutside);
  },
  beforeUnmount() {
    window.removeEventListener('keydown', this.handleKeyDown);
    window.removeEventListener('keyup', this.handleKeyUp);
    window.removeEventListener('click', this.handleClickOutside);
  },



  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  }
};
function exportCSV(chart, filename, getDataFn) {
  // 获取导出的数据
  var data = getDataFn();
  // 创建 Blob 对象
  var blob = new Blob([data], { type: 'text/csv;charset=utf-8;' });
  // 创建下载链接
  var downloadLink = document.createElement('a');
  downloadLink.setAttribute('download', filename);
  downloadLink.setAttribute('href', URL.createObjectURL(blob));
  downloadLink.style.display = 'none';
  document.body.appendChild(downloadLink);
  // 触发下载链接
  downloadLink.click();
  // 移除下载链接
  document.body.removeChild(downloadLink);
}
function createAndDownloadFile(fileName, content) {
  // 创建一个 a 标签
  var aTag = document.createElement('a');
  // 创建一个 Blob 对象
  var blob = new Blob([content]);
  // 设置下载的文件名
  aTag.download = fileName;
  // 创建一个临时的 URL 指向 Blob 对象
  aTag.href = URL.createObjectURL(blob);
  // 模拟 a 标签的点击事件，触发下载
  aTag.click();
  // 释放创建的临时 URL 资源
  URL.revokeObjectURL(blob);
}


function baoluo(params, api) {
  // console.log(params);
  var xValue = api.value(0);
  var highPoint = api.coord([xValue, api.value(1)]);
  var lowPoint = api.coord([xValue, api.value(2)]);

  return {
    type: 'line',
    shape: {
      x1: 350,
      y1: 10,
      x2: 400,
      y2: 100
    },
    style: api.style({
      stroke: 'rgba(0,255,0,0.2)',
      fill: 'none'
    })
  };
}

</script>

<style scoped>
.chart-container {
  top: 0;
  width: 100%;
  height: 100%;

}

.echartbox {
  width: 95%;
  height: 90%;


}

.plotbutton {
  margin-right: 20px;

}
</style>
