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,
  TooltipComponent,
  GridComponent,
  // 数据集组件
  DatasetComponent,
  // 内置数据转换器组件 (filter, sort)
  TransformComponent,
  LegendComponent,
  ToolboxComponent,
  DataZoomComponent
} from 'echarts/components'
import { LineChart } 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,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
  ToolboxComponent,
  LegendComponent,
  DataZoomComponent,
  LineChart
])

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

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

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

      const data = props.reportData || {}
      const seriesList: any = []
      const titleList: any = []
      const valueList: any = []

      for (const i in data) {
        if (i === 'TOTAL') {
          forms.total = Math.ceil(data[i] * 100)
        } else {
          // titleList.push(reportCourseType[i])
          // valueList.push(data[i])
          const value = data[i]
          if (Array.isArray(value)) {
            value.forEach((v: any) => {
              titleList.push(v.name)
              valueList.push(v.value)
            })
          }
        }
      }

      const valueList2: any = []
      const dataNot = props.reportDataNot || {}
      for (const i in dataNot) {
        if (i === 'TOTAL') {
          forms.total2 = Math.ceil(dataNot[i] * 100)
        } else {
          const value = dataNot[i]
          if (Array.isArray(value)) {
            value.forEach((v: any) => {
              // titleList.push(v.name)
              valueList2.push(v.value)
            })
          }
          // valueList2.push(dataNot[i])
        }
      }

      forms.valueList = [...valueList, ...valueList2]

      if (forms.type.includes('YES')) {
        seriesList.push({
          name: '出勤课时数',
          type: 'bar',
          stack: 'work',
          showBackground: false,
          barWidth: 20,
          itemStyle: {
            color: '#5EA4FF'
          },
          label: {
            show: false,
            // position: 'top',
            fontSize: 10,
            color: '#777777'
          },
          data: valueList
        })
      }
      if (forms.type.includes('NOT')) {
        seriesList.push({
          name: '未出勤课时数',
          type: 'bar',
          stack: 'work',
          showBackground: false,
          barWidth: 20,
          itemStyle: {
            color: '#69DDE8'
          },
          label: {
            show: false,
            position: 'top',
            fontSize: 10,
            color: '#777777'
          },
          data: valueList2
        })
      }

      const chartDom = document.getElementById('teacherEcharts')
      myChart = echarts.init(chartDom as HTMLDivElement)
      const option = {
        dataZoom: [
          {
            type: 'inside',
            realtime: true,
            startValue: 0,
            endValue: 4,
            filterMode: 'none',
            zoomLock: true
          }
        ],
        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
        },
        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'
          }
        },
        grid: {
          left: 0,
          top: 22,
          right: 0,
          bottom: 12,
          containLabel: true
        },
        series: seriesList
      }

      option && myChart.setOption(option)
    }

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

    return () => (
      <div
        class={[
          styles.trainSection,
          props.type === 'month' ? styles.teacherTrainSection : '',
          styles.teacherSection
        ]}
      >
        <div class={styles.trainTitle}>
          <div class={styles.name}>
            <Image
              src={props.type === 'month' ? teacherArrowLine : arrowLine}
              class={styles.allowLine}
            />
            本{props.type === 'month' ? '月' : '周'}伴学老师出勤
          </div>
          <div class={styles.countNums}>
            <Image src={arrowPoint} class={styles.arrowPoint} />
            总出勤率
            <span
              style={{
                color: forms.total > 59 ? '#42FFE2' : props.type === 'month' ? '#FF99A2' : '#FF7C88'
              }}
            >
              {forms.total}
            </span>
            %
          </div>
        </div>

        <div class={styles.trainSectionContent}>
          <div class={styles.tContent}>
            <div class={styles.calssEchartTitle}>
              <span class={styles.unit}>单位：课时(节)</span>
              <div>
                <span
                  class={[styles.attendType, forms.type.includes('YES') ? styles.attendActive : '']}
                  onClick={() => {
                    // forms.type = 'target'
                    const index = forms.type.indexOf('YES')
                    if (index > -1) {
                      forms.type.splice(index, 1)
                    } else {
                      forms.type.push('YES')
                    }
                    handleInit()
                  }}
                >
                  出勤课时数
                </span>
                <span
                  class={[
                    styles.attendType,
                    forms.type.includes('NOT') ? styles.attendActive2 : ''
                  ]}
                  onClick={() => {
                    // forms.type = 'submitted'
                    const index = forms.type.indexOf('NOT')
                    if (index > -1) {
                      forms.type.splice(index, 1)
                    } else {
                      forms.type.push('NOT')
                    }
                    handleInit()
                  }}
                >
                  未出勤课时数
                </span>
              </div>
            </div>

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