<script setup>
import { onMounted, onUnmounted, watch, ref } from 'vue';
import * as echarts from 'echarts';
import { formatDecimals } from "@/utils/format";
import { screenApi } from '@/api/screen';
import dayjs from 'dayjs';
import LayoutCard from './LayoutCard.vue';
import { getBarOptions } from '../config/echartOption';

const props = defineProps({
  screenData: {
    type: Object,
    default: []
  }
})

let barOption = {};
let lineOption = {};
let timer = null;
let chart = null;
const activeIndex = ref(0);
const echartRef = ref(null);


const windowResize = () => {
  clearTimeout(timer);
  timer = setTimeout(() => chart.resize(), 100);
};

watch(() => props.screenData, (currentVal) => {
  const { no3Hlj1Jqr, no3Hlj2Jqr, nh31Jqr, nh32Jqr, tpRccJqr } = currentVal;
  const options = [ no3Hlj1Jqr, no3Hlj2Jqr, nh31Jqr, nh32Jqr, tpRccJqr ].map(item => {
    return item ? Number(item.toFixed(2)) : 0;
  })
  barOption = options;
  chart.setOption( getBarOptions(options) )
})

const getLineOptions = ({xAxisData, seriesData}) => {
  const colors = ['#F7931E', '#2454FF', '#00FFFF', '#00FF00', '#3DB0F1', '#F4CF35',];
  const series = Object.keys(seriesData).map(((key, index) => {
    const item = seriesData[key];
    const color = colors[index];
    return {
      name: key,
      type: "line",
      smooth: true,
      symbol: 'none',
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color,
          },
          {
            offset: 1,
            color: "rgba(255, 255, 255, 0.3)",
          },
        ]),
      },
      itemStyle: { color },
      lineStyle: {
        width: '2',
        color
      },
      data: item
    }
  }));

  const option = {
    grid: {
      bottom: '4%',
      top: "23%",
      left: "5%",
      right: "2%",
      containLabel: true,
    },
    tooltip: {
      trigger: "axis",
    },
    legend: [
      {
        show: true,
        orient: 'horizontal',
        icon: 'circle',
        itemWidth: 8,
        y: 'top',
        x: 'right',
        textStyle: {fontSize: '12px', color: '#415B73'},
        data: ['1#好氧池硝酸盐', '1#缺氧氨氮', '二沉池正磷酸盐']  
      },
      {
      show: true,
      orient: 'horizontal',
      icon: 'circle',
      itemWidth: 8,
      y: '8%',
      x: 'right',
      textStyle: {fontSize: '12px', color: '#415B73'},
      data: ['2#好氧池硝酸盐', '2#缺氧氨氮',]  
    }
    ],
    xAxis: {
      type: "category",
      data: xAxisData,
      axisLabel: {
        interval: 'auto',
        show: true,
        fontSize: '11px',
        color: "#0A284E",
      },
      axisLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          show: true,
          color: "#c1d3e6",
        },
      },
      axisTick: {
        show: false,
      },
      interval: 0, // 0 表示强制显示所有标签，'auto' 表示自动间隔
      // boundaryGap: true,
    },
    yAxis: {
      splitNumber: 4,
      type: "value",
      axisLabel: {
        show: true,
        fontSize: '12px',
        color: "#7395B3"
      },
      axisLine: {
        show: false,
        lineStyle: {
          color: "#BDD4E8",
        },
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        lineStyle: {
          color: "#BDD4E8",
          type: "dashed",
        },
      }
    },
    series
  };

  return option;
}

const onChangeTab = (index) => {
  activeIndex.value = index;
  if (index == 0) {
    chart.setOption( getBarOptions(barOption), {notMerge: true} )
  } else {
    chart.setOption( getLineOptions(lineOption), {notMerge: true} )
  }
  setTimeout(() => chart.resize());
}

onMounted(() => {
  screenApi.getContinueDataByDays().then(({ data }) => {
    const seriesData = { '1#好氧池硝酸盐': [], '2#好氧池硝酸盐': [], '1#缺氧氨氮': [], '2#缺氧氨氮': [], '二沉池正磷酸盐': [] };
    const xAxisData = data.map(item => dayjs(item.testHour).format('MM/DD HH'));
    data.forEach(({ no3Hlj1Jqr, no3Hlj2Jqr, nh31Jqr, nh32Jqr, tpRccJqr }) => {
      seriesData['1#好氧池硝酸盐'].push(formatDecimals(no3Hlj1Jqr));
      seriesData['2#好氧池硝酸盐'].push(formatDecimals(no3Hlj2Jqr));
      seriesData['1#缺氧氨氮'].push(formatDecimals(nh31Jqr));
      seriesData['2#缺氧氨氮'].push(formatDecimals(nh32Jqr));
      seriesData['二沉池正磷酸盐'].push(formatDecimals(tpRccJqr));
    })
    lineOption = {xAxisData, seriesData};
  })

  chart = echarts.init(echartRef.value, 'light');
  window.addEventListener("resize", windowResize);
})

onUnmounted(() => {
  window.removeEventListener("resize", windowResize);
})
</script>

<template>
  <LayoutCard title="连续检测数据">
    <template #headerRight>
      <ul>
        <li :class="['btn', activeIndex == 0 ? 'action' : '']" @click="onChangeTab(0)">当前</li>
        <li :class="['btn', activeIndex == 1 ? 'action' : '']" @click="onChangeTab(1)">近7日</li>
      </ul>
    </template>
    <div class="main-container">
      <div class="echart-card">
        <div class="title" v-show="activeIndex == 0">
          <span></span>
          <ul class="tabs space-x-[18px]">
            <li class="item space-x-[6px]">
              <span class="square-icon border-[#FF6737]"><i class="bg-[#FF6737]"></i></span>
              <span>当前值</span>
            </li>
            <li class="item space-x-[6px]">
              <span class="square-icon border-[#00AB84]"><i class="bg-[#00AB84]"></i></span>
              <span>标准值</span>
            </li>
          </ul>
        </div>
        <div class="echart-inner" ref="echartRef" ></div>
        <!-- :style="{ height: activeIndex === 0 ? '10rem' : '20rem' }" -->
      </div>
    </div>
  </LayoutCard>
</template>

<style lang="scss" scoped>
.main-container {
  width: 100%;
  height: 236px;

  .echart-card {
    display: flex;
    flex-flow: column;
    height: 100%;
    color: #415B73;
    font-size: 12px;
    font-weight: bold;

    .title {
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 0 12px 0;

      .tabs {
        display: flex;

        .item {
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;

          .square-icon {
            display: inline-block;
            padding: 1px;
            border-width: 1px;
            border-style: solid;
            background: #fff;

            i {
              display: block;
              width: 8px;
              height: 8px;
            }
          }
        }
      }
    }
    .echart-inner {
      flex: 1;
    }
  }
}

.btn {
  width: 62px;
  height: 28px;
  background: rgba(238, 249, 255, 1);
  border: 1px solid rgba(122, 215, 249, 1);
  float: left;
  border-radius: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: rgba(84, 194, 248, 1);
  font-size: 14px;

  &:first-child {
    border-right: 0;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }

  &:last-child {
    border-left: 0;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
  }
}
.action, .btn:hover {
  background: linear-gradient(270deg, #59CCFA 0%, #3C97F7 100%);
  border: none;
  color: #fff;
}
</style>