<script>
import SensorMethod from "../SerialPort/SerialportMethod.js";
// import SerialportMethod from "../SerialPort/SerialportMethod.js";
import * as echarts from "echarts";
// import EventBus  from "../../eventBus.js";
// import * as fs from '@tauri-apps/plugin-fs';
// import * as dialog from '@tauri-apps/plugin-dialog'
// // import * as dialog from '@tauri-apps/pulgin-dialog';

// import { invoke } from '@tauri-apps/api/core';
import { dialog, fs } from "@tauri-apps/api";
import { invoke } from "@tauri-apps/api/tauri";

export default {
  name: "SetCalibrate",
  data() {
    return {
      shutter_time_up: 1,
      shutter_time_down: 1,
      sensor_gain_up: 0,
      sensor_gain_down: 0,

      option_up: {},
      option_down: {},
      option_lamp: {},
      Devinfo: {
        work_mode: 0,
      },
      DataUP: { shutter_time: 0, value_lable: 0, gain: 0 },
      DataDown: { shutter_time: 0, value_lable: 0, gain: 0 },
      DataUpList: [],
      DataDownList: [],
      LampData: { value_lable: 0 },
      LampDataDown: { value_lable: 0 },
      caijicishu: [1, 1],
      upGain: { Data: [], shutter_time: 0, sensor_gain: 0 },
      downGain: { Data: [], shutter_time: 0, sensor_gain: 0 },
      upOffset: { Data: [], shutter_time: 0, sensor_gain: 0 },
      downOffset: { Data: [], shutter_time: 0, sensor_gain: 0 },
      fiber_type:"Dual"

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

    // this.initChart();
  },
  methods: {
    addDatatoDatalist(direction) {
      if (direction == "UP") {
        let newdata = JSON.parse(JSON.stringify(this.DataUP));
        if (this.DataUP.shutter_time == 0 || this.DataUP.value_lable == 0) {
          alert("请输入shutter及lampvalue");
          return;
        }
        this.DataUpList.push(newdata);
        this.DataUP.data = [];
        this.option_up.series[0].data = [];

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

      } else if (direction == "DOWN") {
        let newdata = JSON.parse(JSON.stringify(this.DataDown));
        if (this.DataDown.shutter_time == 0 || this.DataDown.value_lable == 0) {
          alert("请输入shutter及lampvalue");
          return;
        }

        this.DataDownList.push(newdata);
        this.DataDown.data = [];

        this.option_down.series[0].data = [];

        var chart_down = echarts.getInstanceByDom(this.$refs.chart_down);
        chart_down.setOption(this.option_down);
      }
      else if (direction == "UPNONE") {
        this.DataUpList = [];
      }
      else if (direction == "DOWNNONE") {
        this.DataDownList = [];
      }
    },
    async loadCalibratefile() {
      let ret = await SensorMethod.Get_Calibrate_Data("./calibratefile/upgain.bin");
      this.upGain.Data = ret.data.data;
      this.upGain.shutter_time = ret.data.shutter_time;
      this.upGain.sensor_gain = ret.data.temprature[0];
      ret = await SensorMethod.Get_Calibrate_Data("./calibratefile/upOffset.bin");
      this.upOffset.Data = ret.data.data;
      this.upOffset.shutter_time = ret.data.shutter_time;
      this.upOffset.sensor_gain = ret.data.temprature[0];



      ret = await SensorMethod.Get_Calibrate_Data("./calibratefile/downgain.bin");
      this.downGain.Data = ret.data.data;
      this.downGain.shutter_time = ret.data.shutter_time;
      this.downGain.sensor_gain = ret.data.temprature[0];
      ret = await SensorMethod.Get_Calibrate_Data("./calibratefile/downOffset.bin");
      this.downOffset.Data = ret.data.data;
      this.downOffset.shutter_time = ret.data.shutter_time;
      this.downOffset.sensor_gain = ret.data.temprature[0];

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

      var options = {
        defaultPath: "../",
        directory: false,
        title: "请选择Lamp file路径",
      }
      var pathofdir = await dialog.open(options);
      var isDual = this.Devinfo.fiber_type == "Dual" ? true : false;
      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.bandsum;
        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 };

        if(isDual){
        coeffweave1 = this.Devinfo.bochangxishu2.a0;
        coeffweave2 = this.Devinfo.bochangxishu2.a1;
        coeffweave3 = this.Devinfo.bochangxishu2.a2;
        coeffweave4 = this.Devinfo.bochangxishu2.a3;
        lenthofdata = this.Devinfo.bandsum;
        let weavetarget2 = [];
        for (var i = 0; i < lenthofdata; i++) {
          var weave = coeffweave1 * i * i * i + coeffweave2 * i * i + coeffweave3 * i + coeffweave4;
          weavetarget2.push(weave);

        }
        let valuetarget2 = await invoke("interpolate_spline_at_points", {
          x: weaveValues,
          y: valueValues,
          xTarget: weavetarget2
        });
        this.LampDataDown = { weave: weavetarget2, value: valuetarget2, 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) {

      if (dire == 0) {
        var ret = await SensorMethod.Dev_Opt(70);

        this.shutter_time_up = ret;
        this.sensor_gain_up = 0;
        let datatoshow=await SensorMethod.Get_Dark_Data("UP",this.shutter_time_up,10);
      } else if (dire == 1) {
        var ret = await SensorMethod.Dev_Opt_Two(70);
        this.shutter_time_down = ret;
        this.sensor_gain_down = 0;
        let datatoshow=await SensorMethod.Get_Dark_Data("UP",this.shutter_time_down,10);
      }


    },

    echartresize() {
      console.log("resize")
      const chartDom = this.$refs.chart;


      let chart_up = echarts.getInstanceByDom(this.$refs.chart_up);

      let chart_lamp = echarts.getInstanceByDom(this.$refs.chart_lamp);
 
      chart_up.resize();


      chart_lamp.resize();
      if(this.Devinfo.fiber_type == "Dual"){
        let chart_down = echarts.getInstanceByDom(this.$refs.chart_down);
        chart_down.resize();
      }
 

    },


    async initChart() {
      this.Devinfo = await SensorMethod.Get_Device_Info();
      this.sensor_gain_down = this.Devinfo.sensor_gain_down;
      if (typeof (this.Devinfo.fiber_type) == "string") {
        this.fiber_type = this.Devinfo.fiber_type;
      }
      if (this.Devinfo.fiber_type == "Single") {
        this.shutter_time_up = this.Devinfo.shutter_time;
      } else if (this.Devinfo.fiber_type == "Dual") {
        this.sensor_gain_up = this.Devinfo.sensor_gain_up;
        this.shutter_time_down = this.Devinfo.shutter_time_down;
        this.shutter_time_up = this.Devinfo.shutter_time_up;
      }
      this.upOffset.Data = [];
      this.downOffset.Data = [];
      for (var i = 0; i < this.Devinfo.bandsum; i++) {
        this.upOffset.Data.push(0);
        this.downOffset.Data.push(0);
      }


      let isDual = this.Devinfo.fiber_type == "Dual" ? true : false;
    
      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;

      const chartDom_up = this.$refs.chart_up;
      let chart_up = echarts.init(chartDom_up, null, { renderer: 'svg' });


      let chart_lamp = echarts.init(this.$refs.chart_lamp, null, { renderer: 'svg' });
      chart_up.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];
      let BandNum = this.Devinfo.bandsum;
      this.option_up.xAxis.min = BandNum * BandNum * BandNum * coeff[0] + BandNum * BandNum * coeff[1] + BandNum * coeff[2] + coeff[3];
      if (this.option_up.xAxis.max < this.option_up.xAxis.min) {
        let temp = this.option_up.xAxis.min;
        this.option_up.xAxis.min = this.option_up.xAxis.max;
        this.option_up.xAxis.max = temp;
      }
      this.option_lamp = JSON.parse(JSON.stringify(this.option_up));


      chart_up.setOption(this.option_up);

      if (isDual) {
        let chart_down = echarts.init(this.$refs.chart_down, null, { renderer: 'svg' });
        chart_down.resize();
        chart_down.setOption(this.option_down);
        this.option_down = JSON.parse(JSON.stringify(this.option_up));
        coeff[0] = this.Devinfo.bochangxishu2.a0;
        coeff[1] = this.Devinfo.bochangxishu2.a1;
        coeff[2] = this.Devinfo.bochangxishu2.a2;
        coeff[3] = this.Devinfo.bochangxishu2.a3;
        this.option_down.xAxis.min = BandNum * BandNum * BandNum * coeff[0] + BandNum * BandNum * coeff[1] + BandNum * coeff[2] + coeff[3];
        this.option_down.xAxis.max = coeff[3];
        if (this.option_down.xAxis.max < this.option_down.xAxis.min) {
          let temp = this.option_down.xAxis.min;
          this.option_down.xAxis.min = this.option_down.xAxis.max;
          this.option_down.xAxis.max = temp;
        }
      }
      this.option_lamp.legend.data = ['Lamp'];
      this.option_lamp.series[0].name = 'Lamp';
      chart_lamp.setOption(this.option_lamp);
      
      let that = this;
      window.addEventListener('resize', function () {
        that.echartresize();
      });

    },
    async Get_Data_direction(dire) {

      if (dire == "UP") {
        let coeffweave1 = this.Devinfo.bochangxishu.a0;
        let coeffweave2 = this.Devinfo.bochangxishu.a1;
        let coeffweave3 = this.Devinfo.bochangxishu.a2;
        let coeffweave4 = this.Devinfo.bochangxishu.a3;
        await SensorMethod.Set_Gain(this.sensor_gain_up);
        var data = await SensorMethod.Get_Date_on_Derction(dire, this.shutter_time_up, true, Number(this.caijicishu[0]))
        let lastvalue = this.DataUP.value_lable;
        this.DataUP = data;
        this.DataUP.gain = this.DataUP.temprature[0];
        this.DataUP.value_lable = lastvalue
        //获取波长系数
        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") {
        let coeffweave1 = this.Devinfo.bochangxishu2.a0;
        let coeffweave2 = this.Devinfo.bochangxishu2.a1;
        let coeffweave3 = this.Devinfo.bochangxishu2.a2;
        let coeffweave4 = this.Devinfo.bochangxishu2.a3;
        await SensorMethod.Set_Gain(this.sensor_gain_down);
        var data = await SensorMethod.Get_Date_on_Derction(dire, this.shutter_time_down, true, Number(this.caijicishu[1]))
        let lastvalue = this.DataDown.value_lable;
        this.DataDown = data;
        this.DataDown.gain = this.DataDown.temprature[0];
        this.DataDown.value_lable = lastvalue
        //获取波长系数
        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;
        let sensor_gain = this.DataUP.temprature[0];
        let gain_sensor_gain = this.upGain.sensor_gain;
        let cali_offset = this.upOffset.Data;
        //db to gain
        let sensor_gain_ndb = 10 ** (sensor_gain / 20);
        let gain_sensor_gain_ndb = 10 ** (gain_sensor_gain / 20);
        let gainscale = gain_sensor_gain_ndb / sensor_gain_ndb;
        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;
            let a = this.DataUP.data[i];
            let b = this.upGain.Data[i];
            let c = this.upGain.shutter_time;
            let d = this.DataUP.shutter_time;
            let e = gainscale;
            let f = cali_offset[i];
            var data = this.DataUP.data[i] * this.upGain.shutter_time / this.DataUP.shutter_time * gainscale * this.upGain.Data[i] + cali_offset[i];
            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 && this.Devinfo.fiber_type == "Dual") {
        let coeffweave1 = this.Devinfo.bochangxishu2.a0;
        let coeffweave2 = this.Devinfo.bochangxishu2.a1;
        let coeffweave3 = this.Devinfo.bochangxishu2.a2;
        let coeffweave4 = this.Devinfo.bochangxishu2.a3;
        let sensor_gain = this.DataDown.temprature[0];
        let gain_sensor_gain = this.downGain.sensor_gain;
        //db to gain
        let sensor_gain_ndb = 10 ** (sensor_gain / 20);
        let gain_sensor_gain_ndb = 10 ** (gain_sensor_gain / 20);
        let gainscale = gain_sensor_gain_ndb / sensor_gain_ndb;
        let cali_offset = this.downOffset.Data;
        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;
            // let a=this.DataDown.data[i] ;
            // let b=this.downGain.Data[i] ;
            // let c=this.downGain.shutter_time;
            // let d=this.DataDown.shutter_time;
            // let e=gainscale;
            // let f=cali_offset[i];
            var data = this.DataDown.data[i] * this.downGain.Data[i] * this.downGain.shutter_time / this.DataDown.shutter_time * gainscale + cali_offset[i];
            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() {
      let basename=this.Devinfo.name+"_"+this.Devinfo.serialnumber+"_";
      var isDual = this.Devinfo.fiber_type == "Dual" ? true : false;
      if (this.upGain.shutter_time != 0) {
        console.log(this.upGain.Data);
        let data = {
          gain: this.upGain.Data,
          shutter: this.upGain.shutter_time,
          sensorGain: Number(this.upGain.sensor_gain),
          direction: true,
          filepath: "./calibratefile/"+basename+"upgain.bin"
        }
        await invoke("savecalibratefile", data);

      } else {

      }

      if (this.upOffset.shutter_time != 0) {
        console.log(this.upOffset.Data);
        let data = {
          gain: this.upOffset.Data,
          shutter: this.upOffset.shutter_time,
          sensorGain: Number(this.upOffset.sensor_gain),
          direction: true,
          filepath: "./calibratefile/"+basename+"upOffset.bin"
        }
        await invoke("savecalibratefile", data);

      } else {
        await invoke("delete_file_by_path", { filepath: "./calibratefile/"+basename+"upOffset.bin" });
      }


      if (this.downGain.shutter_time != 0 && isDual) {
        await invoke("savecalibratefile", {
          gain: this.downGain.Data,
          shutter: this.downGain.shutter_time,
          sensorGain: Number(this.downGain.sensor_gain),
          direction: true,
          filepath: "./calibratefile/"+basename+"downgain.bin"
        });

      }
      if (this.downOffset.shutter_time != 0 && isDual) {
        await invoke("savecalibratefile", {
          gain: this.downOffset.Data,
          shutter: this.downOffset.shutter_time,
          sensorGain: Number(this.downOffset.sensor_gain),
          direction: true,
          filepath: "./calibratefile/"+basename+"downOffset.bin"
        });

      } else {
        await invoke("delete_file_by_path", { filepath: "./calibratefile/"+basename+"downOffset.bin" });
      }

    },
    async Compute_Coeff_bytwo() {
      let lampData = this.LampData.value;
      let lampdatadown = this.LampDataDown.value;
      let lampLabel = this.LampData.value_lable;
      let UpData1 = this.DataUpList[0].data;
      let UpData2 = this.DataUpList[1].data;
      let UpLabel1 = this.DataUpList[0].value_lable;
      let UpLabel2 = this.DataUpList[1].value_lable;
      let UpShutter = this.DataUpList[0].shutter_time;
      let DownData1 = this.DataDownList[0].data;
      let DownData2 = this.DataDownList[1].data;
      let DownLabel1 = this.DataDownList[0].value_lable;
      let DownLabel2 = this.DataDownList[1].value_lable;
      let DownShutter = this.DataDownList[0].shutter_time;
      let gainofup = [];
      let offsetofup = [];
      let gainofdown = [];
      let offsetofdown = [];
      for (var i = 0; i < UpData1.length; i++) {
        let upDn1 = UpData1[i];
        let upDn2 = UpData2[i];
        let downDn1 = DownData1[i];
        let downDn2 = DownData2[i];
        let lampup1 = lampData[i] * UpLabel1 / lampLabel;
        let lampup2 = lampData[i] * UpLabel2 / lampLabel;
        let lampdown1 = lampdatadown[i] * DownLabel1 / lampLabel;
        let lampdown2 = lampdatadown[i] * DownLabel2 / lampLabel;
        let gainup = (lampup2 - lampup1) / (upDn2 - upDn1);
        if (upDn2 - upDn1 == 0) {
          if (i == 0) {
            gainup = 1;
          } else {
            gainup = gainofup[i - 1];
          }
        }




        let offsetup = lampup1 - gainup * upDn1;
        let gaindown = (lampdown2 - lampdown1) / (downDn2 - downDn1);
        if (downDn2 - downDn1 == 0) {
          if (i == 0) {
            gaindown = 1;
          } else {
            gaindown = gainofdown[i - 1];
          }
        }


        let offsetdown = lampdown1 - gaindown * downDn1;
        gainofup.push(gainup);
        offsetofup.push(offsetup);
        gainofdown.push(gaindown);
        offsetofdown.push(offsetdown);
      }
      this.upGain.sensor_gain = this.DataUpList[0].temprature[0];
      this.upGain.Data = gainofup;
      this.upGain.shutter_time = UpShutter;
      this.upOffset.sensor_gain = this.DataUpList[0].temprature[0];
      this.upOffset.Data = offsetofup;
      this.upOffset.shutter_time = UpShutter;
      this.downGain.sensor_gain = this.DataDownList[0].temprature[0];
      this.downGain.Data = gainofdown;
      this.downGain.shutter_time = DownShutter;
      this.downOffset.sensor_gain = this.DataDownList[0].temprature[0];
      this.downOffset.Data = offsetofdown;
      this.downOffset.shutter_time = DownShutter;
      this.computCalibrate()
      this.SaveGaindata();





    },
    async compute_coeff_byone() {
      var isDual = this.Devinfo.fiber_type == "Dual" ? true : false;
      let lampData = this.LampData.value;
      let lampdatadown = this.LampDataDown.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 ( UpShutter == 0) {
        alert("请先采集数据");
        return;
      }

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



      let gainofup = [];
      for (var i = 0; i < UpData.length; i++) {
        let upDn = UpData[i];
        let lampup = lampData[i] * UpLabel / lampLabel;
        let gainup = lampup / upDn;
        if (upDn == 0) {
          if (i == 0) {
            gainup = 1;
          } else {
            gainup = gainofup[i - 1];
          }
        }
        gainofup.push(gainup);
      }

      this.upGain.sensor_gain = this.DataUP.gain;

      this.upGain.Data = gainofup;
      this.upGain.shutter_time = UpShutter;



      if(isDual){
        let gainofdown = [];
      for (var i = 0; i < UpData.length; i++) {
      
        let downDn = DownData[i];
       
        let lampdown = lampdatadown[i] * DownLabel / lampLabel;

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


        
        gainofdown.push(gaindown);
      }

      this.downGain.sensor_gain = this.DataDown.gain;
      this.downGain.Data = gainofdown;
      this.downGain.shutter_time = DownShutter;
      }
      
      this.computCalibrate()
      this.SaveGaindata();
    },


    async Start_Comput_Coeff() {
      if (this.DataUpList.length == 0 || this.DataDownList.length == 0) {
        alert("采取单数据计算");
        this.compute_coeff_byone();
        return;
      }
      this.Compute_Coeff_bytwo();


    }
  }



}










</script>

<template>
  <div class="container" style="width: 100%;height: 94%;max-width:100%;margin: 0px;padding: 0px">
    <div class="row linebox" :style="fiber_type == 'Dual' ? 'height:33%' : 'height: 50%'">
      <!--      按钮区域-->
      <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" :style="fiber_type == 'Dual' ? 'height:33%' : 'height: 50%'">

      <!--      按钮区域-->
      <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)"
              :disabled="DataUpList.length != 0">OPT</b-button>
          </b-input-group-prepend>
          <b-form-input v-model="shutter_time_up" :disabled="DataUpList.length != 0"></b-form-input>


        </b-input-group>
        <b-input-group prepend="Gain">

          <b-form-input v-model="sensor_gain_up" step="0.002" :disabled="DataUpList.length != 0"></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>
        <b-input-group prepend="Lamp_Value" size="sm">
          <b-form-input v-model="DataUP.value_lable"></b-form-input>
        </b-input-group>

        <!-- <b-input-group prepend="Gain" size="sm"  v-show="upGain.shutter_time!==0">
        </b-input-group>
          <b-form-input v-model="upGain.gain"></b-form-input> -->

      </div>
      <!--      ///中间区域-->
      <div class="col-9 centerme">
        <div class="chart-container" id="charmian_up" ref="chart_up"></div>
      </div>
      <!--      ///尾部区域-->
      <div class="col-1 tailme" style="position: relative;height: 100%;">

        <b-button variant="secondary" style="position: relative;margin: auto;"
          @click="addDatatoDatalist('UP')">加入列表</b-button>

        <a-row v-for="data in DataUpList" :key="data.index">
          <a-col :span="12">{{ data.shutter_time }}</a-col>
          <a-col :span="12">{{ data.value_lable }}</a-col>
        </a-row>
        <b-button variant="secondary" style="position: absolute;margin: auto;bottom: 0%;left: 8%;"
          @click="addDatatoDatalist('UPNONE')">清空列表</b-button>

        <!-- <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" v-if="fiber_type=='Dual'" style="height: 33%">
      <!--      按钮区域-->
      <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)"
              :disabled="DataDownList.length != 0">OPT</b-button>
          </b-input-group-prepend>
          <b-form-input v-model="shutter_time_down" :disabled="DataDownList.length != 0"></b-form-input>


        </b-input-group>
        <b-input-group prepend="Gain">

          <b-form-input v-model="sensor_gain_down" :disabled="DataDownList.length != 0"></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>
        <b-input-group prepend="Lamp_Value" size="sm">
          <b-form-input v-model="DataDown.value_lable"></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" style="position: relative;height: 100%;">
        <!-- <b-form-floating-label style="margin: auto" v-show="DataDown.shutter_time!==0">Shutter_Time:{{DataDown.shutter_time}}</b-form-floating-label> -->




        <b-button variant="secondary" style="position: relative;margin: auto;"
          @click="addDatatoDatalist('DOWN')">加入列表</b-button>

        <a-row v-for="data in DataDownList" :key="data.index">
          <a-col :span="12">{{ data.shutter_time }}</a-col>
          <a-col :span="12">{{ data.value_lable }}</a-col>
        </a-row>
        <b-button variant="secondary" style="position: absolute;margin: auto;bottom: 0%;left: 8%;"
          @click="addDatatoDatalist('DOWNNONE')">清空列表</b-button>

      </div>
    </div>



  </div>
  <p style="position:absolute ;bottom: 10px;width: 100%;height: 30px">
    <b-button @click="loadCalibratefile" 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%;

  margin: 0px;
  padding: 0px;
  border-bottom: 1px solid #d2dede;

}

.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>
