<template>
  <a-row>
    <a-col :span="12" :key="index" v-for="(item, index) in lineDatas">
      <div class="chart-title">
        <span class="ellipsis">{{ item.mtrcName }}</span>
        <span style="padding-right: 30px"
          >起始时间：<a-select v-model:value="selYear" :options="lineYearOptions" @change="yearChange(item, index)"
        /></span>
      </div>
      <div class="parent">
        <div :ref="setChartRefs(index)" class="chart-container" :style="{ height, width }"> </div>
        <a-slider class="child" vertical range v-model:value="yRange[item.mtrcNo]" @change="setYRange(item, index)" :max="100" :min="0" />
      </div>
    </a-col>
  </a-row>
</template>

<script lang="ts" setup>
  import { ref, defineProps, nextTick, reactive, toRefs } from 'vue';
  import * as echarts from 'echarts';
  import { getPageChartData, getMtricDataByMtrcNo } from './api.ts';

  const props = defineProps({
    data: { require: true, type: Object },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: '40vh',
    },
    loading: {
      type: Boolean,
      default: false,
    },
  });

  const currentYear = new Date().getFullYear();
  const selYear = ref(currentYear);
  const lineDatas = ref([]);
  const chartContainers = {};
  const lineYearOptions = ref([]);

  const oldData = ref({});
  const legendAry = ref(['', '正常', '预警', '干预']);
  const yRange = ref({});

  for (let i = 0; i < 5; i++) {
    let option = {};
    option['value'] = currentYear - i;
    option['label'] = currentYear - i;
    lineYearOptions.value.push(option);
  }

  function setSliderMax(item) {
    return yRange.value[item.mtrcNo][1];
  }

  function setSliderMin(item) {
    return yRange.value[item.mtrcNo][0];
  }

  function setYRange(item, ind) {
    let options = oldData.value[item.mtrcNo];
    options['yAxis']['min'] = yRange.value[item.mtrcNo][0];
    options['yAxis']['max'] = yRange.value[item.mtrcNo][1];
    const childComponent = chartContainers['chart' + ind];
    const chartInstance = echarts.init(childComponent);
    chartInstance.setOption(options);
  }

  function yearChange(item, ind) {
    const childComponent = chartContainers['chart' + ind];
    if (childComponent) {
      const chartInstance = echarts.init(childComponent);
      let item = lineDatas.value[ind];
      let param = { mtrcNo: item.mtrcNo, year: selYear.value };
      getMtricDataByMtrcNo(param).then((res) => {
        if (res.success) {
          let min = res?.result?.min;
          let max = res?.result?.max;
          yRange.value[item.mtrcNo] = [min, max];
          let options = setChartOptions(res.result, item.mtrcNo);
          oldData.value[item.mtrcNo] = options;
          chartInstance.setOption(options);
        }
      });
    }
  }

  async function setChartDatas() {
    await getPageChartData().then((res) => {
      lineDatas.value = res;
      nextTick(() => {
        initCharts();
      });
    });
  }
  setChartDatas();

  const setChartRefs = (index) => {
    return (ref) => {
      chartContainers['chart' + index] = ref;
    };
  };
  async function initCharts() {
    Object.keys(chartContainers).forEach((key) => {
      const childComponent = chartContainers[key];
      if (childComponent) {
        const chartInstance = echarts.init(childComponent);
        let lastInd = key.substring(key.length - 1);
        let item = lineDatas.value[lastInd];
        let param = { mtrcNo: item.mtrcNo, year: item.year };
        selYear.value = item.year;
        getMtricDataByMtrcNo(param).then((res) => {
          if (res.success) {
            yRange.value[item.mtrcNo] = [res.result.min, res.result.max];
            let options = setChartOptions(res.result, item.mtrcNo);
            oldData.value[item.mtrcNo] = options;
            chartInstance.setOption(options);
          }
        });
        window.addEventListener('resize', () => {
          chartInstance.resize();
        });
      }
    });
  }

  function setChartOptions(data, mtrcNo) {
    const interval = Math.ceil((data.max - data.min) / 10);
    const options = {
      backgroundColor: '#fff',
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
          label: {
            show: true,
            backgroundColor: '#ccc',
          },
        },
      },
      legend: {
        data: legendAry.value,
        textStyle: {
          color: 'black',
        },
      },
      xAxis: {
        data: data.category,
        axisLine: {
          show: true,
          lineStyle: {
            color: 'black',
          },
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
        },
      },
      yAxis: {
        type: 'value',
        name: data.unit ? '[单位:' + data.unit + ']' : '',
        position: 'left',
        alignTicks: true,
        interval: interval,
        min: Math.floor(yRange.value[mtrcNo][0]),
        max: Math.ceil(yRange.value[mtrcNo][1]),
        scale: true,
        axisLabel: {
          formatter: '{value}',
        },
        axisLine: {
          show: false,
          onZero: false,
          lineStyle: {
            color: 'black',
          },
        },
        splitLine: {
          show: true,
        },
      },
      series: [
        {
          name: legendAry.value[0],
          type: 'line',
          smooth: true,
          showAllSymbol: 'auto',
          symbol: 'emptyCircle',
          symbolSize: 8,
          data: data['mtrc'],
        },
        {
          name: legendAry.value[2],
          type: 'line',
          smooth: true,
          showAllSymbol: 'auto',
          symbol: 'none',
          symbolSize: 8,
          color: 'yellow',
          lineStyle: {
            color: 'yellow',
          },
          data: data['warn'],
        },
        {
          name: legendAry.value[3],
          type: 'line',
          smooth: true,
          showAllSymbol: 'auto',
          symbol: 'none',
          symbolSize: 8,
          color: 'red',
          data: data['intv'],
          lineStyle: {
            color: 'red',
          },
        },
      ],
    };
    return options;
  }
</script>

<style scoped>
  .chart-container {
    margin-bottom: 30px;
  }
  .parent {
    position: relative;
    background-color: #ffffff;
    border: 2px dotted #1789f5;
    margin-right: 30px;
    margin-bottom: 30px;
    box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.2);
  }

  .child {
    display: none;
    position: absolute;
    top: 40px;
    right: 10px;
    width: 10px;
    height: 60%;
    z-index: 1; /* 控制在层叠顺序中的位置，值越大越靠前 */
    background-color: rgba(255, 255, 255, 0.5);
  }

  .parent:hover .child {
    display: block;
  }
  .chart-title {
    display: flex;
    flex-wrap: nowrap;
    justify-content: space-between;
    padding: 10px 0;
    font-size: 18px;
  }
  .chart-box {
    margin: 5px;
  }
  .ellipsis {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
</style>
