<template>
  <div :class="className" :style="{ height: height, width: width }" ref="chartRef" />
</template>

<script setup>
import { ref, watch } from "vue"
import * as echarts from "echarts"
// import "echarts/theme/macarons" // echarts theme
import { debounce } from "@/utils" // 引入防抖函数

const props = defineProps({
  className: { type: String, default: "chart" },
  width: { type: String, default: "100%" },
  height: { type: String, default: "150px" },
  title: { type: String, default: "折线图" },
  suffix: { type: String, default: "" },
  datas: {
    type: Array,
    default: () => [
      { name: "测试1", value1: "50" },
      { name: "测试2", value1: "60" },
      { name: "测试3", value1: "70" },
    ],
  },
  feilds: {
    type: Array,
    default: () => ["名称", "数值1"],
  },
})

const chartRef = ref(null)
let chart = null

const initChart = () => {
  chart = echarts.init(chartRef.value)
  setOption(props.title, props.datas, props.feilds)
}

const setOption = (title, datas, feilds) => {
  // 将标题进行换行处理
  const setLineFeed = title.split("").join("\n")

  // 数据处理
  let source = formatData(datas, feilds)

  // 系列处理
  let chartSeries = []
  for (let index = 1; index < feilds.length; index++) {
    chartSeries.push({
      type: "line",
      smooth: true,
      areaStyle: {
        color: "#0a3669", //折线区域的背景颜色
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: "rgba(122, 217, 246, 0.8)",
          },
          {
            offset: 1,
            color: "rgba(122, 217, 246, 0.1)",
          },
        ]),
      },
      showSymbol: false,
      itemStyle: {
        color: "#7bdaf7",
        fontSize: 14,
        lineStyle: {
          width: 2, //折线宽度
        },
      },
      label: {
        position: ["50%", "50%"],
      },
    })
  }

  // 构造图标配置信息
  let option = {
    title: {
      show: true,
      left: "left",
      top: "middle",
      textVerticalAlign: "middle",
      text: setLineFeed,
      textStyle: {
        color: "#fff",
        fontSize: 14,
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "line",
      },
      extraCssText: "height:60px;",
      formatter: param => {
        return `时间：${param[0].axisValueLabel}<br/>${props.title}：${param[0].data[1] === null ? "-" :param[0].data[1] + !!props.suffix ? props.suffix : ""}`
      },
    },
    grid: { top: 10, left: 28, right: 20, bottom: 20, containLabel: true },
    dataset: {
      source: source,
    },
    xAxis: {
      type: "category",
      axisLine: {
        lineStyle: {
          color: "#b6c4c9",
          type: "dashed", // 设置为虚线
        },
      },
      boundaryGap: false,
      axisTick: {
        show: false,
      },
      axisLabel: {
        formatter: value => {
          return value.split(" ")[1]
        },
      },
    },
    yAxis: {
      max: value => {
        let num = null
        if (props.alarmUp !== null && value.max < Number(props.alarmUp)) {
          if (Math.floor(value.max).toString().length < Math.floor(Number(props.alarmUp)).toString().length) {
            num = Math.floor(value.max).toString().length
          } else {
            num = Math.floor(Number(props.alarmUp)).toString().length
          }
          return Math.floor(Number(props.alarmUp) + parseInt(1 + "0".repeat(num - 1)))
        } else {
          num = Math.floor(value.max).toString().length
          return Math.floor(value.max + parseInt(1 + "0".repeat(num - 1)))
        }
      },
      axisLine: {
        lineStyle: {
          color: "#b6c4c9",
        },
      },
      splitLine: {
        //网格线
        lineStyle: {
          color: "#b2b3b7",
          type: "dashed", //设置网格线类型 dotted：虚线   solid:实线
        },
        show: true, //隐藏或显示
      },
    },
    series: chartSeries,
  }
  chart.setOption(option, true)
}

const formatData = (datas, feilds) => {
  let source = []
  source.push(feilds)
  datas.forEach(d => {
    let darr = [d.name]
    for (let index = 1; index < feilds.length; index++) {
      darr.push(d[`value${index}`])
    }
    source.push(darr)
  })
  return source
}

watch(
  () => props.title,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      setOption(newVal, props.datas, props.feilds)
    }
  }
)

watch(
  () => props.feilds,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      setOption(props.title, props.datas, newVal)
    }
  },
  { deep: true }
)

watch(
  () => props.datas,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      setOption(props.title, newVal, props.feilds)
    }
  },
  { deep: true }
)
const initListener = debounce(() => {
  if (chart) {
    chart.resize()
  }
}, 100)

onMounted(() => {
  initChart()
  window.addEventListener("resize", initListener)
})

onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener("resize", initListener)
})
</script>
