<script setup lang="ts">
import {onMounted, type Ref, ref, watch} from "vue";
import * as echarts from 'echarts';
import {inject} from "vue-demi";
import useApis from "@/apis";
import type {EChartsType} from "echarts";
import {ElMessage} from "element-plus";
const props = defineProps<{
  assignmentId:number,
  splitNumber:number,
  barWidth:number,
}>()
const apis = useApis();
const pauseData:any[] = [];
let chartData:any[] = [];

let noData = ref(false)


const limit = {
  max:0,
  min:0
}
function formatTimeWithMilliseconds(stamp:number ){
  const date = new Date(stamp);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  const milliseconds = date.getMilliseconds().toString().padStart(3, '0');
  return `${hours}:${minutes}:${seconds}`;
}

const currentEngagement = inject('currentEngagement') as Ref<any>;
watch(currentEngagement,()=>{
  noData.value = false
  setTimeout(()=>{
    let chartDom = document.getElementById('pause-canvas');
    if (!chartDom)return;
    let myChart = echarts.getInstanceByDom(chartDom);
    if (!myChart){
      myChart = echarts.init(chartDom);
    }
    getCanvasData(myChart);
  },0)

});

const maxPauseTime = inject('maxPauseTime') as Ref<number>;
const loadingStatus = inject('loadingStatus') as Ref<{
  edit:boolean,
  pause:boolean,
  process:boolean,
  total:boolean
}>;
function getCanvasData(chart:EChartsType){
  if (!currentEngagement.value){
    return;
  }
  let studentId = currentEngagement.value.studentId;
  let assignmentId = currentEngagement.value.assignmentId;
  chart.showLoading({text:'加载中'});
  loadingStatus.value.pause = true;
  apis.getBehaviorRecordAll(studentId,assignmentId)
      .then((res:any) => {
        if (res && res.data && res.data.code === 200){
          let rowData = res.data.data.events as any[];
          console.log("行为数据",rowData);
          let zeroCount =0;
          pauseData.length = 0;
          chartData.length = 0;
          if (!rowData){
            // ElMessage.error('获取停顿数据失败')
            loadingStatus.value.pause = false;
            chart.hideLoading();
            noData.value = true
            return;
          }
          else{
            loadingStatus.value.pause = false;
            noData.value = false
          }
          if (rowData.length>0){
            limit.max = rowData[0].pauseTime;
          }
          rowData.forEach((item:any) => {
            // console.log("item",item)
            let startStamp = 0;
            if (item.startStamp){
              startStamp = item.startStamp;
            }
            else {
              return;
            }
            if (item.pauseTime < 0){
              return;
            }
            if (startStamp == 0){
              zeroCount++;
            }
            if (zeroCount>1){
              zeroCount = 0;
              return;
            }
            let clock = new Date(startStamp);
            clock.setHours(clock.getHours() + 16);
            pauseData.push([clock,item.pauseTime])
            chartData.push([clock,item.pauseTime])
            limit.max = Math.max(limit.max,item.pauseTime);
          })
          maxPauseTime.value = limit.max;
          let option = {
            xAxis: {
              type:'time',
              splitNumber: props.splitNumber,
            },
            yAxis: {
              type:'value',
              name:'停顿时间(ms)',

            },
            tooltip:{
              formatter:(value:any)=>{
                let date = value.data[0];
                let data = value.data[1];
                return `停顿时刻:${[date.getHours(), date.getMinutes(), date.getSeconds()]
                    .map(num => num.toString().padStart(2, '0'))
                    .join(':')}\n  停顿时长:${data}ms`
              }
            },
            visualMap: {
              type: 'continuous', // 连续型映射
              calculable: true,
              min: limit.min,             // 数据最小值
              max: limit.max,           // 数据最大值
              dimension: 1,       // 根据第2个维度（y值）映射颜色
              inRange: {
                color: ['orange', 'red'] // 渐变范围：小值→蓝色，大值→红色
              },
              itemWidth: props.barWidth,
              bottom:0,
              right:0,
            },
            dataZoom: [
              {
                type: 'inside',
              },
              {
                type: 'slider',
                labelFormatter: function (value) {
                  return formatTimeWithMilliseconds(value);
                }
              }
            ],
            series: [
              {
                symbolSize: 10,

                data: chartData,
                type: 'scatter'
              }
            ]
          };
          chart.setOption( option);
          chart.hideLoading();
          loadingStatus.value.pause = false;
          chart.on('datarangeselected', (params:any) => {
            let range = params.selected as [number,number];
            chartData = pauseData.filter((item:any) => {
              return item[1] >= range[0] && item[1] <= range[1];
            })
            option.series[0].data = chartData;
            chart.setOption(option)
          });
        }
      })

}
onMounted(()=>{
  let chartDom = document.getElementById('pause-canvas');
  let myChart = echarts.init(chartDom);
  getCanvasData(myChart)
  window.addEventListener('resize', ()=>{
    myChart.resize()
  })
})
</script>

<template>
  <div id="pause-canvas" class="canvas-container" v-if="!noData">

  </div>
  <div class="canvas-container" v-else>
    <el-empty description="暂无数据"/>
  </div>
</template>

<style scoped>
.canvas-container{
  width: 100%;
  height: 100%;
}
</style>
