import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'

import * as echarts from 'echarts/core'
import { TooltipComponent, LegendComponent } from 'echarts/components'
import { PieChart } from 'echarts/charts'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { A6_APIgetList, A6_APIgetNum } from '@/store/action/A6statistics'
import { A6ListType } from './data'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import MyTable from '@/components/MyTable'

echarts.use([TooltipComponent, LegendComponent, PieChart, CanvasRenderer, LabelLayout])

function A6statistics() {
  const [JSnum, setJSNum] = useState(0)

  const initFu = useCallback(async () => {
    const res = await A6_APIgetNum()
    if (res.code === 0) {
      const list: A6ListType[] = res.data
      const obj = list.find(v => v.id === 7)
      if (obj) setJSNum(obj.pcs)

      // 去掉最后一个
      const listRes = list.filter(v => v.id !== 7)

      const maxNum = listRes.reduce((accumulator, currentObj) => accumulator + currentObj.pcs, 0)

      const data = listRes.map(c => ({ value: c.pcs, name: c.name }))

      const dom: HTMLDivElement = document.querySelector('.echBox')!
      const myChart = echarts.getInstanceByDom(dom) || echarts.init(dom)

      // 创建名称到数值的映射（用于图例显示）
      const nameToValueMap: any = {}
      data.forEach(item => {
        nameToValueMap[item.name] = item.value
      })

      const option = {
        tooltip: {
          trigger: 'item',
          show: true
        },
        legend: {
          // 图例移动到底部并竖向排列
          orient: 'vertical',
          bottom: '2%', // 距离底部5%的位置
          left: 'center', // 右侧定位
          itemGap: 15, // 图例项间距[6,8](@ref)
          itemHeight: 12, // 图例图标高度[6](@ref)

          // 自定义图例文本（显示名称+数值）
          formatter: function (name: string) {
            return `${name}: ${nameToValueMap[name]}`
          },
          textStyle: {
            fontSize: 14,
            rich: {
              value: {
                fontWeight: 'bold',
                color: '#1890ff'
              }
            }
          }
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '36%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'center',
              fontSize: 18,
              fontWeight: 'bold',
              color: '#333',
              formatter: `总访问量\n\n{c|${maxNum} 次}`,
              rich: {
                c: { color: '#1890ff' }
              }
            },
            // 修复中心文字消失问题[9,10](@ref)
            emphasis: {
              label: {
                show: true // 关键修改：悬停时保持中心文字显示
              },
              itemStyle: {
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ]
      }
      option && myChart.setOption(option)
    }
  }, [])

  useEffect(() => {
    initFu()
  }, [initFu])

  // 获取列表数据
  const dispatch = useDispatch()
  const { list } = useSelector((state: RootState) => state.A6statistics.info)

  useEffect(() => {
    dispatch(A6_APIgetList())
  }, [dispatch])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '访问次数',
        width: 200,
        render: (item: A6ListType) => item.pcs || 0
      }
    ]
  }, [])

  return (
    <div className={styles.A6statistics}>
      <div className='pageTitle'>数据统计</div>

      <div className='A6ll'>
        <div className='A6ll1'>
          <div className='A6llTit'>线上展馆访问量</div>

          {/* ech dom */}
          <div className='echBox'></div>
        </div>
        <div className='A6ll2'>
          <span>祭扫人次：</span>&emsp;{JSnum}人次
        </div>
      </div>
      <div className='A6rr'>
        <div className='A6rrTit'>馆藏文物</div>
        <MyTable
          yHeight={675}
          list={list}
          columnsTemp={[['txt', '藏品名称', 'name']]}
          lastBtn={tableLastBtn}
          pagingInfo={false}
        />
      </div>
    </div>
  )
}

const MemoA6statistics = React.memo(A6statistics)

export default MemoA6statistics
