<template>
  <div :id="id" ref="techy-line-chart" class="techy-chart" />
</template>

<script>
import echarts from 'echarts'
import resize from '@/views/OperationalOverview/components/mixins/resize'
import { Random } from 'mockjs'
import moment from 'moment'

class ChartOption {
  constructor() {
    this.color = ['#E02094', '#F0D63C', '#1A99FF']

    this.legend = {
      top: 11,
      right: 32,
      itemWidth: 8,
      itemHeight: 8,
      textStyle: {
        color: '#fff9',
        fontSize: 10
      }
    }

    this.grid = {
      top: 36,
      left: 64,
      bottom: 36
    }

    this.tooltip = {
      show: true,
      trigger: 'axis',
      // position: [200,10],
      // position: ['25%', '25%'],
      position: pointer => {
        return [pointer[1], 0]
      },
      axisPointer: {
        type: 'line',
        axis: 'x',
        lineStyle: {
          color: '#7BFFFB',
          type: 'dotted'
        }
      },
      padding: 10,
      backgroundColor: 'rgba(13, 29, 53, 0.8)',
      extraCssText: 'width: auto !important; height: auto !important;',
      formatter: params => {
        return `
            <div style="display: flex; flex-direction: column; gap: calc(4px * var(--beilv));">
              <h2 style="font-size: calc(14px * var(--beilv)); margin: 0 0 4px; font-weight: normal; color: white;">${
  params[0].axisValue
}</h2>
              <span style="display: flex; align-items: center; gap: 8px;"><span style="width: 10px; height: 10px; border-radius: 5px; background: ${
  this.color[0]
}"></span><span>${params[0].seriesName}: ${params[0].value}V</span></span>
              <span style="display: flex; align-items: center; gap: 8px;"><span style="width: 10px; height: 10px; border-radius: 5px; background: ${
  this.color[1]
}"></span><span>${params[1].seriesName}: ${params[1].value}%</span></span>
              <span style="display: flex; align-items: center; gap: 8px;"><span style="width: 10px; height: 10px; border-radius: 5px; background: ${
  this.color[2]
}"></span><span>${params[2].seriesName}: ${params[2].value}°C</span></span>
            </div>
            `
      }
    }

    this.xAxis = {
      type: 'category',
      // boundaryGap: false,
      data: Array(7)
        .fill(1)
        .map((_, idx) => {
          const d = moment()
          const day = idx ? d.subtract(idx, 'd') : d
          return day.format('M-DD')
        })
        .reverse(),
      axisTick: { show: false },
      axisLabel: {
        color: '#fff9',
        fontSize: 12,
        margin: 10
      },
      axisLine: {
        lineStyle: {
          color: '#fff3'
        }
      }
    }

    this.yAxis = [
      {
        name: '电流/A    ',
        nameTextStyle: { align: 'right', fontSize: 10, color: '#fff9' },
        type: 'value',
        splitNumber: 4,
        onZero: true,
        position: 'left',
        offset: 28,
        axisTick: { show: false },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#5982B2',
            width: 1
          }
        },
        axisLabel: {
          color: '#fff9',
          fontSize: 10,
          formatter: '{value}%'
        },
        splitLine: {
          show: false,
          lineStyle: {
            color: '#fff1',
            type: 'dotted'
          }
        }
      },
      {
        name: '  电压/V  ',
        nameTextStyle: { align: 'right', fontSize: 10, color: '#fff9' },
        type: 'value',
        splitNumber: 4,
        axisTick: { show: false },
        onZero: true,
        position: 'left',
        offset: 0,
        axisLine: {
          show: true,
          lineStyle: {
            color: '#5982B2',
            width: 1
          }
        },
        axisLabel: {
          color: '#fff9',
          fontSize: 10
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#fff3',
            type: 'dotted'
          }
        }
      },
      {
        name: '        温度',
        nameTextStyle: { align: 'left', color: '#fff9', fontSize: 10 },
        axisTick: { show: false },
        axisLine: {
          show: false,
          lineStyle: {
            color: '#fff9',
            width: 1
          }
        },
        // min: 'dataMin',
        min: 20,
        max: 50,
        type: 'value',
        splitNumber: 4,
        splitLine: {
          show: false,
          lineStyle: {
            color: '#fff1',
            type: 'dotted'
          }
        },
        axisLabel: {
          color: '#fff9',
          fontSize: 10,
          formatter: '{value}°C'
        }
      }
    ]

    this.series = [
      {
        name: '电压',
        type: 'line',
        yAxisIndex: 1,
        // smooth: true,
        emphasis: {
          focus: 'series'
        },
        data: Array(7)
          .fill(1)
          // .map(_ => Random.integer(30, 100)),
          .map(_ => Random.integer(360, 390)),
        symbol: 'circle',
        symbolSize: 0.2,
        showSymbol: false,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: '#E0209466' // 0% 处的颜色
              },
              {
                offset: 1,
                color: 'transparent' // 100% 处的颜色
              }
            ],
            global: false // 缺省为 false
          }
        }
      },
      {
        name: '电流',
        type: 'line',
        yAxisIndex: 0,
        // smooth: true,
        emphasis: {
          focus: 'series'
        },
        data: Array(7)
          .fill(1)
          .map(_ => Random.integer(76, 85)),
        // .map(_ => Random.integer(30, 100)),
        symbol: 'circle',
        symbolSize: 0.2,
        showSymbol: false,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: '#F0D63C66' // 0% 处的颜色
              },
              {
                offset: 1,
                color: 'transparent' // 100% 处的颜色
              }
            ],
            global: false // 缺省为 false
          }
        }
      },
      {
        name: '电缆温度',
        type: 'line',
        yAxisIndex: 2,
        // smooth: true,
        emphasis: {
          focus: 'series'
        },
        data: Array(7)
          .fill(1)
          // .map(_ => Random.integer(20, 55)),
          .map(_ => Random.integer(36, 45)),
        symbol: 'circle',
        symbolSize: 0.2,
        showSymbol: false,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: '#1A99FF66' // 0% 处的颜色
              },
              {
                offset: 1,
                color: 'transparent' // 100% 处的颜色
              }
            ],
            global: false // 缺省为 false
          }
        }
      }
    ]
  }

  get option() {
    return this
  }

  optionFilter(option, calcSize = () => {} /** callback */) {
    let newOption
    if (Array.isArray(option)) {
      newOption = []
      option.forEach(item => {
        newOption.push(this.optionFilter(item, calcSize))
      })
      return newOption
    } else if (typeof option === 'object') {
      newOption = {}
      for (const key in option) {
        if (key === 'colorStops') newOption[key] = option[key]
        else if (
          typeof option[key] === 'number' /** 过滤不做变化的属性 */ &&
          ['splitNumber', 'x', 'x2', 'min', 'max', 'y', 'y2', 'yAxisIndex', 'xAxisIndex'].indexOf(key) === -1
        ) {
          newOption[key] = calcSize(option[key])
        } else newOption[key] = this.optionFilter(option[key], calcSize)
      }
      return newOption
    } else {
      newOption = calcSize(option)
      return option
    }
  }
}

export default {
  name: 'DianLineChart',
  mixins: [resize],
  /** Fn.1: 保证全屏切换时也刷新图表 ，应该在每个父组件为flex:1的echarts组件里都加上，以确保能正确地伸缩 */
  inject: ['resizeStatus'],
  /** End Fn.1 */
  props: {
    id: {
      type: String,
      default: 'default-dian-line-chart'
    }
  },
  data() {
    return {
      chart: null,
      option: null
    }
  },
  computed: {
    shouldResize() {
      return this.resizeStatus()
    }
  },
  watch: {
    shouldResize(val, oldVal) {
      setTimeout(() => {
        this.chart.resize()
      }, 250)
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (!this.chart) this.chart = echarts.init(this.$refs['techy-line-chart'])
      this.setChartOption()
    })
  },
  beforeDestroy() {
    if (this.chart) this.chart.dispose()
    this.chart = null
  },
  methods: {
    calcSize(num) {
      const beilv = document.documentElement.style.getPropertyValue('--beilv')
      return num * beilv
    },
    setChartOption() {
      const cOption = new ChartOption()
      this.chart.setOption(cOption.optionFilter(cOption.option, this.calcSize))
    }
  }
}
</script>
<style scoped>
.techy-chart {
  height: 100%;
  width: 100%;
}

.techy-chart >>> div {
  width: 100% !important;
  height: 100% !important;
}
</style>
