import { defineComponent, onMounted, reactive, watch } from 'vue'
import { Image } from 'vant'
import styles from './index.module.less'
import arrowLine from '../images/week/icon-arrow-line.png'
import arrowPoint from '../images/icon-arrow-point.png'
import teacherArrowLine from '../images/month/teacher-icon-arrow-line.png'
import * as echarts from 'echarts/core'
import {
  TitleComponent,
  // 组件类型的定义后缀都为 ComponentOption
  TooltipComponent,
  GridComponent,
  // 数据集组件
  DatasetComponent,
  // 内置数据转换器组件 (filter, sort)
  TransformComponent,
  LegendComponent,
  ToolboxComponent,
  DataZoomComponent
} from 'echarts/components'
import { BarChart } from 'echarts/charts'
import { PieChart } from 'echarts/charts'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { reportCourseType } from '../week-report'
import OEmpty from '@/components/o-empty'
// type EChartsOption = echarts.EChartsOption

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

export default defineComponent({
  name: 'orchestra-num',
  props: {
    type: {
      type: String,
      default: 'week'
    },
    reportData: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props) {
    const forms = reactive({
      total: 0,
      valueList: []
    })

    watch(
      () => props.reportData,
      () => {
        handleInit()
      }
    )

    let myChart: any
    const handleInit = () => {
      if (myChart) {
        myChart.dispose()
      }

      const data = props.reportData || {}
      const titleList: any = []
      const valueList: any = []
      for (const i in data) {
        if (i === 'TOTAL') {
          forms.total = data[i]
        } else {
          const value = data[i]
          if (Array.isArray(value)) {
            value.forEach((v: any) => {
              titleList.push(v.name)
              valueList.push(v.value)
            })
          }
        }
      }
      forms.valueList = valueList

      const chartDom = document.getElementById('classEcharts')
      myChart = echarts.init(chartDom as HTMLDivElement)
      const option = {
        tooltip: {
          trigger: 'axis',
          confine: true,
          axisPointer: {
            type: 'shadow',
            label: {
              formatter: (params: any) => {
                if (params.value.length > 16) {
                  return params.value.substring(0, 16) + '...'
                }
                return params.value
              }
            }
          },
          textStyle: {
            color: '#131415',
            width: 100,
            overflow: 'truncate'
          }
        },
        dataZoom: [
          {
            type: 'inside',
            realtime: true,
            startValue: 0,
            endValue: 4,
            filterMode: 'none',
            zoomLock: true,
            throttle: 100
          }
        ],
        xAxis: {
          type: 'category',
          data: titleList,
          axisLabel: {
            interval: 0,
            fontSize: 9,
            color: '#333',
            width: 54,
            formatter: (value: any) => {
              let ret = '' // 拼接加\n返回的类目项
              const valLength = value.length // X轴类目项的文字个数
              const rowN = Math.ceil(valLength / 6) // 类目项需要换行的行数
              if (rowN > 1) {
                ret =
                  value.substring(0, 6) +
                  '\n' +
                  value.substring(6, 11) +
                  (valLength > 11 ? '... ' : '')
                return ret
              } else {
                return value + '\n' //+ '{b|添加}'
              }
            }
          },
          axisLine: {
            lineStyle: {
              color: '#D6D6D6'
            }
          }
        },
        yAxis: {
          type: 'value',
          minInterval: 1
        },
        grid: {
          left: 0,
          top: 22,
          right: 0,
          bottom: 12,
          containLabel: true
        },
        series: [
          {
            name: '本周训练',
            type: 'bar',
            showBackground: false,
            barWidth: 20,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#69DCE8' },
                { offset: 0.5, color: '#E5CEFB' },
                { offset: 1, color: '#58A2FF' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#69DCE8' },
                  { offset: 0.5, color: '#E5CEFB' },
                  { offset: 1, color: '#58A2FF' }
                ])
              }
            },
            label: {
              show: true,
              position: 'top',
              fontSize: 10,
              color: '#777'
            },
            data: valueList
          }
        ]
      }
      option && myChart.setOption(option)
    }

    onMounted(() => {
      handleInit()
    })

    return () => (
      <div class={[styles.trainSection, props.type === 'month' ? styles.teacherTrainSection : '']}>
        <div class={styles.trainTitle}>
          <div class={styles.name}>
            <Image
              src={props.type === 'month' ? teacherArrowLine : arrowLine}
              class={styles.allowLine}
            />
            训练课程
          </div>
          <div class={styles.countNums}>
            <Image src={arrowPoint} class={styles.arrowPoint} />
            乐团累计总课时<span>{forms.total}</span>课时
          </div>
        </div>

        <div class={styles.trainSectionContent}>
          <div class={styles.tContent}>
            <div class={styles.calssEchartTitle}>
              <span class={styles.unit}>单位：课时</span>
              <span class={styles.unitType}>本{props.type === 'month' ? '月' : '周'}训练</span>
            </div>

            <div class={styles.echartsContainer}>
              <div id="classEcharts" class={styles.classEcharts}></div>
              {forms.valueList.length <= 0 && (
                <div class={styles.oEmtpy}>
                  <OEmpty classImgSize={'SMALL'} type="emptyDefault" tips={'暂无数据'} />
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    )
  }
})
