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

interface ResultItem {
  name: string
}

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

export default function ButtonModal() {
  const { data = [] } = useDataFieldQuery()

  const [results, setResults] = useState<ResultItem[]>(
    data.filter((item: any) => {
      return item.type.includes('DECIMAL') || item.type.includes('SMALLINT')
    })
  )
  const { isLoading, post } = useAI({
    onComplete: (message) => {
      if (!message.content) return
      const parse = JSON.parse(message.content)
      console.log(parse)
      setResults(parse.results || {})
    },
  })

  const handleAI = () => {
    const names = results.map((item: any) => item.name).join(',')
    post({
      response_format: { type: 'json_object' },
      messages: [
        {
          role: 'user',
          content: `请帮我计算数据集中，字段${names}的${selectedButtons.join('、')}
返回格式示例：
json
{
  results:[
    { name: "字段1", 计算类型(中文):"计算结果" },
    { name: "字段2", 计算类型(中文):"计算结果" },
  ]
}`,
        },
      ],
    })
  }
  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 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={
          <Flex justify="center" gap={20}>
            <Button type="primary" loading={isLoading} 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 bordered dataSource={dataSource} columns={columns} pagination={false} scroll={{ x: 'max-content' }} />
        </div>
      </Modal>
    </>
  )
}
