<template>
  <a-card class="general-card" title="我的工作">
    <Chart height="160px" :option="chartOption" />
  </a-card>
</template>

<script lang="ts" setup>
import { getWorkStat } from '@/api/project/work'
import useChartOption from '@/hooks/chart-option'
import { ToolTipFormatterParams } from '@/types/echarts'
import { onMounted, ref } from 'vue'

const workStat = ref<{
  units: string[]
  name: string[]
  values: number[]
}>({
  units: [],
  name: [],
  values: []
})

const tooltipItemsHtmlString = (items: ToolTipFormatterParams[]) => {
  return items
    .map(el => {
      return `<div class="content-panel">
          <p>
            <span style="background-color: ${
              el.color
            }" class="tooltip-item-icon"></span><span>${
        el.axisValueLabel
      }</span>
          </p>
          <span class="tooltip-value">${
            el.value === undefined ? 0 : el.value.toLocaleString()
          }${workStat.value.units[el.componentIndex]}</span>
        </div>`
    })
    .reverse()
    .join('')
}

const { chartOption } = useChartOption(isDark => {
  if (workStat.value.name.length === 0) {
    return {}
  }
  return {
    grid: {
      left: 80,
      right: 20,
      top: 0,
      bottom: 20
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        show: true,
        formatter(value: number, idx: number) {
          if (idx === 0) return String(value)
          return `${Number(value)}`
        }
      },
      splitLine: {
        lineStyle: {
          color: isDark ? '#484849' : '#E5E8EF'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: workStat.value.name,
      axisLabel: {
        show: true,
        color: '#4E5969'
      },
      axisTick: {
        show: true,
        length: 2,
        lineStyle: {
          color: '#A9AEB8'
        },
        alignWithLabel: true
      },
      axisLine: {
        lineStyle: {
          color: isDark ? '#484849' : '#A9AEB8'
        }
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter(params) {
        const [firstElement] = params as ToolTipFormatterParams[]
        return `<div>
              <p class="tooltip-title">${firstElement.axisValueLabel}</p>
              ${tooltipItemsHtmlString(params as ToolTipFormatterParams[])}
            </div>`
      },
      className: 'echarts-tooltip-diy'
    },
    series: [
      {
        data: workStat.value.values,
        type: 'bar',
        barWidth: 7,
        itemStyle: {
          color: '#4086FF',
          borderRadius: 4
        }
      }
    ]
  }
})

onMounted(async () => {
  const { list } = await getWorkStat()
  list.map(item => {
    workStat.value.values.push(item.value)
    workStat.value.name.push(item.name)
    workStat.value.units.push(item.unit)
    return item
  })
  // statList.value = list
})
</script>

<style scoped lang="less"></style>
