<template>
  <!-- CDF曲线图 -->
  <div class="container">
    <div class="main">
      <div :id="idName" class="cdfCurve"></div>
      <!-- <div class="showDetial" @click="showViewClick" v-if="isShowDetial">
        <el-icon v-if="showView" class="icon">
          <View />
        </el-icon>
        <el-icon v-else class="icon">
          <Hide />
        </el-icon>
        <span>详情</span>
      </div> -->
      <!-- <div class="showValue">
        <div v-for="(item, index) in markLineData" :key="index">
          <span style="font-weight: 700;font-size: 10px; padding: 0 5.5px;" :style="{ color: item.color }">--</span>{{
            item.descript }}
        </div>
      </div> -->
    </div>
    <el-dialog v-model="isDetialDialogVisible" :show-close="false" :modal="false" custom-class="custom-cdf-dialog"
      width="200" height="100" :destroy-on-close="false" :before-close="isDetialDialogVisibleHandleClose"
      style="margin: 0;padding: 0; background-color: rgba(0, 0, 0, 0);">
      <childrenCdfCurve ref="childrenCdfRef" :propsDate="propsDate"
        @isDetialDialogVisibleHandleClose="isDetialDialogVisibleHandleClose" />
    </el-dialog>
  </div>
</template>

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

<script setup>

import * as echarts from 'echarts';
import childrenCdfCurve from './childrenCdfCurve.vue'
import { onMounted, onUnmounted, ref, nextTick, computed, watch } from 'vue';

const idName = ref(Math.random().toString(30).slice(2, 8))

const props = defineProps({
  propsDate: {
    type: Object,
    default: () => ({})
  },
  isShowDetial: {
    type: Boolean,
    default: false
  },
  color: {
    type: String,
    default: '#5470C6'
  },
  legendName: {
    type: String,
    default: 'CDF曲线图'
  },
  data: {
    type: Array,
    default: () => []
  },
  zoomHeight: {
    type: String,
    default: null
  }
})

const dataX = computed(() => {
  if (props.data.length > 0 && props.data[0]?.x == 'PDF分布') {
    let arr = []
    props.data.forEach(item => {
      arr = item.y.dropRate.map(el => el.x)
    })
    return arr
  }
  return props.data.length > 0 ? props.data.map(item => item.x) : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
})
const dataY = computed(() => {
  if (props.data.length > 0 && props.data[0]?.x == 'PDF分布') {
    let arr = []
    props.data.forEach(item => {
      arr = item.y.dropRate.map(el => el.y)
    })
    return arr
  }
  return props.data.length > 0 ? props.data.map(item => item.y) : [12, 13, 5, 103, 19, 3, 18]
})

watch(() => props.data, (newVal) => {
  initChart();
})

const showView = ref(false);

var lineColor = props.color;
const markLineData = ref([
  {
    color: '#89dac4',
    descript: "最大值：12"
  },
  {
    color: '#da45ds',
    descript: "最小值：12"
  },
  {
    color: '#56fds9',
    descript: "平均值：12"
  },
])
let myChart = null;
const isDetialDialogVisible = ref(false);
function showViewClick() {
  // //console.log("时间");
  isDetialDialogVisible.value = !isDetialDialogVisible.value;
  showView.value = true;
  if (window.ue5) {
    window.ue5("callBackAllDialogFn", String(JSON.stringify({
      type: "CDFCurveDetailDialog",
      status: "open"
    })));
  }
  // //console.log("当前的值:",showView.value);

}
function isDetialDialogVisibleHandleClose() {
  isDetialDialogVisible.value = false;
  showView.value = false;
  if (window.ue5) {
    window.ue5("callBackAllDialogFn", String(JSON.stringify({
      type: "CDFCurveDetailDialog",
      status: "close"
    })));
  }
}
onMounted(() => {
  nextTick(() => {
    initChart();
  })
  //console.log("-------cdfCurve-------",props.idName);
  // document.getElementById(props.idName).style.height = '240px';

});

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

function initChart() {
  const chartDom = document.getElementById(idName.value);
  chartDom.style.height = '100%';
  chartDom.style.width = '100%';
  if (!myChart) {
    myChart = echarts.init(chartDom);
  };
  const option = {
    legend: {
      show: true,
      data: [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: '8%',
      bottom: '16%',
      left: '18%',
      containLabel: true //自动计算x轴label
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dataX.value,
      // axisLabel: {
      //   interval: 0,
      //   rotate: 0,
      //   fontSize: 10,
      //   color: '#fff',
      // }
      axisLabel: {
        interval: 0,
        fontSize: 10,
        color: '#fff',
        rotate: 45,
        margin: 20,
        fontSize: 10,
        // interval: 'auto', // 或直接不写
        // interval: function (index) {
        //   return index % 10 === 0 // 每10个显示一个
        // },
        hideOverlap: true, //  防重叠（很关键）
        formatter: function (value) {
          // console.log('x - value', value)
          if (value.toString().includes('-')) {
            // console.log('嘿嘿', value)
            let str = []
            const arr = value.split('-') // 只保留日期部分
            for (let val of arr) {

              if (Number(val) >= 1e8 && val.includes('.')) {
                // console.log(val)
                val = (Number(val) / 1e8).toFixed(0) + '亿'
              }
              str.push(val)
            }
            return str.join('-') // 用换行符连接
          }
          // console.log('value', value)
          return value
        }
      },
      axisLine: {
        show: true, //去除轴线
        lineStyle: {
          color: "#DCE2E8",//设置x轴轴线颜色
        }
      },
    },
    dataZoom: dataX.value.length <= 7 ? [] : [
      // {
      //   type: 'slider',
      //   xAxisIndex: 0,
      //   startValue: 0,
      //   endValue: 5, // 一屏只看20个点 ⭐
      //   height: 5,
      //   showDetail: false,
      //   top: 40
      // },
      // {
      //   type: 'inside',
      //   start: 0,
      //   end: 10,
      //   left: '18%',
      //   right: '8%',
      //   minSpan: 1,
      //   handleLabel: {
      //     show: false
      //   },
      //   labelFormatter: function (value) {
      //     console.log('xxx', dataX[value])
      //     return dataX[value]
      //   },
      //   textStyle: {
      //     color: 'rgba(255, 255, 255, 0.92)',
      //     fontSize: 8
      //   }
      // },
      {
        start: 0,
        end: 100,
        minSpan: 1,
        bottom: 8,
        left: '14%',
        right: '10%',
        height: Number(props?.zoomHeight) || 20,
        handleLabel: {
          show: false
        },
        labelFormatter: function (value) {
          return dataX[value]
        },
        textStyle: {
          color: 'rgba(255, 255, 255, 0.92)',
          fontSize: 8
        }
      }

    ],
    yAxis: {
      type: 'value',
      // max: 120,
      minInterval: 1,
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)',
          width: 1,
          type: 'dashed'
        }
      },
      splitNumber: 5,
      axisLabel: {
        color: '#fff',
        fontSize: 10,
        formatter: function (value) {
          return value.toFixed(0);
        }
      }
    },
    series: [
      {
        name: props.legendName,
        color: props.color,
        data: dataY.value,
        type: 'line',
        smooth: 0.6,
        symbol: 'none',
        lineStyle: {
          color: lineColor,
          width: 3
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: lineColor
              },
              {
                offset: 1,
                color: 'rgba(84,112,198,0.20)'
              }
            ],
            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'
          //     },
          //   }
          // ]
        }
      }
    ],
    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
      },
      // 固定tooltip位置在顶部
      position: function (pos, params, dom, rect, size) {
        return ['10%', pos[1]];
      }
    }
  };

  myChart.setOption(option);
  resizeChart();
  window.addEventListener('resize', resizeChart);
}

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;
}

.cdfCurve div {
  width: 100%;
  height: 100%;
}

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

/* .custom-cdf-dialog{
  position: absolute;
  left: 100px;
} */
.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>