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'

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

export default function ButtonModal() {
  const { data } = useDataQuery()
  const { numberFields } = useDataFieldQuery()

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

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

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

  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 calculateStats = (values: number[]) => {
    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 [dataSource, setDataSource] = useState<any[]>([])
  useEffect(() => {
    setDataSource(numberFields.map((field) => ({ name: field.name })))
  }, [numberFields])

  const handleAI = () => {
    const newDataSource = numberFields.map((field) => {
      const fieldData = data.list.map((item: any) => Number(item[field.english_name])).filter((v: number) => !isNaN(v))

      if (fieldData.length === 0) return { name: field.name }

      const stats = calculateStats(fieldData)
      const result: { [key: string]: number | string } = { name: field.name }

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

      return result
    })

    setDataSource(newDataSource)
  }

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

  // 导出
  const handleExportExcel = () => {
    const worksheet = utils.json_to_sheet(dataSource)
    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={
          <Flex justify="center" gap={20}>
            <Button type="primary" onClick={handleAI}>
              一键计算
            </Button>
          </Flex>
        }
        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
            rowKey="name"
            bordered
            dataSource={dataSource}
            columns={columns}
            pagination={false}
            scroll={{ x: 'max-content' }}
          />
        </div>
      </Modal>
    </>
  )
}
