import React, { useCallback, useEffect } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { A2_APIgetlist } from '@/store/action/A2statistics'
import { Button } from 'antd'
import { RootState } from '@/store'
import { authorityFu } from '@/utils/authority'
import history from '@/utils/history'

import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import { MessageFu } from '@/utils/message'
import dayjs from 'dayjs'

function A2statistics() {
  const dispatch = useDispatch()

  const getListFu = useCallback(() => {
    dispatch(A2_APIgetlist())
  }, [dispatch])

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

  const info = useSelector((state: RootState) => state.A2statistics.info)

  // 导出表格函数
  const exportToExcel = useCallback(() => {
    if (!info.total || !info.data.length) {
      MessageFu.warning('暂无数据可导出')
      return
    }

    try {
      // 准备数据
      const worksheetData = [
        ['分类', '子分类', '数量'], // 表头
        ['藏品总账数量', '', info.total || 0] // 总账数量
      ]

      // 添加分类数据
      info.data.forEach(item => {
        item.son.forEach((son, index) => {
          worksheetData.push([
            index === 0 ? item.name : '', // 只有第一行显示分类名
            son.name,
            son.value
          ])
        })
      })

      // 创建工作簿和工作表
      const workbook = XLSX.utils.book_new()
      const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)

      // 设置列宽
      const colWidth = [
        { wch: 15 }, // 分类列
        { wch: 25 }, // 子分类列
        { wch: 10 } // 数量列
      ]
      worksheet['!cols'] = colWidth

      // 添加工作表到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, '数据统计')

      // 导出文件
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
      const data = new Blob([excelBuffer], { type: 'application/octet-stream' })
      saveAs(data, `数据统计_${dayjs(new Date()).format('YYYY-MM-DD HH:mm')}.xlsx`)
    } catch (error) {
      MessageFu.error('导出失败')
      console.error('导出错误:', error)
    }
  }, [info.data, info.total])

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

      <div className='A2top'>
        数量统计以藏品总账中的藏品数据（包括已登记/修改中/删除中）为准
        <Button type='primary' onClick={exportToExcel}>
          导出表格
        </Button>
      </div>

      <div className='A2main'>
        <div className='A2Row'>
          <div className='A2Row1'>藏品总账数量</div>
          <div
            className='A2Row2 A2Row2Ac'
            onClick={() => {
              authorityFu(300, '您没有藏品总账页面权限', () => {
                history.push('/ledger')
              })
            }}
          >
            {info.total}
          </div>
        </div>

        {info.data.map(item => (
          <div className='A2son' key={item.name}>
            <div className='A2sonll'>{item.name}</div>

            <div className='A2sonrrBox'>
              {item.son.map(son => (
                <div className='A2sonrr' key={son.name}>
                  <div className='A2sonrr1'>{son.name}</div>
                  <div className='A2sonrr2'>{son.value}</div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

const MemoA2statistics = React.memo(A2statistics)

export default MemoA2statistics
