<template>
  <!-- 瞬时曲线图 -->
  <div class="container">
    <div class="main">
      <div :id="idName" class="cdfCurve"></div>
    </div>
    <el-dialog v-model="isDetialDialogVisible" :modal='false' :show-close="false" :modal-penetrable='true' width="200"
      height="100" :before-close="isDetialDialogVisibleHandleClose" style="margin: 0;padding: 0; ">
      <childrenInstantCurveDetail ref="childrenInstantRef" :propsDate="propsDate"
        @isDetialDialogVisibleHandleClose="isDetialDialogVisibleHandleClose" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "cdfCurve_chart"
}
</script>

<script setup>
import * as echarts from 'echarts';
import childrenInstantCurveDetail from './childrenInstantCurve.vue'
import { onMounted, onUnmounted, ref, nextTick, watch } from 'vue';
//不重复的id信息
const idName = ref(Math.random().toString(30).slice(2, 8) + new Date().getTime())
const props = defineProps({
  propsDate: {
    type: Object,
    default: () => ({})
  },
  isShowDetail: {//暂时无用
    type: Boolean,
    default: false
  },
  legendName: {//可能是数组
    type: null,
    default: '默认曲线图'
  },
  color: {//可能是数组
    type: null,
    default: '#5470C6'
  },
  data: {
    type: Array,
    default: () => []
  },
  zoomHeight: {
    type: String,
    default: null
  },
  lineArray: {
    type: Boolean,
    default: false
  },
  istemplate: {//判断是配置模版还是右侧正常显示
    type: Boolean,
    default: false
  },
  yName: {//y轴名称
    type: Array,
    default: () => []
  }
})
watch(() => props.data, (newVal) => {
  initChart();
})

const dataX = computed(() => {
  if (props.lineArray) {//代表x轴有多个
    let arrx = []
    props.data.forEach(it => {
      arrx.push(it.length > 0 ? it.map(item => item.x.split(' ')[1]?.slice(0, 8)) : props.istemplate ? ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] : [])
    })
    // console.log(arrx, 'x轴信息');
    return arrx
    // return props.data.length > 0 ? props.data.map(item => item.x.split(' ')[1].slice(0, 8)) : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  } else {
    return props.data.length > 0 ? props.data.map(item => item.x.split(' ')[1]?.slice(0, 8)) : props.istemplate ? ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] : [];
  }

})
const dataY = computed(() => {
  // console.log(props.data, 'Y轴信息');
  let arry = []
  if (props.lineArray) {
    props.data.forEach(it => {
      if (it[0]?.y && Object.prototype.toString(it[0]?.y) === '[object Object]' && it[0].y?.errorRate !== undefined) {
        it.forEach(item => {
          item.y = item.y.dropRate
        })
      }
      arry.push(it.length > 0 ? it.map(item => item.y) : props.istemplate ? [12, 13, 5, 103, 19, 3, 18] : [])
    })
    return arry
  } else {
    if (props.data[0]?.y && Object.prototype.toString(props.data[0]?.y) === '[object Object]' && props.data[0].y?.errorRate !== undefined) {
      props.data.forEach(item => {
        item.y = item.y.dropRate
      })
    }
    return props.data.length > 0 ? props.data.map(item => item.y) : props.istemplate ? [12, 13, 5, 103, 19, 3, 18] : []
  }

})

//折线图颜色设置
const isDetialDialogVisible = ref(false)//弹框状态
//关闭弹窗
const isDetialDialogVisibleHandleClose = () => {
  isDetialDialogVisible.value = false;
  if (window.ue5) {
    window.ue5("callBackAllDialogFn", String(JSON.stringify({
      type: "InstantaneousCurveDetailsDialog",
      status: "close"
    })));
  }
}
let myChart = null;
onMounted(() => {
  nextTick(() => {
    initChart();
  })
});

onUnmounted(() => {
  if (myChart) {
    window.removeEventListener('resize', resizeChart);
    myChart.dispose();
  }
});

const series1Data = ref([])//时间轴对象数据
function initChart() {
  console.log(props.data, '传入数据---------------');
  const chartDom = document.getElementById(idName.value);
  if (!myChart) {
    myChart = echarts.init(chartDom);
  };
  chartDom.style.height = '100%';
  chartDom.style.width = '100%';
  //判断x轴刻度问题
  var firstTime = 0, lastTime = 0;
  // 定义一个字段,判断x轴是不是时间,如果是,则type为time
  var xAxisType = 'category';

  let seriesArr = [];//图标数据
  if (props.lineArray) {
    xAxisType = 'time';
    props.data.forEach((it, index) => {
      if (it.length > 0) {
        series1Data.value = it.map((item, idx) => [item.x, it[0]?.y && Object.prototype.toString(it[0]?.y) === '[object Object]' && it[0].y?.errorRate !== undefined ? item.y.dropRate : item.y]);
        // console.log(series1Data.value, '最终数据');
        if (series1Data.value.length > 0) {
          if (firstTime < 1) {
            firstTime = new Date(series1Data.value[0][0]).getTime()
          }
          // firstTime = new Date(series1Data.value[0][0]).getTime() < firstTime ? new Date(series1Data.value[0][0]).getTime() : firstTime
          firstTime = new Date(series1Data.value[0][0]).getTime() < firstTime ? new Date((series1Data.value[0][0]).split(' ')[0] + ' 00:00:00').getTime() : firstTime
          // lastTime = new Date(series1Data.value[series1Data.value.length - 1][0]).getTime() > lastTime ? new Date((series1Data.value[series1Data.value.length - 1][0])).getTime() : lastTime
          lastTime = new Date(series1Data.value[series1Data.value.length - 1][0]).getTime() > lastTime ? new Date((series1Data.value[series1Data.value.length - 1][0]).split(' ')[0] + ' 23:59:59').getTime() : lastTime

          seriesArr.push({
            color: props.color[index],
            name: props.legendName[index],
            data: series1Data.value,
            type: 'line',
            smooth: 0.6,
            symbol: 'none',
            lineStyle: {
              color: props.color[index],
              width: 3
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: hexToRgba(props.color[index], 0.8)
                  },
                  {
                    offset: 1,
                    color: hexToRgba(props.color[index], 0.2)
                  }
                ],
                global: false
              }
            },
            markLine: {
              symbol: 'none',
              label: {
                show: false
              },
            }
          })

        } else {
          seriesArr = []
          firstTime = 0
          lastTime = 0
        }
      }
    })
  } else {
    // console.log(dataX.value, 'xinxi1-----', props.data);

    if (props.data[0]?.x?.includes(':')) {
      xAxisType = 'time';
      if (dataX.value.length > 0) {
        // firstTime = props.data[0]?.x
        firstTime = new Date((props.data[0]?.x).split(' ')[0] + ' 00:00:00').getTime()
        // lastTime = props.data[props.data.length - 1]?.x
        lastTime = new Date((props.data[props.data.length - 1]?.x.split(' ')[0]) + ' 23:59:59').getTime()
      }
      series1Data.value = props.data.map((item, idx) => [item.x, item?.y && Object.prototype.toString(item?.y) === '[object Object]' && item.y?.errorRate !== undefined ? item.y.dropRate : item.y]);
      // console.log(series1Data.value, '最终数据');

    } else {
      xAxisType = 'category';
    }

    seriesArr.push({
      color: props.color,
      name: props.legendName,
      data: xAxisType == 'time' ? series1Data.value : dataY.value,
      type: 'line',
      smooth: 0.6,
      symbol: 'none',
      lineStyle: {
        color: props.color,
        width: 3
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: hexToRgba(props.color, 0.8)
            },
            {
              offset: 1,
              color: hexToRgba(props.color, 0.2)
            }
          ],
          global: false
        }
      },
      markLine: {
        symbol: 'none',
        label: {
          show: false
        },
        // data: [
        //   {
        //     yAxis: 45,
        //     lineStyle: {
        //       color: '#ff0000',
        //       width: 2,
        //       type: 'dashed'
        //     },
        //   },
        //   {
        //     yAxis: 70,
        //     lineStyle: {
        //       color: '#ff55f5',
        //       width: 2,
        //       type: 'dashed'
        //     },
        //   }
        // ]
      }
    })
  }


  var option = {
    legend: {
      show: true,
      data: Array.isArray(props.legendName) ? props.legendName : [props.legendName],
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      top: 0,
      left: '-5px',
      backgroundColor: 'transparent',
      borderColor: 'transparent',
      padding: [5, 10],
      // 添加图标样式控制
      icon: 'rect',  // 使用矩形图标
      itemWidth: 15, // 图例宽度
      itemHeight: 5, // 图例高度，设为较小值形成线条效果

    },
    grid: {
      top: '23%',
      right: '4%',
      bottom: '16%',
      left: '8%',
      containLabel: true //自动计算x轴label
    },
    xAxis: {
      type: xAxisType,
      // type: props.lineArray ? 'time' : 'category',
      boundaryGap: false,
      data: dataX.value,
      // data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      axisLabel: {
        interval: 0,
        fontSize: 10,
        color: '#fff',
        rotate: 45,
        margin: 20,
        interval: !props.lineArray ? 'auto' : 0, // 或直接不写
        hideOverlap: false, //  防重叠（很关键）
        showMinLabel: true,   // 显示最小刻度标签
        showMaxLabel: true,    // 显示最大刻度标签

        formatter: function (value) {
          if (!props.lineArray) {
            if (xAxisType == 'time') {
              return timestampToHMS(value)
              //   if (firstTime == value || lastTime == value) {
              //     return value
              //   } else {
              //     if (value.split(':')[1] == '00' && value.split(':')[2] == '00') {
              //       console.log(value);
              //       return value
              //     }
              //   }
            } else {
              return value
            }

            // console.log(value, 'x轴刻度', firstTime, lastTime);



          }
          if (value.toString().includes(':')) {
            const date = new Date(value);
            const minutes = date.getMinutes();
            if (minutes === 0) {
              return value
            }
          } else if (!isNaN(Number(value)) || (firstTime == value || lastTime == value)) {//展示整点和其实和结束点
            const date = new Date(value);
            const minutes = date.getMinutes();
            if (firstTime == value || lastTime == value) {
              return timestampToHMS(value)
            }
            if (minutes === 0) {
              // console.log(date, '判断分钟11', value);
              return timestampToHMS(value)
            }
          }
        }
      },
      axisLine: {
        show: true, //去除轴线
        lineStyle: {
          color: "#DCE2E8",//设置x轴轴线颜色
        }
      },
      max: lastTime,
      // 单独设置最大值标签
      maxLabel: {
        formatter: function (value) {
          return '终点 ' + value;
        }
      },
    },
    yAxis: {
      type: 'value',
      name: props.lineArray ? (props.yName.type ? props.yName.value[0] : '') : props.yName.value,//y轴名称
      nameTextStyle: {            // 文本样式
        fontSize: 12,
        fontWeight: 'bold',
        color: '#fff',
        // padding: [0, 40, 0, 0]
      },
      // max: 120,
      minInterval: 1,
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)',
          width: 1,
          type: 'dashed'
        }
      },
      splitNumber: 5,
      axisLabel: {
        color: '#fff',
        // rotate: 45,
        fontSize: 10,
        formatter: function (value) {
          if (Number(value) >= 1e8) {
            return (Number(value) / 1e8).toFixed(0) + '亿'
          }
          return value
        }
      }
    },
    dataZoom: (props.lineArray ? series1Data.value.length <= 7 : dataX.value.length <= 7) ? [] : [
      {
        start: 0,
        end: 100,
        minSpan: 1,
        type: 'slider',
        left: '14%',
        right: '10%',
        height: Number(props.zoomHeight) || 20,
        bottom: 8,
        handleLabel: {
          show: false
        },
        labelFormatter: function (value) {
          if (props.lineArray) {
            // console.log('触发', value);
            return series1Data.value[value]
          } else {
            return dataX[value]
          }
        },
        textStyle: {
          color: 'rgba(255, 255, 255, 0.92)',
          fontSize: 8
        }
      },
      { type: 'inside', start: 0, end: 100 }
    ],
    series: seriesArr,
    tooltip: {
      trigger: 'axis',
      // 确保tooltip显示在最上层
      extraCssText: 'z-index: 999999 !important;',
      backgroundColor: 'rgba(50,50,50,0.8)',
      borderColor: '#333',
      borderWidth: 1,
      padding: 10,
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      formatter: function (params) {
        let res = ''
        if (params[0].seriesIndex == 0) {
          if (Array.isArray(props.legendName) && props.legendName.length > 1) {
            res = timestampToHMS(params[0].axisValue) + '<br>';
            if (props.data[0].length > 0) {
              res += `${`<span style=\"display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${props.color[0]};\"></span>`} ${props.legendName[0]}: ${params[0].value[1]} ${props.lineArray ? props.yName?.value[params[0].seriesIndex] : props.yName?.value}<br>`;
            }
            if (props.data[1].length > 0) {
              res += `${`<span style=\"display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${props.color[1]};\"></span>`} ${props.legendName[1]}:<br>`;
            }
            return res;
          } else {
            // console.log(params,props.legendName);

            res = timestampToHMS(params[0].axisValue) + '<br>';
            res += `${params[0].marker} ${props.legendName}: ${params[0].value[1]} ${props.lineArray ? props.yName?.value[params[0].seriesIndex] : props.yName?.value}<br>`;
            return res;
          }

        } else if (params[0].seriesIndex == 1) {

          let res = timestampToHMS(params[0].axisValue) + '<br>';
          if (props.data[0].length > 0) {
            res += `${`<span style=\"display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${props.color[0]};\"></span>`} ${props.legendName[0]}:<br>`;
          }
          if (props.data[1].length > 0) {
            res += `${`<span style=\"display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${props.color[1]};\"></span>`} ${props.legendName[1]}: ${params[0].value[1]} ${props.lineArray ? props.yName?.value[params[0].seriesIndex] : props.yName?.value} <br>`;
          }
          return res;
        }
      },
      // 固定tooltip位置在顶部
      position: function (pos, params, dom, rect, size) {
        return ['10%', pos[1]];
      }
    }
  };
  // console.log(option, '配置项目');

  if (props.lineArray) {
    delete option.xAxis.data
  }
  // console.log(JSON.stringify(option), '数据配置');

  clearTimeout(timesset)
  myChart.setOption(option);
  resizeChart();
  window.addEventListener('resize', resizeChart);
}
//转换颜色函数
function hexToRgba(hex, alpha) {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
//将时间戳转换成时分秒
function timestampToHMS(timestamp) {
  const date = new Date(timestamp); // 如果传入的是秒，需要乘以1000转换为毫秒
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${hours}:${minutes}:${seconds}`;
}
var timesset = null
function resizeChart() {
  if (myChart) {
    myChart.resize();
  }
}
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  position: relative;
}

.main {
  width: 100%;
  height: 100%;
  /* border: 1px solid #3A4C5B; */
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  position: relative;
}

.cdfCurve {
  width: 100%;
  /* flex: 1; */
  min-height: 180px;
  height: 100%;
  /* 改为min-height确保足够空间 */
  position: relative;
  z-index: 1;
}


.showDetial {
  position: absolute;
  /* flex-direction: row; */
  font: 12px "微软雅黑";
  color: #8a8a8a;
  top: 0;
  right: 10px;
  z-index: 1;
  /* background-color: aquamarine; */
  /* justify-content: center;
  align-items: center; */
}

.showDetial .icon {
  margin: 0;
  padding: 0;
  top: 2px;

}

.showDetial span {
  padding-left: 5px;
}

.showDetial:hover {
  /* background-color: rgba(255, 255, 255, 0.91); */
  color: #607FB0;
  /* font-weight: 800; */
}

.showValue {
  width: 100%;
  /* padding: 5px; */
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
  flex-wrap: wrap;
  font-size: 10px;
  /* background-color: black; */
  z-index: 0;
  /* overflow: hidden; */
  /* 确保在图表下方 */
}
</style>