import { useEffect, useState } from 'react'
import { Button, Flex, Modal, Form, Table, Select } from 'antd'
import { useDataFieldQuery } from '@/hooks/useQuery'
import AppProgressSteps from '@/components/AppProgressSteps'
import { useProcessData } from '../query'

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

  const [open, setOpen] = useState(false)

  const [current, setCurrent] = useState(0)
  const [form] = Form.useForm()
  const [dataSource, setDataSource] = useState<{ key: number; raw_value: string; new_value: string }[]>([])
  const { mutate, isPending, progress, message, remove } = useProcessData()
  // 开始处理
  const handleStart = () => {
    form.validateFields().then((values) => {
      mutate(values)
    })
  }

  // 关闭并重置
  const handleClose = () => {
    setOpen(false)
    setCurrent(0)
    remove()
  }

  useEffect(() => {
    if (fields?.length) {
      setDataSource(
        fields
          .filter((item) => !item.type.includes('VARCHAR'))
          .map((item: any, index) => ({
            key: index + 1,
            ...item,
            new_value: '',
          }))
      )
    }
  }, [fields])

  // 处理映射值变化
  const handleValueChange = (value: string, key: number) => {
    setDataSource((prevDataSource) =>
      prevDataSource.map((item) => (item.key === key ? { ...item, new_value: value } : item))
    )
  }

  const options = [{ label: '文本', value: 'string' }]
  const steps = [
    {
      title: '请选择转换字段',
      content: (
        <Form.Item>
          <Table
            bordered
            pagination={false}
            rowSelection={{ type: 'radio' }}
            columns={[
              { title: '序号', dataIndex: 'key', align: 'center', width: 80 },
              { title: '字段名称', dataIndex: 'name', align: 'center' },
              { title: '原始值', dataIndex: 'type_name', align: 'center' },
              {
                title: '新数据类型',
                dataIndex: 'new_value',
                align: 'center',
                render: (_, record) => (
                  <Select
                    options={options}
                    value={record.new_value}
                    placeholder="请选择"
                    onChange={(value) => handleValueChange(value, record.key)}></Select>
                ),
              },
            ]}
            dataSource={dataSource}
          />
        </Form.Item>
      ),
    },
    {
      title: '处理执行',
      content: (
        <>
          <Flex vertical align="center" style={{ marginTop: '20px' }}>
            <Button type="primary" loading={isPending} onClick={handleStart}>
              开始处理
            </Button>
            <AppProgressSteps
              current={progress}
              items={[
                { title: '开始', description: message[1] },
                { title: '数据类型转换', description: message[2] },
                { title: '处理结果', description: message[3] },
              ]}
            />
          </Flex>
        </>
      ),
    },
  ]

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>
        数据类型转换
      </Button>
      <Modal
        title={steps[current].title}
        open={open}
        footer={
          <Flex justify="center" gap={20}>
            {current > 0 && <Button onClick={() => setCurrent(current - 1)}>上一步</Button>}
            {current < steps.length - 1 && (
              <Button type="primary" onClick={() => setCurrent(current + 1)}>
                下一步
              </Button>
            )}
            {current === steps.length - 1 && (
              <Button type="primary" disabled={isPending} onClick={handleClose}>
                关闭
              </Button>
            )}
          </Flex>
        }
        destroyOnClose
        width={800}
        onCancel={handleClose}>
        <div style={{ minHeight: 300, padding: '20px 0' }}>
          <Form form={form} labelCol={{ span: 5 }} preserve={false}>
            {steps.map((item, index) => (
              <div key={index} hidden={current !== index} style={{ marginTop: '20px' }}>
                {item.content}
              </div>
            ))}
          </Form>
        </div>
      </Modal>
    </>
  )
}
