<script setup lang="ts">
import studyAnalysisApi from '@/api/studyAnalysis'
import * as echarts from 'echarts/core'
import { LegendComponent, TooltipComponent } from 'echarts/components'
import { PieChart } from 'echarts/charts'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import SelectTime from './SelectTime.vue'
import KnowledgeList from './KnowledgeList.vue'
import { $font_color } from '@/styles/variate'

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

const emits = defineEmits(['change'])

echarts.use([TooltipComponent, LegendComponent, PieChart, CanvasRenderer, LabelLayout])
let myChart: any
let myChartBar: any
watch(
  () => props.subjectId,
  nv => {
    getDuration(true)
  },
)
const chartDomPie = ref() // 饼图
const chartDomBar = ref() // 柱状图
const showData = ref({
  bar: {
    knownChangeNum: 0,
    knownNum: 0,
    masteredChangeNum: 0,
    masteredNum: 0,
    studyDate: '',
    unKnownChangeNum: 0,
    unKnownNum: 0,
  },
  knowledgeList: [
    {
      answerCount: 0,
      correctCount: 0,
      knowledgeName: '',
      masteryDegree: 0,
      recommendedNum: 0,
    },
  ],
  ringList: [
    {
      count: '',
      masteryDegree: '',
      percentage: '',
      totalCount: '',
    },
  ],
})
const dateType = ref(0)
const showLoading = ref(false)
const showLoading2 = ref(false)

function getSizeTransform(size: number): number {
  return Math.floor((props.windowWidth * size) / 1920)
}

function initChartPie() {
  myChart = echarts.init(chartDomPie.value)
  const option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      icon: 'circle',
      bottom: '0%',
      left: 'center',
      itemHeight: getSizeTransform(22),
      itemGap: getSizeTransform(40),
      itemStyle: {
        decal: {
          symbol: 'pin',
        },
      },
      textStyle: {
        fontSize: getSizeTransform(30),
        padding: [0, getSizeTransform(8)],
      },
    },
    series: [
      {
        name: '知识图谱统计',
        type: 'pie',
        radius: ['30%', '70%'],
        data: [
          {
            value:
              showData.value.ringList.find(item => Number(item.masteryDegree) === 3)?.count || 0,
            name: '熟悉',
            itemStyle: {
              color: '#0CA8E5',
            },
          },
          {
            value:
              showData.value.ringList.find(item => Number(item.masteryDegree) === 2)?.count || 0,
            name: '掌握',
            itemStyle: {
              color: '#8AC500',
            },
          },
          {
            value:
              showData.value.ringList.find(item => Number(item.masteryDegree) === 1)?.count || 0,
            name: '陌生',
            itemStyle: {
              color: '#F45151',
            },
          },
          {
            value:
              showData.value.ringList.find(item => Number(item.masteryDegree) === 0)?.count || 0,
            name: '待点亮',
            itemStyle: {
              color: '#B6B6B6',
            },
            emphasis: {
              itemStyle: {
                color: '#B6B6B6',
              },
            },
            label: {
              color: '#999',
            },
            labelLine: {
              lineStyle: {
                color: '#999',
              },
            },
          },
        ],
        label: {
          // formatter: '{name|{b}}\n{time|{c} 小时}',
          alignTo: 'labelLine',
          formatter: '{d}%\n',
          fontSize: getSizeTransform(30),
          color: 'inherit',
        },
        labelLine: {
          length: getSizeTransform(20),
          length2: getSizeTransform(20),
          lineStyle: {
            width: getSizeTransform(2),
          },
        },

        labelLayout: function (params: anyObj) {
          const isLeft = params.labelRect.x < myChart.getWidth() / 2
          const points = params.labelLinePoints
          points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width
          return {
            labelLinePoints: points,
          }
        },
      },
    ],
  }

  option && myChart.setOption(option)
}

function initChartBar() {
  myChartBar = echarts.init(chartDomBar.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    legend: {
      itemHeight: getSizeTransform(22),
      itemGap: getSizeTransform(40),
      itemStyle: {
        decal: {
          symbol: 'pin',
        },
      },
      textStyle: {
        fontSize: getSizeTransform(30),
        padding: [0, getSizeTransform(8)],
      },
      formatter: '123123',
    },
    xAxis: [
      {
        type: 'category',
        data: ['陌生数', '熟悉数', '掌握数'],
        axisLine: {
          show: true,
          lineStyle: {
            color: '#8A94FD70',
            width: getSizeTransform(4),
          },
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          margin: getSizeTransform(20),
          color: '#666666',
          fontSize: getSizeTransform(30),
        },
        zlevel: 5,
      },
    ],
    yAxis: [
      {
        type: 'value',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#8A94FD50',
            width: getSizeTransform(4),
          },
        },
        axisLabel: {
          margin: 50,
          align: 'center',
          verticalAlign: 'middle',
          color: '#666666',
          fontSize: getSizeTransform(30),
          lineHeight: getSizeTransform(45),
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            type: [5, 10],
            color: 'rgba(138, 148, 253, 0.25)',
            width: 2,
          },
        },
        zlevel: 2,
      },
    ],
    series: [
      {
        name: '',
        type: 'bar',
        barWidth: '32%',
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
          color: $font_color,
          fontSize: getSizeTransform(32),
        },
        data: [
          {
            value: Math.abs(showData.value.bar.unKnownChangeNum),
            itemStyle: {
              color: showData.value.bar.unKnownChangeNum > 0 ? '#3FD15F' : '#F94A55',
            },
          },
          {
            value: Math.abs(showData.value.bar.knownChangeNum),
            itemStyle: {
              color: showData.value.bar.knownChangeNum > 0 ? '#3FD15F' : '#F94A55',
            },
          },
          {
            value: Math.abs(showData.value.bar.masteredChangeNum),
            itemStyle: {
              color: showData.value.bar.masteredChangeNum > 0 ? '#3FD15F' : '#F94A55',
            },
          },
        ],
      },
    ],
  }
  option && myChartBar.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

  return isminute ? m : h
}

function getDuration(isFirst = false) {
  if (isFirst) {
    showLoading2.value = true
  }
  showLoading.value = true
  studyAnalysisApi
    .getReportKnowledge({
      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 (isFirst) {
        myChart?.dispose()
      }
      myChartBar?.dispose()
      setTimeout(() => {
        if (isFirst) {
          initChartPie()
        }
        initChartBar()
      })
    })
    .finally(() => {
      showLoading.value = showLoading2.value = false
    })
}
</script>
<template>
  <div class="data-content">
    <div class="data-title">知识图谱统计</div>
    <div v-if="showLoading2" class="chart loading">
      <Empty type="loading" />
    </div>
    <div v-else ref="chartDomPie" class="chart"></div>
    <div class="nav">
      <SelectTime v-model="dateType" @change="getDuration()"></SelectTime>
    </div>
    <div class="list-title">我的知识图谱变化情况</div>
    <div class="bar-box">
      <div class="top-legend">
        <div class="add">增加</div>
        <div class="rev">减少</div>
      </div>
      <div v-if="showLoading" class="chartBar loading">
        <Empty type="loading" />
      </div>
      <div v-else ref="chartDomBar" class="chartBar"></div>
    </div>
    <div class="list-title">已学知识点及掌握程度</div>
    <KnowledgeList :dataList="showData.knowledgeList"></KnowledgeList>
  </div>
</template>

<style lang="scss" scoped>
//
.chart {
  width: 720;
  height: 51.67vh;
  margin: 0 auto;
}
.nav {
  display: flex;
  justify-content: center;
  margin-top: 6vh;
}
.list-title {
  margin-top: 5.83vh;
  color: $font-color;
  text-align: center;
  font-size: 2.67vh;
  font-style: normal;
  font-weight: 600;
  line-height: normal;
}
.bar-box {
  width: 1300px;
  height: 56.67vh;
  margin: 3.33vh auto 0;
  padding-top: 4.17vh;
  position: relative;
  .top-legend {
    position: absolute;
    top: 1.67vh;
    width: 100%;
    display: flex;
    justify-content: center;
    color: #666;
    font-size: 2.33vh;
    line-height: 3.5vh;
    .add,
    .rev {
      position: relative;
      width: 102px;
      text-align: right;
      &::before {
        content: '';
        height: 0.42vh;
        width: 30px;
        position: absolute;
        left: 5px;
        top: 50%;
        transform: translateY(-50%);
        background-color: #f94a55;
      }
    }
    .add {
      margin-right: 78px;
      &::before {
        background-color: #3fd15f;
      }
    }
  }
}
.chartBar {
  width: 100%;
  height: 52.5vh;
}
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
