<script setup lang="ts">
import studyAnalysisApi from '@/api/studyAnalysis'
import * as echarts from 'echarts/core'
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components'
import { LineChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { UniversalTransition } from 'echarts/features'
import SelectTime from './SelectTime.vue'
import NumberCard from './NumberCard.vue'
import dayjs from '@/plugins/dayjs'

import { getArrow, timeTool } from '../hooks'

const props = withDefaults(
  defineProps<{
    subjectId: number
    userId: any
    windowWidth: number
  }>(),
  {
    subjectId: 0,
    userId: '',
    windowWidth: 1920,
  },
)

const emits = defineEmits(['change'])
echarts.use([
  LegendComponent,
  GridComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
  TooltipComponent,
])
let myChart: any
watch(
  () => props.subjectId,
  nv => {
    getDuration()
  },
)
const chartDom = ref()
const showData = ref({
  videoCount: '',
  videoCountRatio: '',
  videoTime: '',
  videoTimeRatio: '',
  videoRecordVoList: [
    {
      studyDate: '',
      videoCount: '0',
      videoTime: '0',
    },
  ],
})
const dateType = ref(0)

const showLoading = ref(false)
function getSizeTransform(size: number): number {
  return Math.floor((props.windowWidth * size) / 1920)
}
function initChart() {
  myChart = echarts.init(chartDom.value)
  const option = {
    tooltip: {
      show: true,
      trigger: 'axis',
      axisPointer: {
        z: 0,
        type: 'line',
        lineStyle: {
          color: '#8FCC00',
          width: getSizeTransform(4),
          type: 'solid',
        },
        shadowStyle: {},
      },
      formatter: (params: anyObj[], ticket: string) => {
        const time = Math.floor(
          Number(showData.value.videoRecordVoList[params[0].dataIndex].videoTime) / 60,
        )

        return `<div class="tooltip">
                            <div style="font-size: 1.562vw; line-height: 2.343vw; color: #999">
                                ${dayjs(showData.value.videoRecordVoList[params[0].dataIndex].studyDate).format('YYYY.M.D')}
                            </div>
                            <div style="font-size: 1.666vw; line-height: 2.5vw; color: #666">
                                观看视频时长：<br />${Math.floor(time / 60)}时${time === 60 ? 0 : time}分
                            </div>
                        </div>
                    `
      },
    },
    legend: {
      selectedMode: false,
      textStyle: {
        fontSize: getSizeTransform(30),
        color: '#666',
        fontFamily: 'Alibaba Health',
      },
      itemHeight: getSizeTransform(14),
    },
    xAxis: {
      type: 'category',
      // data: showData.value.videoRecordVoList.map(item => item.studyDate),
      data: showData.value.videoRecordVoList.map((item: anyObj) =>
        dayjs(item.studyDate).format('MM/DD'),
      ),
      boundaryGap: false,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#8A94FD',
          width: getSizeTransform(4),
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        margin: getSizeTransform(20),
        color: '#666666',
        fontWeight: '400',
        fontSize: getSizeTransform(30),
        fontFamily: 'Alibaba Health',
      },
      splitLine: {
        show: true,

        lineStyle: {
          color: '#8A94FD',
          opacity: 0.5,
          width: getSizeTransform(3),
        },
      },
    },
    yAxis: {
      nameGap: getSizeTransform(30),
      nameTextStyle: {
        color: '#666666',
        fontWeight: '400',
        fontSize: getSizeTransform(30),
        fontFamily: 'Alibaba Health',
      },
      type: 'value',
      scale: false,
      position: 'left',
      show: true,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#8A94FD',
          width: getSizeTransform(4),
        },
      },
      axisLabel: {
        margin: getSizeTransform(45),
        align: 'center',
        verticalAlign: 'middle',
        color: '#666666',
        fontWeight: '400',
        fontSize: getSizeTransform(30),
        fontFamily: 'Alibaba Health',
      },
      splitLine: {
        lineStyle: {
          color: '#8A94FD',
          opacity: 0.5,
          width: getSizeTransform(3),
        },
      },
    },
    series: [
      {
        name: '时长统计',
        symbol: 'circle',
        symbolSize: getSizeTransform(12),
        type: 'line',
        smooth: true,
        // selectedMode: 'single',
        lineStyle: {
          color: '#8A94FD',
          width: getSizeTransform(4),
        },
        itemStyle: {
          normal: {
            borderWidth: getSizeTransform(4),
            borderColor: '#8A94FD',
            color: 'white',
            borderType: 'solid',
          },
        },
        emphasis: {
          scale: 2,
          itemStyle: {
            borderWidth: getSizeTransform(4),
            borderColor: 'white',
            color: '#8FCC00',
            borderType: 'solid',
          },
        },
        data: showData.value.videoRecordVoList.map(item =>
          (Number(item.videoTime) / 60 / 60).toFixed(1),
        ),
      },
    ],
  }

  option && myChart.setOption(option)
}
// function timeTool(second: string | number, isminute = false) {
//     const seconds = Number(second);
//     let h: number | string = Math.floor(seconds / 3600);
//     let m: number | string = Math.floor((seconds % 3600) / 60);
//     // 补零
//     h = h < 10 ? '0' + h : h;
//     m = m < 10 ? '0' + m : m;
//     console.log('isminute ? m : h', isminute ? m : h);

//     return isminute ? m : h;
// }

function getDuration() {
  showLoading.value = true
  studyAnalysisApi
    .getReportvideo({
      dateType: dateType.value,
      subjectId: props.subjectId,
      userId: props.userId,
    })
    .then((res: any) => {
      for (const key in showData.value) {
        showData.value[key as keyof typeof showData.value] = res.data.data[key]
      }
      if (!dateType.value) return
      myChart?.dispose()
      setTimeout(() => {
        initChart()
      })
    })
    .finally(() => {
      showLoading.value = false
    })
}
</script>
<template>
  <div class="data-content">
    <div class="data-title">视频学习统计</div>

    <div class="nav">
      <SelectTime v-model="dateType" @change="getDuration"></SelectTime>
    </div>
    <div class="data-content-bottom">
      <div :class="{ 'data-content-card': true, isToday: !dateType }">
        <NumberCard title="已学视频" fill="#FED769" fontColor="#A13C00">
          <div class="data-content-card-content">
            <span class="number">{{ showData.videoCount }}</span
            >个
            <Icon size="38" :name="getArrow(showData.videoCount, showData.videoCountRatio)"></Icon>
          </div>
        </NumberCard>
        <NumberCard title="观看视频时长" fill="#A7AEFFA1" fontColor="#2D39BC">
          <div class="data-content-card-content">
            <span class="number">{{ timeTool(showData.videoTime) }}</span
            >时<span class="number">{{ timeTool(showData.videoTime, true) }}</span
            >分
            <Icon size="38" :name="getArrow(showData.videoTime, showData.videoTimeRatio)"></Icon>
          </div>
        </NumberCard>
      </div>
      <div v-if="dateType" class="right">
        <div class="title">观看视频时长</div>
        <div v-if="showLoading" class="chart loading">
          <Empty type="loading" />
        </div>
        <div v-else ref="chartDom" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
//
.data-content-bottom {
  display: flex;
  margin-top: 5.83vh;
  .data-content-card {
    .count-card-item {
      margin-top: 2.67vh;
    }
    &.isToday {
      display: flex;
      justify-content: center;
      margin: 0 auto;
      .count-card-item:first-child {
        margin-right: 32px;
      }
    }
  }
  .right {
    flex: 1;
    .title {
      color: $font-color;
      text-align: center;
      font-family: OPPOSans;
      font-size: 2.67vh;
      font-weight: 600;
      margin-bottom: 3.33vh;
    }
  }
}
.nav {
  display: flex;
  justify-content: center;
  margin: 6vh 0 1.67vh;
}

.chart {
  flex: 1;
  width: 100%;
  height: 53.17vh;
  margin: 0 auto;
}
</style>
