<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 } from '../hooks'

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

const emits = defineEmits(['change'])
echarts.use([
  LegendComponent,
  GridComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
  TooltipComponent,
])
let myChart: any

const chartDom = ref()
const showData = ref({
  correctRate: '',
  correctedNum: '',
  correctedRatioNum: '',
  errorNum: '',
  errorRatioNum: '',
  totalNum: '',
  totalRatioNum: '',
  recordVoList: [
    {
      correctRate: 0,
      correctedErrors: 0,
      studyDate: '',
      totalErrors: 0,
      totalQuestions: 0,
    },
  ],
})
const englishShowData = ref({
  beforeSentenceCount: 0,
  beforeSentenceWordCount: 0,
  sentenceCount: 0,
  sentenceWordCount: 0,
  rate: 0,
  statList: [
    {
      sentenceCount: 0,
      sentenceWordCount: 0,
      statTime: '',
    },
  ],
})
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 seriesStyle = {
    type: 'line',
    symbol: 'circle',
    symbolSize: getSizeTransform(12),
    smooth: true,
    selectedMode: 'single',
    tooltip: {
      trigger: 'item',
      formatter: (params: anyObj, ticket: string) => {
        return `<div class="tooltip">
                            <div style="font-size: 1.562vw; line-height: 2.343vw; color: #999">
                                ${dayjs(
                                  props.isEnglish
                                    ? englishShowData.value.statList[params.dataIndex].statTime
                                    : showData.value.recordVoList[params.dataIndex].studyDate,
                                ).format('YYYY.M.D')}
                            </div>
                            <div style="font-size: 1.666vw; line-height: 2.5vw; color: #666">
                               ${params.seriesName}：${params.data}
                            </div>
                        </div>
                        `
      },
    },
    blur: {
      lineStyle: {
        opacity: 1,
      },
      itemStyle: {
        opacity: 1,
      },
    },
    emphasis: {
      scale: 2,
      focus: 'series',
      itemStyle: {
        borderWidth: getSizeTransform(4),
        borderColor: 'white',
        color: '#8FCC00',
        borderType: 'solid',
      },
    },
  }
  const option = {
    tooltip: {
      show: true,
      trigger: 'axis',
      axisPointer: {
        z: 0,
        type: 'line',
        lineStyle: {
          color: '#8FCC00',
          width: getSizeTransform(4),
          type: 'solid',
        },
      },
    },
    legend: {
      selectedMode: false,
      textStyle: {
        fontSize: getSizeTransform(30),
        color: '#666',
        fontFamily: 'Alibaba Health',
      },
      itemGap: getSizeTransform(32),
      itemHeight: getSizeTransform(16),
      itemWidth: getSizeTransform(38),
      itemStyle: {
        borderWidth: getSizeTransform(4),
      },
      lineStyle: {
        width: getSizeTransform(4),
      },
    },
    xAxis: {
      type: 'category',
      data: props.isEnglish
        ? englishShowData.value.statList.map(item => dayjs(item.statTime).format('MM/DD'))
        : showData.value.recordVoList.map(item => 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: '#8A94FD50',
          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: [
      {
        ...seriesStyle,
        lineStyle: {
          color: '#FF7A6A',
          width: getSizeTransform(4),
        },
        itemStyle: {
          normal: {
            borderWidth: getSizeTransform(4),
            borderColor: '#FF7A6A',
            color: 'white',
            borderType: 'solid',
          },
        },

        name: '做题数',
        data: showData.value.recordVoList.map(item => item.totalQuestions),
      },
      {
        ...seriesStyle,
        lineStyle: {
          color: '#FED769',
          width: getSizeTransform(4),
        },
        itemStyle: {
          normal: {
            borderWidth: getSizeTransform(4),
            borderColor: '#FED769',
            color: 'white',
            borderType: 'solid',
          },
        },

        name: props.isEnglish ? '句子练习数' : '产生错题数',
        data: props.isEnglish
          ? englishShowData.value.statList.map(item => item.sentenceCount)
          : showData.value.recordVoList.map(item => item.totalErrors),
      },
      {
        ...seriesStyle,
        lineStyle: {
          color: '#8A94FD',
          width: getSizeTransform(4),
        },
        itemStyle: {
          normal: {
            borderWidth: getSizeTransform(4),
            borderColor: '#8A94FD',
            color: 'white',
            borderType: 'solid',
          },
        },

        name: props.isEnglish ? '阅读词汇量' : '订正错题数',
        data: props.isEnglish
          ? englishShowData.value.statList.map(item => item.sentenceWordCount)
          : showData.value.recordVoList.map(item => item.correctedErrors),
      },
    ],
  }
  if (props.isEnglish) {
    option.series.shift()
  }

  option && myChart.setOption(option)
}
function getDuration() {
  showLoading.value = true

  if (props.isEnglish) {
    studyAnalysisApi
      .getStatListByTimeFlag({
        startTime: [
          dayjs().format('YYYY-MM-DD'),
          dayjs().subtract(6, 'days').format('YYYY-MM-DD'),
          dayjs().subtract(30, 'days').format('YYYY-MM-DD'),
          null,
        ][dateType.value],
        endTime: dateType.value === 3 ? null : dayjs().add(1, 'days').format('YYYY-MM-DD'),
      })
      .then((res: any) => {
        for (const key in englishShowData.value) {
          englishShowData.value[key as keyof typeof englishShowData.value] = res.data.data[key]
        }
        if (!dateType.value) return
        setTimeout(() => {
          initChart()
        })
      })
      .finally(() => {
        showLoading.value = false
      })
    return
  }
  studyAnalysisApi
    .getReportError({
      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
      setTimeout(() => {
        initChart()
      })
    })
    .finally(() => {
      showLoading.value = false
    })
}
watch(
  () => props.subjectId,
  nv => {
    getDuration()
  },
  {
    immediate: true,
  },
)
</script>
<template>
  <div class="data-content">
    <div class="data-title">{{ isEnglish ? '语感统计' : '刷题统计' }}</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 || dateType === 3,
          isEnglish: isEnglish && (!dateType || dateType === 3),
        }"
      >
        <NumberCard
          v-if="!isEnglish"
          title="做题数"
          fill="rgba(255, 99, 80, 0.85)"
          fontColor="#BC2D37"
        >
          <div class="data-content-card-content">
            <span class="number">{{ showData.totalNum }}</span
            >道
            <Icon size="38" :name="getArrow(showData.totalNum, showData.totalRatioNum)"></Icon>
          </div>
        </NumberCard>
        <NumberCard
          :title="isEnglish ? '句子练习数' : '产生错题数'"
          fill="#FED769"
          fontColor="#A13C00"
        >
          <div class="data-content-card-content">
            <span class="number">{{
              isEnglish ? englishShowData.sentenceCount : showData.errorNum
            }}</span
            >{{ isEnglish ? '句' : '道' }}
            <Icon
              size="38"
              :name="
                isEnglish
                  ? getArrow(englishShowData.sentenceCount, englishShowData.beforeSentenceCount)
                  : getArrow(showData.errorNum, showData.errorRatioNum)
              "
            ></Icon>
          </div>
        </NumberCard>
        <NumberCard
          :title="isEnglish ? '阅读词汇量' : '订正错题数'"
          fill="#A7AEFFA1"
          fontColor="#2D39BC"
        >
          <div class="data-content-card-content">
            <span class="number">{{
              isEnglish ? englishShowData.sentenceWordCount : showData.correctedNum
            }}</span
            >{{ isEnglish ? '词' : '道' }}
            <Icon
              size="38"
              :name="
                isEnglish
                  ? getArrow(
                      englishShowData.sentenceWordCount,
                      englishShowData.beforeSentenceWordCount,
                    )
                  : getArrow(showData.correctedNum, showData.correctedRatioNum)
              "
            ></Icon>
          </div>
        </NumberCard>
        <NumberCard
          v-if="isEnglish ? !dateType || dateType === 3 : true"
          :title="isEnglish ? '正确率' : '答题正确率'"
          fill="#B8FC90"
          fontColor="#2F8A5B"
        >
          <div class="data-content-card-content">
            <span class="number">{{
              isEnglish ? (englishShowData.rate || 0) * 100 + '%' : showData.correctRate || '0%'
            }}</span>
          </div>
        </NumberCard>
      </div>
      <div v-if="dateType === 1 || dateType === 2" 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 {
      width: 800px;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      margin: 0 auto;
      .count-card-item {
        &:last-child {
          margin-right: 0;
        }
      }
    }
    &.isEnglish {
      width: 80%;
    }
  }
  .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;
}
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
