import {
  defineComponent,
  nextTick,
  PropType,
  ref,
  watch
} from 'vue'
import styles from './index.module.less'
import * as echarts from 'echarts/core'
import {
  LineChart
  // LineSeriesOption
} from 'echarts/charts'
// import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  // 组件类型的定义后缀都为 ComponentOption
  // TitleComponentOption,
  TooltipComponent,
  // TooltipComponentOption,
  GridComponent,
  // 数据集组件
  DatasetComponent,
  // DatasetComponentOption,
  // 内置数据转换器组件 (filter, sort)
  // TransformComponent,
  LegendComponent,
  ToolboxComponent,
  DataZoomComponent
} from 'echarts/components'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { formatSecToHMS } from '..'

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  // TransformComponent,
  LabelLayout,
  // UniversalTransition,
  CanvasRenderer,
  // PieChart,
  ToolboxComponent,
  LegendComponent,
  DataZoomComponent,
  LineChart
])

const lineChartOption = (params: {
  xAxisData: any
  seriesData: any
  colors: {
    lineColor?: string
    startColor?: string
    endColor?: string
    unit?: string
  },
  splitNumber: number
}) => {
  return {
    title: {
      text: '单位：' + (params.colors.unit || '人'),
      textStyle: {
        color: '#777777',
        fontSize: 13,
        fontWeight: 400
      }
    },
    legend: { show: false },
    emphasis: { lineStyle: { width: 2 } },
    xAxis: {
      boundaryGap: true,
      data: params.xAxisData,
      type: 'category',
      axisLine: { lineStyle: { color: '#8C8C8C' } },
      lineStyle: { color: '#F2F2F2' },
      axisLabel: {
        margin: 16,
        // alignWithLabel: true,
        // inside: false
      },
      axisTick: {
        show: true,
        alignWithLabel: true
      },
      axisPointer: {
        handle: {
          show: true,
          size: [0, 0]
        }
      }
    },
    color: [
      params.colors.lineColor || '#2DC7AA'
      // '#FF6079'
      // '#2DC7AA',
      // '#FF602C',
      // '#91DD1C',
      // '#FFA92C',
      // '#BE7E2E',
      // '#1C96DD',
      // '#D22CFF',
      // '#FF3C3C',
      // '#1AEE3E',
      // '#00c9ff'
    ],
    series: [
      {
        lineStyle: { width: 2 },
        data: params.seriesData,
        symbol: 'circle',
        showSymbol: false,
        name: '购买次数',
        type: 'line',
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: params.colors.startColor || 'rgba(45, 199, 170, 0.23)'
                // 0% 处的颜色
              },
              {
                offset: 1,
                // 100% 处的颜色
                color: params.colors.endColor || 'rgba(45, 199, 170, 0)'
              }
            ]
          }
        },
        emphasis: { lineStyle: { width: 2 } }
      }
    ],
    grid: {
      bottom: '3%',
      containLabel: true,
      left: '4%',
      right: '5%',
      top: '40'
    },
    tooltip: {
      trigger: 'axis',
      alwaysShowContent: true,
      confine: true,
      formatter: function (params: any) {
        return params[0].name
      },
      position: function (point) {
        // 固定在顶部
        return [point[0], '10%']
      },
      backgroundColor: params.colors.lineColor || '#FF6079',
      boxShadow: 'none',
      borderWidth: 0,
      borderRadius: 24,
      padding: [1, 4],
      textStyle: {
        color: '#FFFFFF',
        fontSize: 12
      },
      extraCssText: 'z-index: 2;box-shadow: none;',
      axisPointer: {
        lineStyle: {
          color: params.colors.lineColor || '#FF6079'
        }
      }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        axisLine: { lineStyle: { color: '#8C8C8C' } },
        lineStyle: { color: ['#f2f2f2'], type: 'dashed' }
      },
      splitNumber: params.splitNumber || 5
    },
    dataZoom: [{ type: 'inside', throttle: 100 }],
    toolbox: { feature: { saveAsImage: { show: false } } }
  }
}
export default defineComponent({
  name: 'eChats-model',
  props: {
    obj: {
      type: Object,
      default: () => ({})
    },
    type: {
      type: String as PropType<'TIME' | 'NUM'>,
      default: 'TIME'
    }
  },
  setup(props) {
    const chartId = 'eChart_' + Date.now() + props.type
    const color = props.type === 'NUM' ? '#FF955D' : '#2DC7AA'
    const statisticCounts = ref({
      time: '' as any,
      count: 0 as any
    })
    let myChart: echarts.ECharts

    nextTick(() => {
      myChart = echarts.init(document.getElementById(chartId) as HTMLDivElement)
    })

    const _initData = () => {
      nextTick(() => {
        statisticCounts.value.time = props.obj.time || ''
        statisticCounts.value.count =
          props.type === 'NUM'
            ? props.obj.count
            : formatSecToHMS(props.obj.count || 0).all

        myChart.clear()
        lineChartOption &&
          myChart.setOption(
            lineChartOption({
              xAxisData: props.obj.xAxisData,
              seriesData: props.obj.yAxisData,
              colors: {
                lineColor: color,
                startColor:
                  props.type === 'NUM'
                    ? 'rgba(255, 149, 93, 0.23)'
                    : 'rgba(45, 199, 170, 0.23)',
                endColor:
                  props.type === 'NUM'
                    ? 'rgba(255, 149, 93, 0)'
                    : 'rgba(45, 199, 170, 0)',
                unit: props.type === 'NUM' ? '人' : '分钟'
              },
              splitNumber: props.obj.countMaxCount
            })
          )
        myChart.on('highlight', function (params: any) {
          const batch = params.batch || []
          // const options: any = myChart.getOption()

          batch.forEach((item: any) => {
            const batchIndex = item.dataIndex

            const count =
              props.type === 'NUM'
                ? props.obj.yAxisData[batchIndex]
                : formatSecToHMS(props.obj.yAxisData[batchIndex]?.[2] || 0).all
            const time = props.obj.xAxisData[batchIndex]
            statisticCounts.value = {
              count,
              time
            }
          })
        })

        // 可能出现多个时，图表同时渲染，提示有问题
        setTimeout(() => {
          const lastIndex = props.obj.xAxisData.length - 1
          myChart.dispatchAction({
            type: 'showTip',
            seriesIndex: 0, // 系列索引
            dataIndex: lastIndex // 数据索引
          })
        }, 0)
      })
    }

    nextTick(() => {
      myChart = echarts.init(document.getElementById(chartId) as HTMLDivElement)
      _initData()
    })

    watch(
      () => props.obj,
      () => {
        _initData()
      },
      {
        deep: true
      }
    )
    return () => (
      <div class={styles.eChartSection}>
        <div class={styles.eChartTitle}>
          <div class={styles.left}>
            <div class={styles.item} style={{ '--color': color } as any}>
              {/* <span class={styles.line}></span> */}
              {props.type === 'NUM' ? (
                <>
                  <span class={styles.text}>
                    {statisticCounts.value.time} 练习人数
                  </span>
                  <span class={styles.num}>
                    {statisticCounts.value.count || 0}人
                  </span>
                </>
              ) : (
                <>
                  <span class={styles.text}>
                    {statisticCounts.value.time} 练习时长
                  </span>
                  <span class={styles.num}>{statisticCounts.value.count}</span>
                </>
              )}
            </div>
          </div>
        </div>

        <div class={styles.eChart}>
          <div id={chartId} style="width: 100%; height: 100%;"></div>
        </div>
      </div>
    )
  }
})
