<template>
  <a-spin :loading="loading" style="width: 100%">
    <a-card
      class="general-card"
      :header-style="{ paddingBottom: 0 }"
      :body-style="{
        paddingTop: '20px'
      }"
      title="项目计划统计"
    >
      <template #extra>
        <a-radio-group
          v-model="dateType"
          type="button"
          @change="v => filterData(v as number)"
        >
          <a-radio :value="0"> 本年 </a-radio>
          <a-radio :value="1"> 近一月 </a-radio>
          <a-radio :value="2"> 近一周 </a-radio>
        </a-radio-group>
      </template>
      <Chart height="320px" :option="chartOption" />
    </a-card>
  </a-spin>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { LineSeriesOption } from 'echarts'
import useLoading from '@/hooks/loading'
import useChartOption from '@/hooks/chart-option'
import { ToolTipFormatterParams } from '@/types/echarts'
import { AnyObject, ProjectPlanStatReqParams } from '@/types/dashboard'
import { getProjectPlanStat } from '@/api/dashboard/project'
import {
  endOfYear,
  format,
  startOfYear,
  eachDayOfInterval,
  startOfDay,
  subMonths,
  subWeeks
} from 'date-fns'

const dateType = ref(2)
const totalCount = ref<any[]>([])
const inCompleteCount = ref<any[]>([])
const delayedCount = ref<any[]>([])
const delayRate = ref<any[]>([])
const xAxisStat = ref<string[]>([])
const requestData = reactive<{
  beginAt: Date
  endAt: Date
  dateType: number
}>({
  dateType: 0,
  beginAt: subWeeks(new Date(), 1),
  endAt: startOfDay(new Date())
})
const units = ['个', '个', '个', '%']

function graphicFactory(side: AnyObject) {
  return {
    type: 'text',
    bottom: '8',
    ...side,
    style: {
      text: '',
      textAlign: 'center',
      fill: '#4E5969',
      fontSize: 12
    }
  }
}
const { loading, setLoading } = useLoading(true)
const graphicElements = ref([
  graphicFactory({ left: '2.6%' }),
  graphicFactory({ right: 0 })
])

const generateSeries = (
  name: string,
  lineColor: string,
  itemBorderColor: string,
  data: number[]
): LineSeriesOption => {
  return {
    name,
    // eslint-disable-next-line no-sparse-arrays
    data,
    type: 'line',
    smooth: true,
    connectNulls: true,
    symbol: 'circle',
    symbolSize: 8,
    itemStyle: {
      color: lineColor
    },
    emphasis: {
      focus: 'series',
      itemStyle: {
        color: lineColor,
        borderWidth: 2,
        borderColor: itemBorderColor
      }
    },
    lineStyle: {
      width: 2,
      color: lineColor
    },
    showSymbol: false,
    areaStyle: {
      opacity: 0.1,
      color: lineColor
    }
    // label: {
    //   show: true,
    //   formatter: params => {
    //     // 当数据值为 0 时，不显示标签
    //     return params.value === 0 ? '' : params.value
    //   }
    // }
  }
}

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.seriesName}</span>
          </p>
          <span class="tooltip-value">${
            el.value === 0 || el.value === null || el.value === undefined
              ? '-'
              : el.value.toLocaleString()
          }${
        el.value === 0 || el.value === null || el.value === undefined
          ? ''
          : units[el.componentIndex]
      }</span>
        </div>`
    })
    .reverse()
    .join('')
}

const { chartOption } = useChartOption(dark => {
  return {
    legend: {
      show: true,
      textStyle: {
        color: dark ? '#fff' : '#333'
      }
    },
    grid: {
      left: '2.6%',
      right: '0',
      top: '40',
      bottom: '30'
    },
    xAxis: {
      //   boundaryGap: ['20%', '20%'],
      type: 'category',
      data: xAxisStat.value,
      axisLine: {
        show: true
      },
      axisTick: {
        show: true
      },
      splitLine: {
        show: true
      },
      axisPointer: {
        show: true,
        lineStyle: {
          color: '#23ADFF',
          width: 2
        }
      }
    },
    yAxis: {
      //   boundaryGap: ['5%', '5%'],
      type: 'value',
      axisLine: {
        show: true
      },
      splitLine: {
        lineStyle: {
          color: dark ? '#2E2E30' : '#F2F3F5'
        }
      }
    },
    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'
    },
    graphic: {
      elements: graphicElements.value
    },
    series: [
      generateSeries(
        '总任务数',
        'rgb(22, 93, 255)',
        'rgb(232, 243, 255)',
        totalCount.value
      ),
      generateSeries(
        '未完成任务数',
        '#F77234',
        '#FFE4BA',
        inCompleteCount.value
      ),
      generateSeries('任务延期数', '#33D1C9', '#E8FFFB', delayedCount.value),
      generateSeries('任务延期率', '#722ED1', '#F5E8FF', delayRate.value)
    ]
  }
})

const getDataStat = async () => {
  try {
    xAxisStat.value = []
    totalCount.value = []
    inCompleteCount.value = []
    delayedCount.value = []
    delayRate.value = []
    setLoading(true)
    const { beginAt, endAt } = requestData
    const params: ProjectPlanStatReqParams = {
      begin_at: format(beginAt, 'yyyy-MM-dd'),
      end_at: format(endAt, 'yyyy-MM-dd')
    }
    const xValue = eachDayOfInterval({
      start: beginAt,
      end: endAt
    }).map(item => {
      return format(item, 'yyyy-MM-dd')
    })
    xAxisStat.value = xValue
    const { list } = await getProjectPlanStat(params)
    xValue.map(item => {
      const data = list.find(l => l.ts === item)
      if (data) {
        totalCount.value.push(data.total_count)
        inCompleteCount.value.push(data.incomplete_count)
        delayedCount.value.push(data.delayed_count)
        delayRate.value.push(data.delay_rate)
      } else {
        totalCount.value.push(null)
        inCompleteCount.value.push(null)
        delayedCount.value.push(null)
        delayRate.value.push(null)
      }
      return item
    })
  } catch (e) {
    setLoading(false)
  } finally {
    setLoading(false)
  }
}

const filterData = (value: number) => {
  console.log(value)
  switch (value) {
    case 1:
      requestData.beginAt = subMonths(new Date(), 1)
      requestData.endAt = startOfDay(new Date())
      break
    case 2:
      requestData.beginAt = subWeeks(new Date(), 1)
      requestData.endAt = startOfDay(new Date())
      break
    default:
      requestData.beginAt = startOfYear(new Date())
      requestData.endAt = endOfYear(new Date())
      break
  }
  getDataStat()
}
// const fetchData = async () => {
//   setLoading(true)
//   try {
//     const chartData = getLineData()
//     chartData.forEach((el: { x: string; y: number }, idx: number) => {
//       xAxis.value.push(el.x)
//       chartsData.value.push(el.y)
//       if (idx === 0) {
//         graphicElements.value[0].style.text = el.x
//       }
//       if (idx === chartData.length - 1) {
//         graphicElements.value[1].style.text = el.x
//       }
//     })
//   } catch (err) {
//     // you can report use errorHandler or other
//   } finally {
//     setLoading(false)
//   }
// }
// fetchData()
getDataStat()
</script>

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