import { useEffect, useState } from 'react'
import { Button, Flex, Modal, Form, Divider, Select, Radio, Row, Col, Input } from 'antd'
import { useDataFieldQuery } from '@/hooks/useQuery'
import { useCreateChart, useUpdateChart, useViewChartQuery } from '@/hooks/useChartQuery'
import { useAI } from '@/hooks/useAI'
import Chart from './Chart'

interface Props {
  id?: string
  type: string
  setOpen: (open: boolean) => void
}

const ruleOptions = [
  { label: '无计算', value: '无计算' },
  { label: '求和', value: '求和' },
  { label: '求平均值', value: '求平均值' },
  { label: '计数', value: '计数' },
  { label: '求最大值', value: '求最大值' },
  { label: '求最小值', value: '求最小值' },
  { label: '求中位数', value: '求中位数' },
  { label: '求方差', value: '求方差' },
]

const sortOptions = [
  { label: '无排序', value: '无排序' },
  { label: '数值顺序', value: '数值顺序' },
  { label: '数值倒序', value: '数值倒序' },
  { label: '数值顺序Top N', value: '数值顺序Top N' },
  { label: '数值倒序Top N', value: '数值倒序Top N' },
]

const showOptions = [
  { label: '显示', value: true },
  { label: '不显示', value: false },
]

// 数字字段设置
const Step1 = ({ fieldOptions, getFieldOptions, type }: any) => {
  return (
    <>
      <Divider orientation="left" orientationMargin="0">
        数字字段设置
      </Divider>
      <Row gutter={20}>
        <Col span={8}>
          <Form.Item label='请选择"度量"字段' name="y">
            <Select options={getFieldOptions('number')} placeholder="请选择" mode="multiple" allowClear></Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="计算规则" name="yRule">
            <Select options={ruleOptions} placeholder="请选择"></Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="排序规则" name="ySort">
            <Select options={sortOptions} placeholder="请选择"></Select>
          </Form.Item>
        </Col>
      </Row>
      {!['11', '10'].includes(type) && (
        <Row gutter={20}>
          <Col span={8}>
            <Form.Item label='请选择"维度"字段' name="x">
              <Select options={fieldOptions} placeholder="请选择" allowClear></Select>
            </Form.Item>
          </Col>
        </Row>
      )}
      <Row gutter={20}>
        <Col span={8}>
          <Form.Item label="是否显示行轴" name="showX" hidden={!['1', '2'].includes(type)}>
            <Radio.Group options={showOptions}></Radio.Group>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="是否显示列轴" name="showY" hidden={!['1', '2'].includes(type)}>
            <Radio.Group options={showOptions}></Radio.Group>
          </Form.Item>
        </Col>
      </Row>
    </>
  )
}

// 辅助可视化设置
const Step2 = ({ fieldOptions, type, showTitle }: any) => {
  return (
    <>
      <Divider orientation="left" orientationMargin="0">
        辅助可视化设置
      </Divider>
      <Row gutter={20}>
        {!['11'].includes(type) && (
          <Col span={12}>
            <Form.Item label='请选择"标签"字段' name="labelField">
              <Select options={fieldOptions} placeholder="请选择" allowClear></Select>
            </Form.Item>
          </Col>
        )}
        <Col span={12}>
          <Form.Item label="请选择颜色规则" name="color">
            <Radio.Group options={[{ label: '自动颜色', value: 'auto' }]}></Radio.Group>
          </Form.Item>
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={12}>
          <Flex>
            <Form.Item label="是否有标题" name="showTitle">
              <Radio.Group
                options={[
                  { label: '无', value: false },
                  { label: '有', value: true },
                ]}></Radio.Group>
            </Form.Item>
            <Form.Item name="title" hidden={!showTitle}>
              <Input placeholder="请输入" />
            </Form.Item>
          </Flex>
        </Col>
        <Col span={12}>
          <Form.Item label="请选择填充图案" name="fillPattern" hidden={!['1'].includes(type)}>
            <Radio.Group
              options={[
                { label: '纯色', value: 'solid' },
                { label: '斜线', value: 'diagonal' },
                { label: '横线', value: 'horizontal' },
                { label: '竖线', value: 'vertical' },
              ]}></Radio.Group>
          </Form.Item>
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={12}>
          <Form.Item label="是否显示图例" name="showLegend" hidden={['11'].includes(type)}>
            <Radio.Group options={showOptions}></Radio.Group>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="是否四个角圆滑" name="borderRadius" hidden={!['1'].includes(type)}>
            <Radio.Group
              options={[
                { label: '不做圆滑处理', value: 0 },
                { label: '四个角圆滑处理', value: 10 },
                { label: '两个角圆滑处理', value: [10, 10, 0, 0] },
              ]}></Radio.Group>
          </Form.Item>
        </Col>
      </Row>
    </>
  )
}

// 表格设置
const TableStep = ({ fieldOptions }: any) => {
  return (
    <>
      <Row gutter={20}>
        <Col span={8}>
          <Form.Item label="选择字段" name="y" rules={[{ required: true, message: '请选择字段' }]}>
            <Select options={fieldOptions} placeholder="请选择" mode="multiple" allowClear></Select>
          </Form.Item>
        </Col>
      </Row>
    </>
  )
}

// 指标卡设置
const GaugeStep = ({ getFieldOptions, showTitle }: any) => {
  return (
    <>
      <Divider orientation="left" orientationMargin="0">
        辅助可视化设置
      </Divider>
      <Row gutter={20}>
        <Col span={8}>
          <Form.Item label='请选择"度量"字段' name="y">
            <Select
              options={getFieldOptions('number')}
              placeholder="请选择"
              mode="multiple"
              allowClear
              maxCount={1}></Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="计算规则" name="yRule">
            <Select options={ruleOptions} placeholder="请选择"></Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="请选择颜色规则" name="color">
            <Radio.Group options={[{ label: '自动颜色', value: 'auto' }]}></Radio.Group>
          </Form.Item>
        </Col>
      </Row>

      <Flex>
        <Form.Item label="是否有标题" name="showTitle">
          <Radio.Group
            options={[
              { label: '无', value: false },
              { label: '有', value: true },
            ]}></Radio.Group>
        </Form.Item>
        <Form.Item name="title" hidden={!showTitle}>
          <Input placeholder="请输入" />
        </Form.Item>
      </Flex>
    </>
  )
}

// 词云设置
const WordCloudStep = ({ fieldOptions, getFieldOptions, showTitle }: any) => {
  return (
    <>
      <Divider orientation="left" orientationMargin="0">
        辅助可视化设置
      </Divider>
      <Row gutter={20}>
        <Col span={12}>
          <Form.Item label="大小" name="y" rules={[{ required: true, message: '请选择' }]}>
            <Select
              options={getFieldOptions('number')}
              placeholder="请选择"
              mode="multiple"
              allowClear
              maxCount={1}></Select>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="计算规则" name="yRule">
            <Select options={ruleOptions} placeholder="请选择"></Select>
          </Form.Item>
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={12}>
          <Form.Item label='请选择"标签"字段' name="labelField" rules={[{ required: true, message: '请选择' }]}>
            <Select options={fieldOptions} placeholder="请选择" allowClear></Select>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="请选择颜色规则" name="color">
            <Radio.Group options={[{ label: '自动颜色', value: 'auto' }]}></Radio.Group>
          </Form.Item>
        </Col>
      </Row>

      <Flex>
        <Form.Item label="是否有标题" name="showTitle">
          <Radio.Group
            options={[
              { label: '无', value: false },
              { label: '有', value: true },
            ]}></Radio.Group>
        </Form.Item>
        <Form.Item name="title" hidden={!showTitle}>
          <Input placeholder="请输入" />
        </Form.Item>
      </Flex>
    </>
  )
}

const FormStep = ({ type, fieldOptions, getFieldOptions, showTitle }: any) => {
  if (type === '12') {
    return <TableStep fieldOptions={fieldOptions} />
  } else if (type === '9') {
    return <GaugeStep fieldOptions={fieldOptions} getFieldOptions={getFieldOptions} type={type} showTitle={showTitle} />
  } else if (type === '6' || type === '7') {
    return (
      <WordCloudStep fieldOptions={fieldOptions} getFieldOptions={getFieldOptions} type={type} showTitle={showTitle} />
    )
  } else {
    return (
      <>
        <Step1 fieldOptions={fieldOptions} getFieldOptions={getFieldOptions} type={type} />
        <Step2 fieldOptions={fieldOptions} type={type} showTitle={showTitle} />
      </>
    )
  }
}

const ModalContent = ({ setOpen, type, id = '' }: Props) => {
  const { fieldOptions, getFieldOptions } = useDataFieldQuery()
  const { data: chartData } = useViewChartQuery(id)

  const [form] = Form.useForm()

  useEffect(() => {
    if (id && chartData) {
      try {
        const parsedContent = JSON.parse(chartData.content)
        form.setFieldsValue({ ...parsedContent.form })
      } catch (e) {
        console.error('解析图表数据失败:', e)
      }
    }
  }, [id, chartData, form])

  const [results, setResults] = useState({})
  const xField = Form.useWatch('x', form)
  const yField = Form.useWatch('y', form)
  const labelField = Form.useWatch('labelField', form)
  const showTitle = Form.useWatch('showTitle', form)
  const title = Form.useWatch('title', form)
  const showLegend = Form.useWatch('showLegend', form)
  const showX = Form.useWatch('showX', form)
  const showY = Form.useWatch('showY', form)
  const color = Form.useWatch('color', form)
  const borderRadius = Form.useWatch('borderRadius', form)
  const fillPattern = Form.useWatch('fillPattern', form)
  const config = {
    title: { show: showTitle, text: title },
    legend: { show: showLegend },
    xAxis: { show: showX },
    yAxis: { show: showY },
    xField,
    yField,
    labelField,
    color,
    borderRadius,
    fillPattern,
    ...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 handlePreview = () => {
    const values = form.getFieldsValue()
    post({
      response_format: { type: 'json_object' },
      messages: [
        {
          role: 'user',
          content: `
        根据以下配置生成ECharts柱状图配置：
        - X轴字段：${values.x}
        - Y轴字段：${values.y}
        - 颜色字段：${values.labelField || '无'}
        - 标题：${values.title || '无'}
        - 是否显示X轴：${values.showX}
        - 是否显示Y轴：${values.showY}
        - 是否显示图例：${values.showLegend}
        - 填充图案：${values.fillPattern}
        - 圆角处理：${values.borderRadius}

        请生成完整的ECharts配置，包含以下部分：
        - title: 图表标题配置
        - tooltip: 提示框配置
        - showLegend: 图例配置
        - grid: 图表位置配置
        - xAxis: X轴配置
        - yAxis: Y轴配置
        - series: 数据系列配置，包含柱状图样式、颜色等

        以JSON格式输出，格式如下：
        {
          "results": {
            "title": {...},
            "tooltip": {...},
            "showLegend": {...},
            "grid": {...},
            "xAxis": {...},
            "yAxis": {...},
            "series": [...]
          }
        }
        `,
        },
      ],
    })
  }

  const { mutate: mutateCreate } = useCreateChart()
  const { mutate: mutateUpdate } = useUpdateChart()
  // 保存
  const handleSubmit = () => {
    form.validateFields().then((values) => {
      const params = { ...values, type, content: JSON.stringify({ form: values, config }) }

      if (id) {
        mutateUpdate(
          { id, ...params },
          {
            onSuccess: () => setOpen(false),
          }
        )
      } else {
        mutateCreate(params, {
          onSuccess: () => setOpen(false),
        })
      }
    })
  }

  return (
    <>
      <Form
        form={form}
        preserve={false}
        initialValues={{
          showX: true,
          showY: true,
          color: 'auto',
          borderRadius: 0,
          showLegend: true,
          showTitle: false,
          fillPattern: 'solid',
        }}>
        <Form.Item label="组件名称" name="name" rules={[{ required: true, message: '请输入组件名称' }]}>
          <Input placeholder="请输入" />
        </Form.Item>
        <FormStep type={type} fieldOptions={fieldOptions} getFieldOptions={getFieldOptions} showTitle={showTitle} />
        <Divider orientation="left" orientationMargin="0">
          预览组件效果
        </Divider>
        <Chart type={type} {...config} style={{ height: '400px', width: '960px' }} />
      </Form>

      <Flex justify="center" gap={20} style={{ marginTop: 40 }}>
        <Button type="primary" onClick={handlePreview}>
          预览组件效果
        </Button>
        {/* <Button type="primary">AI对话调整</Button> */}
        <Button type="primary" autoInsertSpace onClick={handleSubmit}>
          保存
        </Button>
      </Flex>
    </>
  )
}

export default function ButtonModal({ type = '1', id = '' }) {
  const [open, setOpen] = useState(false)
  const title = id ? '编辑' : '新建'
  return (
    <>
      <Button color="primary" variant={id ? 'text' : 'solid'} onClick={() => setOpen(true)}>
        {title}
      </Button>
      <Modal title={title} open={open} footer={null} destroyOnClose width={1000} onCancel={() => setOpen(false)}>
        <ModalContent type={type} setOpen={(open) => setOpen(open)} id={id} />
      </Modal>
    </>
  )
}
