import { useState, useMemo, useEffect } from 'react'
import { Button, Flex, Modal, Table, Checkbox } from 'antd'
import { DownloadOutlined } from '@ant-design/icons'
import { useDataFieldQuery, useDataQuery } from '@/hooks/useQuery'
import { utils, writeFile } from 'xlsx'

interface ResultItem {
  name: string
  [key: string]: any
}

interface DataField {
  name: string
  english_name: string
  type: string
}

interface DataListItem {
  [key: string]: string | number
}

interface Stats {
  最大值: number
  最小值: number
  平均值: number
  中位数: number
  众数: number
  '1/4位数': number
  '3/4位数': number
  方差: number
  标准差: number
  极差: number
}

const buttons = [
  '最大值',
  '最小值',
  '平均值',
  '中位数',
  '众数',
  '1/4位数',
  '3/4位数',
  '方差',
  '标准差',
  '极差',
] as const

export default function ButtonModal() {
  const { data } = useDataQuery()
  const { getFieldOptions } = useDataFieldQuery()
  const numberFields = getFieldOptions('number') as DataField[]

  const [selectedButtons, setSelectedButtons] = useState<string[]>([])

  const calculateStats = (values: number[]): Stats => {
    const sortedValues = [...values].sort((a, b) => a - b)
    const n = values.length
    const sum = values.reduce((a, b) => a + b, 0)
    const mean = sum / n
    const variance = values.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / n

    const roundToTwo = (num: number) => Math.round(num * 100) / 100

    return {
      最大值: roundToTwo(Math.max(...values)),
      最小值: roundToTwo(Math.min(...values)),
      平均值: roundToTwo(mean),
      中位数: roundToTwo(
        n % 2 === 0 ? (sortedValues[n / 2 - 1] + sortedValues[n / 2]) / 2 : sortedValues[Math.floor(n / 2)]
      ),
      众数: roundToTwo(
        (() => {
          const frequency: { [key: number]: number } = {}
          values.forEach((v) => (frequency[v] = (frequency[v] || 0) + 1))
          return Number(Object.entries(frequency).sort((a, b) => b[1] - a[1])[0][0])
        })()
      ),
      '1/4位数': roundToTwo(sortedValues[Math.floor(n * 0.25)]),
      '3/4位数': roundToTwo(sortedValues[Math.floor(n * 0.75)]),
      方差: roundToTwo(variance),
      标准差: roundToTwo(Math.sqrt(variance)),
      极差: roundToTwo(Math.max(...values) - Math.min(...values)),
    }
  }

  const results = numberFields.map((field) => {
    const fieldData = (data.list as DataListItem[])
      .map((item) => Number(item[field.english_name]))
      .filter((v: number) => !isNaN(v))
    if (fieldData.length === 0) return field

    const stats = calculateStats(fieldData)
    const result: ResultItem = { name: field.name }

    selectedButtons.forEach((button) => {
      result[button] = stats[button as keyof Stats]
    })

    return result
  })

  const [open, setOpen] = useState(false)
  const [title, setTitle] = useState('')

  const handleOpen = (buttonName: string) => {
    setSelectedButtons([buttonName])
    setTitle(`探索` + buttonName)
    setOpen(true)
  }

  const dataSource = results.map((item) => {
    return { ...item, key: item.name }
  })

  const columns: any = useMemo(() => {
    const baseColumns = [
      {
        title: '序号',
        key: 'index',
        render(_value: any, _record: any, index: any) {
          return index + 1
        },
        width: 62,
        align: 'center',
      },
      {
        title: '字段名称',
        dataIndex: 'name',
        align: 'center' as const,
      },
    ]

    const selectedColumns = buttons
      .filter((button) => selectedButtons.includes(button))
      .map((button) => ({
        title: button,
        dataIndex: button,
        align: 'center' as const,
      }))

    return [...baseColumns, ...selectedColumns]
  }, [selectedButtons])

  const handleButtonChange = (checkedValues: string[]) => {
    setSelectedButtons(checkedValues)
  }

  // 导出
  const handleExportExcel = () => {
    const worksheet = utils.json_to_sheet(results)
    const workbook = utils.book_new()
    utils.book_append_sheet(workbook, worksheet, 'Sheet1')
    writeFile(workbook, 'data.xlsx')
  }

  return (
    <>
      {buttons.map((button) => (
        <Button type="primary" key={button} onClick={() => handleOpen(button)}>
          {button}
        </Button>
      ))}
      <Modal title={title} open={open} footer={null} destroyOnClose width={1000} onCancel={() => setOpen(false)}>
        <div style={{ minHeight: 300, padding: '20px 0' }}>
          <Flex justify="space-between" align="center" style={{ marginBottom: '20px' }}>
            <div>
              请选择字段：
              <Button type="text" icon={<DownloadOutlined />} size="small" onClick={handleExportExcel}>
                导出
              </Button>
            </div>
            <Checkbox.Group value={selectedButtons} onChange={handleButtonChange}>
              {buttons.map((button) => (
                <Checkbox key={button} value={button}>
                  {button}
                </Checkbox>
              ))}
            </Checkbox.Group>
          </Flex>
          <Table bordered dataSource={dataSource} columns={columns} pagination={false} scroll={{ x: 'max-content' }} />
        </div>
      </Modal>
    </>
  )
}
