<template>
  <div class="w-h-full">
    <v-chart :option="option" />
  </div>
</template>

<script lang="ts" setup>
import { reactive } from "vue"
import { use, graphic } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { BarChart } from "echarts/charts";
import { TitleComponent, GridComponent } from "echarts/components";
import VChart from "vue-echarts";
import { get_in_positioning_id } from '../api/util'


use([
  CanvasRenderer,
  BarChart,
  TitleComponent,
  GridComponent
]);

const props = defineProps({
  title: String,
  color: String
})

const BAR_COUNT			   		 = 30
const UN_POSITIONING_COLOR = '#9ca3af'
const IN_POSITIONING_COLOR = new graphic.LinearGradient(
  0, 1, 0, 0,
  [
    {offset: 0.3, color: '#83bff6'},
    {offset: 1,   color: '#188df0'}
  ]
)

const option 			 = reactive({
  title: {
    text: props.title,
    left: 'center',
    textStyle: {
      color: 'white'
    }
  },
  xAxis: {
    type: 'category',
    axisTick: {show: false},
    axisLine: {show: false},
  },
  yAxis: {
    show: false,
    max: 60
  },
  series: [{
    type: 'bar',
    barCategoryGap: '50%',
    label: {
      show: true,
      position: 'top',
      formatter: function ({ value }) {
        return !value || value[1] === 0 ? '' : value[1];
      }
    },
    itemStyle: {
      color: props.color
    },
  }]
})
const update 			 = (GSVArr: Array<any>, GSAArr: Array<any>) => {
  const SNROption: any = getSNROption(GSVArr, GSAArr)
  if (!SNROption) return
  
  if (SNROption.xAxis.data.length !== SNROption.series[0].data.length) {
    return
  }
  
  const length = SNROption.xAxis.data.length
  if (length < BAR_COUNT) {
    const fill_num 			 		 = BAR_COUNT - length
    SNROption.xAxis.data 		 = SNROption.xAxis.data.concat(new Array(fill_num).fill(''))
    SNROption.series[0].data = SNROption.series[0].data.concat(new Array(fill_num).fill(0))
  }
  
  Object.assign(option, SNROption)
}
const getSNROption = (GSVArr: Array<any>, GSAArr: Array<any>) => {
  try {
    let xAxis_data  : Array<any> = []
    let series_data : Array<any> = []
    const in_positioning_id = get_in_positioning_id(GSAArr)
    
    GSAArr.forEach(({ satellites }) => {
      in_positioning_id.push(...satellites)
    });

    GSVArr.forEach(({ satellites }) => {
      satellites.forEach(({ id, SNRdB }) => {
        xAxis_data.push(id)
        if (in_positioning_id.indexOf(parseInt(id)) < 0) {
          series_data.push([id, SNRdB, false])
        } else {
          series_data.push([id, SNRdB, true])
        }
      });
    });
    
    const SNROption = {
      xAxis: {
        data: xAxis_data
      },
      series: [{
        data: series_data
      }]
    }

    return SNROption
  } catch (error) {
    console.error(error);
  }
}

defineExpose({ update })
</script>