import { useState } from 'react'
import { Button, Flex, Modal, Input, Form, Select } from 'antd'
import AppProgressSteps from '@/components/AppProgressSteps'
import FunctionInput from '@/components/data/FunctionInput'
import { useProcessData } from '../query'

const functionOptions = [
  { label: 'ABS：返回数字的绝对值', value: 'ABS' },
  { label: 'AVERAGE：计算数值的平均值', value: 'AVERAGE' },
  { label: 'CEILING：将数值向上舍入到指定基数的倍数', value: 'CEILING' },
  { label: 'COUNT：统计包含数字的单元格数量', value: 'COUNT' },
  { label: 'COUNTIF：统计满足条件的单元格数量', value: 'COUNTIF' },
  { label: 'FLOOR：将数值向下舍入到指定基数的倍数', value: 'FLOOR' },
  { label: 'INT：将数值向下舍入到最接近的整数', value: 'INT' },
  { label: 'MAX：返回一组数值中的最大值', value: 'MAX' },
  { label: 'MIN：返回一组数值中的最小值', value: 'MIN' },
  { label: 'MOD：返回两数相除的余数', value: 'MOD' },
  { label: 'POWER：计算数值的指定次幂', value: 'POWER' },
  { label: 'PRODUCT：计算所有参数的乘积', value: 'PRODUCT' },
  { label: 'ROUND：将数值四舍五入到指定小数位数', value: 'ROUND' },
  { label: 'ROUNDUP：将数值向上舍入到指定小数位数', value: 'ROUNDUP' },
  { label: 'ROUNDDOWN：将数值向下舍入到指定小数位数', value: 'ROUNDDOWN' },
  { label: 'SQRT：返回数值的平方根', value: 'SQRT' },
  { label: 'SUM：计算所有数值的总和', value: 'SUM' },
  { label: 'SUMIF：对满足条件的单元格求和', value: 'SUMIF' },
  { label: 'SUMPRODUCT：计算多个数组的对应元素乘积之和', value: 'SUMPRODUCT' },
  { label: 'TRUNC：截断数值的小数部分（不四舍五入）', value: 'TRUNC' },
]

export default function ButtonModal() {
  const [open, setOpen] = useState(false)
  const [current, setCurrent] = useState(0)
  const [form] = Form.useForm()

  // 处理下一步按钮逻辑
  const handleNext = async () => {
    if (current === 0) {
      // 第一步验证表单
      await form.validateFields(['name', 'english_name'])
    } else if (current === 1) {
      await form.validateFields()
    }
    setCurrent(current + 1)
  }

  const { mutate, isPending, progress, message, remove } = useProcessData()

  // 开始处理
  const handleStart = () => {
    const values = form.getFieldsValue()
    const content = values.content || ''

    // 提取 content 中的参数
    const fieldsMatch = content.match(/\((.*?)\)/) // 匹配括号内的内容
    const fields = fieldsMatch ? fieldsMatch[1].split(',').map((field: string) => field.trim()) : []
    const params = { ...values, fields: JSON.stringify(fields) } // 将提取的参数赋值给 fields
    mutate(params, {
      onSuccess: handleClose,
    })
  }

  // 关闭并重置
  const handleClose = () => {
    setOpen(false)
    setCurrent(0)
    remove()
  }
  const handleFunctionChange = (value: string) => {
    form.setFieldsValue({ content: `${value}()` })
  }

  // 步骤定义
  const steps = [
    {
      title: '请选择数值计算字段',
      content: (
        <>
          <Form.Item label="数值计算字段名称" name="name" rules={[{ required: true, message: '请输入字段名称' }]}>
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            label="数值计算字段英文名称"
            name="english_name"
            rules={[{ required: true, message: '请输入英文名称' }]}>
            <Input placeholder="请输入" />
          </Form.Item>
        </>
      ),
    },
    {
      title: '配置数值计算规则',
      content: (
        <>
          <Form.Item label="请选择函数" name="function" rules={[{ required: true, message: '请选择函数' }]}>
            <Select options={functionOptions} onChange={handleFunctionChange} />
          </Form.Item>
          <Form.Item label="请输入函数公式" name="content" rules={[{ required: true, message: '请输入函数公式' }]}>
            <FunctionInput fieldType="string" />
          </Form.Item>
        </>
      ),
    },
    {
      title: '处理执行',
      content: (
        <>
          <Flex vertical align="center" style={{ marginTop: '20px' }}>
            <Button type="primary" onClick={handleStart} loading={isPending}>
              开始处理
            </Button>
            <AppProgressSteps
              current={progress}
              items={[
                { title: '新建字段' },
                { title: '复制数据' },
                { title: '数值计算处理' },
                { title: '处理结果', description: <>{message[3]}</> },
              ]}
            />
          </Flex>
        </>
      ),
    },
  ]

  const Footer = () => {
    return (
      <Flex justify="center" gap={20}>
        {current === 1 && <Button type="primary">AI检查函数公式</Button>}
        {current > 0 && <Button onClick={() => setCurrent(current - 1)}>上一步</Button>}
        {current < steps.length - 1 && (
          <Button type="primary" onClick={handleNext}>
            下一步
          </Button>
        )}
        {current === steps.length - 1 && (
          <Button type="primary" onClick={handleClose} disabled={isPending}>
            关闭
          </Button>
        )}
      </Flex>
    )
  }

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>
        数值计算
      </Button>
      <Modal
        title={steps[current]?.title}
        open={open}
        footer={<Footer />}
        destroyOnClose
        width={800}
        onCancel={handleClose}>
        <div style={{ minHeight: 300, padding: '20px 0' }}>
          <Form form={form} labelCol={{ span: 6 }} preserve={false}>
            {steps.map((item, index) => (
              <div key={index} hidden={current !== index} style={{ marginTop: '20px' }}>
                {item.content}
              </div>
            ))}
          </Form>
        </div>
      </Modal>
    </>
  )
}
