<script>

import SerialportMethod from "../SerialPort/SerialportMethod.js";
import * as echarts from "echarts";
import EventBus  from "../../eventBus.js";
import {dialog, fs} from "@tauri-apps/api";
import {invoke} from "@tauri-apps/api/tauri";
import SerilporDefine from "../serportdefine.js";
export default {
  name: "SetCalibrate",
  data(){
    return {
      shutter_time_up:1,
      shutter_time_down:1,
      option_up:{},
      option_down:{},
      option_lamp:{},
      Devinfo:{
        work_mode:0,
      },
      DataUP:{shutter_time:0,value_lable:0},
      DataDown:{shutter_time:0,value_lable:0},
      LampData:{value_lable:0},
      caijicishu:[1,1],
      upGain:{gain:[],shutter_time:0},
      downGain:{gain:[],shutter_time:0},


    }
  },
  mounted() {
    //100ms 后执行
    setTimeout(() => {
      this.initChart();
    }, 100);
    // setTimeout(() => {
    //   this.readFileAndParse()
    // }, 1000);

   // this.initChart();
  },
  methods: {

    updateCalifile(){
      let aa=invoke("sendcalibratetodev",{
        gain:this.upGain.gain,
        shutter:this.upGain.shutter_time,
        direction:SerilporDefine.Derection.Up
      });
      console.log(aa);
      let aa1=invoke("sendcalibratetodev",{
        gain:this.downGain.gain,
        shutter:this.downGain.shutter_time,
        direction:SerilporDefine.Derection.Down
      });
      console.log(aa1);
    },
    async  readFileAndParse() {

      var options= {
        defaultPath: "../",
        directory: false,
        title: "请选择保存路径",
      }
      var pathofdir=await dialog.open(options);

      try {
        // 读取文件内容
        const data = await fs.readTextFile(pathofdir);

        // 解析文件内容
        const lines = data.split('\n');
        const valueLine = lines.shift();  // 读取第一行
        const [key, value] = valueLine.split('=');  // 解析第一行内容
        const valueVar = parseFloat(value);  // 将 value 转换为数字

        const weaveValues = [];
        const valueValues = [];

        // 解析剩余行的内容
        for (const line of lines) {
          if (line.trim() !== '') {  // 排除空行
            const [weave, val] = line.split(' ').map(Number);  // 将每一行的两个值转换为数字
            weaveValues.push(weave*1000);
            valueValues.push(val);
          }
        }
        let coeffweave1=this.Devinfo.bochangxishu.a0;
        let coeffweave2=this.Devinfo.bochangxishu.a1;
        let coeffweave3=this.Devinfo.bochangxishu.a2;
        let coeffweave4=this.Devinfo.bochangxishu.a3;
        let lenthofdata=this.Devinfo.bandnum;
        let weavetarget=[];
        for (var i=0;i<lenthofdata;i++)
        {
          var weave=coeffweave1*i*i*i+coeffweave2*i*i+coeffweave3*i+coeffweave4;
          weavetarget.push(weave);

        }
       let valuetarget= await invoke("interpolate_spline_at_points",{
          x:weaveValues,
          y:valueValues,
         xTarget:weavetarget
        });
       // console.log(valuetarget);
        this.LampData={weave:weavetarget,value:valuetarget,value_lable:valueVar};
        var dataforshow=[];
        for (var i=0;i<lenthofdata;i++)
        {
          dataforshow.push([weavetarget[i],valuetarget[i]]);
        }
        var char_lamp=echarts.getInstanceByDom(this.$refs.chart_lamp);
        this.option_lamp.series[0].data=dataforshow;
        char_lamp.setOption(this.option_lamp);






      } catch (err) {
        console.error('Error reading file:', err);
      }
    },
    async OPT_devic(dire) {
      var shuttertime = await SerialportMethod.Dev_Opt();
      if (dire == 0) this.shutter_time_up = shuttertime;
      else this.shutter_time_down = shuttertime;

    },
    async initChart() {
      this.Devinfo= await SerialportMethod.Get_Device_Info();
      var coeff=[];
      coeff[0]=this.Devinfo.bochangxishu.a0;
      coeff[1]=this.Devinfo.bochangxishu.a1;
      coeff[2]=this.Devinfo.bochangxishu.a2;
      coeff[3]=this.Devinfo.bochangxishu.a3;
      let bandnum=this.Devinfo.bandnum;
      const chartDom_up = this.$refs.chart_up;
      let chart_up = echarts.init(chartDom_up, null, {renderer: 'svg'});
      let chart_down = echarts.init(this.$refs.chart_down, null, {renderer: 'svg'});
      let chart_lamp = echarts.init(this.$refs.chart_lamp, null, {renderer: 'svg'});
      chart_up.resize();
      chart_down.resize();
      chart_lamp.resize();
      this.option_up = {


        // ECharts 配置选项
        xAxis: {
          type: 'value',
          boundaryGap: false,// 显示连续的刻度
          min: 0,
          max: 1100,
          dataZoom: [
            {
              type: 'inside', // 内置数据区域缩放
              start: 0, // 初始缩放范围的起始位置（0%）
              end: 100 // 初始缩放范围的结束位置（100%）
            }
          ],
          triggerEvent: true
        },
        animation: false,
        yAxis:[ {
          type: 'value',
          //min:0,
        },
          {
            type: 'value',
            //min:0,
          }


      ],
        tooltip: {
          trigger: 'axis',


        },
        axisPointer: {
          link: {xAxisIndex: 'all'},
          label: {
            backgroundColor: '#777'
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '10%',
          top: '5%'
        },
        // visualMap: [
        //     {
        //         type: 'continuous',
        //     }
        // ],
        dataZoom: [
          {
            type: 'inside', // 内置数据区域缩放，包括滚轮缩放
            xAxisIndex: [0], // 对应 x 轴
            filterMode: 'none' // 不过滤数据

          },
          {
            type: 'inside', // 内置数据区域缩放，包括滚轮缩放
            yAxisIndex: [0], // 对应 y 轴
            filterMode: 'none', // 不过滤数据
            //width :15

          }
        ],


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




      this.option_up.xAxis.max =coeff[3];
      bandnum=bandnum-1;
      this.option_up.xAxis.min = bandnum*bandnum*bandnum*coeff[0]+bandnum*bandnum*coeff[1]+bandnum*coeff[2]+coeff[3];
      this.option_lamp =  JSON.parse(JSON.stringify(this.option_up));
      this.option_down = JSON.parse(JSON.stringify(this.option_up));

      chart_up.setOption(this.option_up);
      chart_down.setOption(this.option_down);
      this.option_lamp.legend.data = ['Lamp'];
      this.option_lamp.series[0].name = 'Lamp';
      chart_lamp.setOption(this.option_lamp);


    },
    async Get_Data_direction(dire) {
      let coeffweave1=this.Devinfo.bochangxishu.a0;
      let coeffweave2=this.Devinfo.bochangxishu.a1;
      let coeffweave3=this.Devinfo.bochangxishu.a2;
      let coeffweave4=this.Devinfo.bochangxishu.a3;
      if (dire == "UP") {
        var data = await SerialportMethod.Get_Date_on_Derction(dire,this.shutter_time_up,true,Number(this.caijicishu[0]))
        this.DataUP=data;
        this.DataUP.value_lable=0
        //获取波长系数
        var lenthofdata=data.data.length;
        let dataforshow=[];
        for (var i=0;i<lenthofdata;i++)
        {
          var weave=coeffweave1*i*i*i+coeffweave2*i*i+coeffweave3*i+coeffweave4;
          dataforshow.push([weave,data.data[i]]);
        }
        this.option_up.series[0].data = dataforshow;

        var chart_up = echarts.getInstanceByDom(this.$refs.chart_up);
        chart_up.setOption(this.option_up);

       // console.log(dataforshow);
      }else if(dire=="DOWN")
      {
        var data = await SerialportMethod.Get_Date_on_Derction(dire,this.shutter_time_down,true,Number(this.caijicishu[0]))
        this.DataDown=data;
        this.DataDown.value_lable=0
        //获取波长系数
        var lenthofdata=data.data.length;
        let dataforshow=[];
        for (var i=0;i<lenthofdata;i++)
        {
          var weave=coeffweave1*i*i*i+coeffweave2*i*i+coeffweave3*i+coeffweave4;
          dataforshow.push([weave,data.data[i]]);
        }
        this.option_down.series[0].data = dataforshow;

        var chart_down = echarts.getInstanceByDom(this.$refs.chart_down);
        chart_down.setOption(this.option_down);

       // console.log(dataforshow);
      }
      this.computCalibrate()
    },
    async computCalibrate(){

      if(this.upGain.shutter_time!=0)
      {
        let coeffweave1=this.Devinfo.bochangxishu.a0;
      let coeffweave2=this.Devinfo.bochangxishu.a1;
      let coeffweave3=this.Devinfo.bochangxishu.a2;
      let coeffweave4=this.Devinfo.bochangxishu.a3;
        var uprandiance=[];
        if(this.DataUP.data.length!=0)
        {
          for (var i=0;i<this.DataUP.data.length;i++)
          {
            var weave=coeffweave1*i*i*i+coeffweave2*i*i+coeffweave3*i+coeffweave4;
            var data=this.DataUP.data[i]*this.upGain.gain[i]*this.upGain.shutter_time/this.DataUP.shutter_time;
            uprandiance.push([weave,data]);
          }
          var series=
           {
            data: [[1, 150], [2, 230], [3, 224], [4, 218], [5, 135], [6, 147], [7, 260]], // 使用二维数组表示数据点的坐标
            type: 'line',
            name: 'Radiance',
            symbol: 'none', // 不显示数据点
            smooth: false, // 不使用平滑处理
                  yAxisIndex: 1,
            // step: 'start' // 设置 step 类型的起始位置
          }
          series.data=uprandiance;
          if(this.option_up.series.length==1)
          {
            this.option_up.series.push(series);
            this.option_up.legend.data.push('Radiance');
          }else{
            this.option_up.series[1]=series;
          }
          var chart_up = echarts.getInstanceByDom(this.$refs.chart_up);
          chart_up.setOption(this.option_up);
         //this.option_up.series
        }
      }
      if(this.downGain.shutter_time!=0)
      {
        let coeffweave1=this.Devinfo.bochangxishu.a0;
      let coeffweave2=this.Devinfo.bochangxishu.a1;
      let coeffweave3=this.Devinfo.bochangxishu.a2;
      let coeffweave4=this.Devinfo.bochangxishu.a3;
        var downrandiance=[];
        if(this.DataDown.data.length!=0)
        {
          for (var i=0;i<this.DataDown.data.length;i++)
          {
            var weave=coeffweave1*i*i*i+coeffweave2*i*i+coeffweave3*i+coeffweave4;
            var data=this.DataDown.data[i]*this.downGain.gain[i]*this.upGain.shutter_time/this.DataDown.shutter_time;
            downrandiance.push([weave,data]);
          }
          var series=
           {
            data: [[1, 150], [2, 230], [3, 224], [4, 218], [5, 135], [6, 147], [7, 260]], // 使用二维数组表示数据点的坐标
            type: 'line',
            name: 'Radiance',
            symbol: 'none', // 不显示数据点
            smooth: false, // 不使用平滑处理
                  yAxisIndex: 1,
            // step: 'start' // 设置 step 类型的起始位置
          }
          series.data=downrandiance;
          if(this.option_down.series.length==1)
          {
            this.option_down.series.push(series);
            this.option_down.legend.data.push('Radiance');
          }else{
            this.option_down.series[1]=series;
          }
          var chart_down = echarts.getInstanceByDom(this.$refs.chart_down);
          chart_down.setOption(this.option_down);
         //this.option_up.series
        }
      }



    },

    async SaveGaindata(){
      if(this.upGain.shutter_time!=0)
      {
        console.log(this.upGain.gain);
        let data={
          gain:this.upGain.gain,
          shutter:this.upGain.shutter_time,
          direction:true,
          filepath:"./calibratefile/upgain.bin"
        }
       await invoke("savecalibratefile",data);
        // await invoke("sendcalibratetodev",{
        //   gain:this.upGain.gain,
        //   shutter:this.upGain.shutter_time,
        //   direction:true
         
        // });
      }

      if(this.downGain.shutter_time!=0)
      {
        await invoke("savecalibratefile",{
          gain:this.downGain.gain,
          shutter:this.downGain.shutter_time,
          direction:true,
          filepath:"./calibratefile/downgain.bin"
        });

      }

    },
    async Start_Comput_Coeff(){
      let lampData=this.LampData.value;
      let lampLabel=this.LampData.value_lable;
      let UpData=this.DataUP.data;
      let UpLabel=this.DataUP.value_lable;
      let UpShutter=this.DataUP.shutter_time;
      let DownData=this.DataDown.data;
      let DownLabel=this.DataDown.value_lable;
      let DownShutter=this.DataDown.shutter_time;
      if (lampLabel==0)
      {
        alert("请先导入灯数据");
        return;
      }

      if (DownShutter==0||UpShutter==0)
      {
        alert("请先采集数据");
        return;
      }
      if (UpLabel==0||DownLabel==0)
      {
        alert("请填写对应的Value");
        return;
      }

      let gainofup=[];
      let gainofdown=[];
      for (var i=0;i<UpData.length;i++)
      {
       let upDn=UpData[i];
       let downDn=DownData[i];
       let lampup=lampData[i]*UpLabel/lampLabel;
       let lampdown=lampData[i]*DownLabel/lampLabel;
       let gainup=lampup/upDn;
        //判断upDN是否为0 如果是0 则gainup为前一个值 如果是第一个 则为1

        if (upDn==0)
        {
          if (i==0)
          {
            gainup=1;
          }else{
            gainup=gainofup[i-1];
          }
        }


     
       let gaindown=lampdown/downDn;
        //判断downDn是否为0 如果是0 则gainup为前一个值 如果是第一个 则为1
        if (downDn==0)
        {
          if (i==0)
          {
            gaindown=1;
          }else{
            gaindown=gainofdown[i-1];
          }
        }
        

        gainofup.push(gainup);
        gainofdown.push(gaindown);
      }
      this.upGain.gain=gainofup;
      this.upGain.shutter_time=UpShutter;
      this.downGain.gain=gainofdown;
      this.downGain.shutter_time=DownShutter;
      this.computCalibrate()
      this.SaveGaindata();

    }
  }



}










</script>

<template>
  <div class="container" style="width: 100%;height: 100%;max-width:100%;margin: 0px;padding: 0px">
    <div class="row linebox">
<!--      按钮区域-->
      <div class="col-2 buttonme">
        <b-button variant="secondary" pill class="siglebt" @click="readFileAndParse()">导入灯数据</b-button>
      </div>
<!--      ///中间区域-->
      <div class="col-9 centerme">
        <div class="chart-container" id="charmian_lamp" ref="chart_lamp" ></div>
      </div>
<!--      ///尾部区域-->
      <div class="col-1 tailme">
        <b-form-floating-label style="margin: auto" v-show="LampData.value_lable!==0">value:{{LampData.value_lable}}</b-form-floating-label>
      </div>
    </div>
<!--      中建行      -->
    <div class="row linebox">

      <!--      按钮区域-->
      <div class="col-2 buttonme" style="padding: 0px" size="sm">
        <b-input-group append="ms">
          <b-input-group-prepend>
          <b-button variant="secondary" style="margin: auto" @click="OPT_devic(0)">OPT</b-button>
          </b-input-group-prepend>
          <b-form-input v-model="shutter_time_up"></b-form-input>


        </b-input-group>
        <b-input-group append="次">
          <b-input-group-prepend>
            <b-button variant="secondary" style="margin: auto" @click="Get_Data_direction('UP')">采集向上数据</b-button>
          </b-input-group-prepend>
          <b-form-input v-model="caijicishu[0]"></b-form-input>
        </b-input-group>

      </div>
      <!--      ///中间区域-->
      <div class="col-9 centerme">
        <div class="chart-container" id="charmian_up" ref="chart_up" ></div>
      </div>
      <!--      ///尾部区域-->
      <div class="col-1 tailme">
        <b-form-floating-label style="margin: auto" v-show="DataUP.shutter_time!==0">Shutter_Time:{{DataUP.shutter_time}}</b-form-floating-label>
        <b-input-group prepend="Lamp_Value" size="sm"  v-show="DataUP.shutter_time!==0">
        </b-input-group>
          <b-form-input v-model="DataUP.value_lable"></b-form-input>


      </div>
    </div>
<!--    向下               -->
    <div class="row linebox">
      <!--      按钮区域-->
      <div class="col-2 buttonme">
        <b-input-group append="ms">
          <b-input-group-prepend>
            <b-button variant="secondary" style="margin: auto" @click="OPT_devic(1)"> OPT</b-button>
          </b-input-group-prepend>
          <b-form-input v-model="shutter_time_down"></b-form-input>


        </b-input-group>
        <b-input-group append="次">
          <b-input-group-prepend>
            <b-button variant="secondary"  @click="Get_Data_direction('DOWN')">采集向下数据</b-button>
          </b-input-group-prepend>
          <b-form-input v-model="caijicishu[1]"></b-form-input>
        </b-input-group>

      </div>
      <!--      ///中间区域-->
      <div class="col-9 centerme">
        <div class="chart-container" id="charmian_up" ref="chart_down" ></div>
      </div>
      <!--      ///尾部区域-->
      <div class="col-1 tailme">
        <b-form-floating-label style="margin: auto" v-show="DataDown.shutter_time!==0">Shutter_Time:{{DataDown.shutter_time}}</b-form-floating-label>
        <b-input-group prepend="Lamp_Value" size="sm"  v-show="DataDown.shutter_time!==0">
        </b-input-group>
          <b-form-input v-model="DataDown.value_lable"></b-form-input>

      </div>
    </div>



  </div>
  <p style="position:absolute ;bottom: 10px;width: 100%;height: 30px" >
    <b-button @click="updataName" style="position:absolute;left: 20px ">导入已有文件</b-button>
    <b-button @click="Start_Comput_Coeff()" style="position:absolute; left: 150px ">计算</b-button>
    <b style="position:absolute; left: 250px;border: #0f0f0f 1px solid; margin: auto">adsfsdsadfsdf</b>
    <b-button @click="updateCalifile" style="position:absolute;right: 20px ">设置</b-button>
  </p>
</template>

<style scoped>
.linebox{
  width: 100%;
  height: 30%;
  margin: 0px;
  padding: 0px;
  border-bottom:1px solid #d2dede;
  max-width: 100%;
}

.buttonme{
  background-color: #f8f9fa;
  padding-top: 0px;
  padding-bottom: 0px;
  padding: 0px;
  border-right: 1px solid #d2dede;
  align-content: center;

}
.centerme{

  padding-top: 0px;
  padding-bottom: 0px;
  padding: 0px;
  border-right: 1px solid #d2dede;
}
.tailme{
  background-color: #f8f9fa;
  margin: auto;

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

</style>
