import { useState } from 'react'
import { Button, Flex, Modal, Form, Divider, Select, Radio, Row, Col, Input } from 'antd'
import { useDataQuery, useDataFieldQuery } from '@/hooks/useQuery'
import { useCreateChart } from '@/hooks/useChartQuery'
import { useAI } from '@/hooks/useAI'
import { Column } from '@ant-design/plots'

export default function ButtonModal({ title = '新建柱状图', type = '1' }) {
  const { data } = useDataQuery()
  const { fieldOptions } = useDataFieldQuery()

  const [open, setOpen] = useState(false)
  const [form] = Form.useForm()

  const [results, setResults] = useState({})
  const config = { data: data.list, xField: '', yField: '', ...results }

  const { post } = useAI({
    onComplete: (message) => {
      console.log(message)
      try {
        const { results } = JSON.parse(message.content)
        setResults(results)
        console.log(results)
      } catch (e) {
        console.log(e)
      }
    },
  })

  const hiddenOptions = ['隐藏', '不隐藏']

  const handlePreview = () => {
    const values = form.getFieldsValue()
    post({
      response_format: { type: 'json_object' },
      messages: [
        {
          role: 'user',
          content: `
        用户配置：X轴字段为${values.x}，Y轴字段为${values.y}，标签字段为${values.label}，是否隐藏行轴为${values.hidden_axis_x}，是否隐藏列轴为${values.hidden_axis_y}，颜色规则为${values.fill_color}，是否有标题为${values.has_title}，标题为${values.title}，填充图案为${values.fill_image}，是否隐藏图例为${values.legend}，是否四个角圆滑为${values.radius}
        根据以上用户配置，生成Ant Design Charts柱状图配置，不需要返回data, 以 JSON 的形式输出，输出的 JSON 需遵守以下的格式：
        {
          "results": {
            "xField": "x",
            "yField": "y",
          }
        }
        `,
        },
      ],
    })
  }

  const { mutate } = useCreateChart()

  // 保存
  const handleSubmit = () => {
    form.validateFields().then((values) => {
      const params = { ...values, type, content: JSON.stringify({ config }) }
      mutate(params, {
        onSuccess: () => setOpen(false),
      })
    })
  }

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>
        {title}
      </Button>
      <Modal
        title={title}
        open={open}
        footer={
          <Flex justify="center" gap={20}>
            <Button type="primary" onClick={handlePreview}>
              预览组件效果
            </Button>
            <Button type="primary">AI对话调整</Button>
            <Button type="primary" autoInsertSpace onClick={handleSubmit}>
              保存
            </Button>
          </Flex>
        }
        destroyOnClose
        width={1000}
        onCancel={() => setOpen(false)}>
        <div style={{ minHeight: 300, padding: '20px 0' }}>
          <Form
            form={form}
            preserve={false}
            initialValues={{
              hidden_axis_x: '隐藏',
              hidden_axis_y: '隐藏',
              fill_color: '自动颜色',
              radius: '不做圆滑处理',
              legend: '隐藏',
              has_title: '无',
              fill_image: '纯色',
            }}>
            <Form.Item label="组件名称" name="name">
              <Input placeholder="请输入" />
            </Form.Item>
            <Divider orientation="left" orientationMargin="0">
              步骤1：数字字段设置
            </Divider>
            <Row gutter={20}>
              <Col span={8}>
                <Form.Item label="请选择“度量”字段" name="y">
                  <Select options={fieldOptions} placeholder="请选择"></Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="计算规则" name="y_rule">
                  <Select options={[{ label: '无计算', value: '无计算' }]} placeholder="请选择"></Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="排序规则" name="y_sort">
                  <Select options={[{ label: '无排序', value: '无排序' }]} placeholder="请选择"></Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={20}>
              <Col span={8}>
                <Form.Item label="请选择“维度”字段" name="x">
                  <Select options={fieldOptions} placeholder="请选择"></Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={20}>
              <Col span={8}>
                <Form.Item label="是否隐藏行轴" name="hidden_axis_x">
                  <Radio.Group options={hiddenOptions}></Radio.Group>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="是否隐藏列轴" name="hidden_axis_y">
                  <Radio.Group options={hiddenOptions}></Radio.Group>
                </Form.Item>
              </Col>
            </Row>
            <Divider orientation="left" orientationMargin="0">
              步骤2：辅助可视化设置
            </Divider>
            <Row gutter={20}>
              <Col span={12}>
                <Form.Item label="请选择“标签”字段" name="label">
                  <Select options={fieldOptions} placeholder="请选择"></Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="请选择颜色规则" name="fill_color">
                  <Radio.Group options={['自动颜色', '不同柱子颜色不同']}></Radio.Group>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={20}>
              <Col span={12}>
                <Flex>
                  <Form.Item label="是否有标题" name="has_title">
                    <Radio.Group options={['无', '有']}></Radio.Group>
                  </Form.Item>
                  <Form.Item name="title">
                    <Input placeholder="请输入" />
                  </Form.Item>
                </Flex>
              </Col>
              <Col span={12}>
                <Form.Item label="请选择填充图案" name="fill_image">
                  <Radio.Group options={['纯色', '斜线', '横线', '竖线']}></Radio.Group>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={20}>
              <Col span={12}>
                <Form.Item label="是否隐藏图例" name="legend">
                  <Radio.Group options={hiddenOptions}></Radio.Group>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="是否四个角圆滑" name="radius">
                  <Radio.Group options={['不做圆滑处理', '四个角圆滑处理', '两个角圆滑处理']}></Radio.Group>
                </Form.Item>
              </Col>
            </Row>
            <Divider orientation="left" orientationMargin="0">
              步骤3：预览组件效果
            </Divider>
            {!!Object.keys(results).length && <Column {...config} />}
          </Form>
        </div>
      </Modal>
    </>
  )
}
