/* eslint-disable */
import React, { useState } from 'react';
import { Button, message, Radio, Modal, Tooltip } from 'antd-v4';
import { HistoryOutlined } from '@ant-design/icons';
import * as commonUtils from '@/utils/utils';/* 通用方法 */
import styles from './JsonFormatter.less';

const JSONFormatter = ({ initialJsonString, onJsonFormatOk, onJsonFormatCancel }) => {
  const [jsonString, setJsonString] = useState(initialJsonString);
  const [question, setQuestion] = useState('');
  const [answer, setAnswer] = useState('');
  const [selectedOption, setSelectedOption] = useState('');
  const [qaHistory, setQaHistory] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);

  const handleJsonChange = (e) => {
    const newJsonString = e.target.value;
    setJsonString(newJsonString);
  };

  const handleQuestionChange = (e) => {
    setQuestion(e.target.value);
  };

  const handleOptionChange = (e) => {
    const value = e.target.value;
    setSelectedOption(value);
    // 获取选中的 Radio 元素
    const radioElement = document.querySelector(`input[type="radio"][value="${value}"]`);
    if (radioElement) {
      // 获取自定义属性中的文本值
      const optionText = radioElement.getAttribute('data-question-text');
      setQuestion(optionText);
    }
  };

  const handleAsk = () => {
    const finalQuestion = selectedOption || question;
    if (jsonString) {
      try {
        const parsedData = JSON.parse(jsonString);
        let newAnswer;
        if (finalQuestion.includes('有多少个属性')) {
          newAnswer = `JSON 对象有 ${Object.keys(parsedData).length} 个属性。`;
        } else if (finalQuestion.includes('获取props.sSrcModelsId')) {
          newAnswer = '暂未实现获取 props.sSrcModelsId 的逻辑，请根据实际情况处理。';
        } else {
          newAnswer = '暂不支持该问题，请换个问题试试。';
        }
        setAnswer(newAnswer);
        setQaHistory([...qaHistory, { question: finalQuestion, answer: newAnswer }]);
      } catch (error) {
        const errorAnswer = 'JSON 解析出错，请检查 JSON 格式。';
        setAnswer(errorAnswer);
        setQaHistory([...qaHistory, { question: finalQuestion, answer: errorAnswer }]);
      }
    } else {
      const noDataAnswer = '请先输入有效的 JSON 数据。';
      setAnswer(noDataAnswer);
      setQaHistory([...qaHistory, { question: finalQuestion, answer: noDataAnswer }]);
    }
    setQuestion(''); // 清空输入框
    setSelectedOption(''); // 清空单选框选择
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      handleAsk();
    }
  };

  const handleOk = () => {
    if (jsonString) {
      try {
        JSON.parse(jsonString);
        if (onJsonFormatOk) {
          onJsonFormatOk(jsonString);
        }
      } catch (error) {
        message.error('JSON 格式不正确,请检查');
      }
    }
  };

  const handleCancel = () => {
    if (onJsonFormatCancel) {
      onJsonFormatCancel();
    }
  };

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  try {
    const parsedData = commonUtils.isNotEmptyObject(jsonString) ? JSON.parse(jsonString) : {};
    const formattedJSON = commonUtils.isNotEmptyObject(parsedData) ? JSON.stringify(parsedData, null, 2) : '';
    return (
      <div className={styles.jsonMain}>
        <div className={styles.jsonFormatterContainer}>
          <div className={styles.jsonPanel}>
            <h3>原始 JSON</h3>
            <textarea
              value={jsonString}
              onChange={handleJsonChange}
              className={styles.jsonTextarea}
            />
          </div>
          <div className={styles.divider} />
          <div className={styles.jsonPanel2}>
            <h3>格式化后的 JSON</h3>
            <pre className={styles.formattedJson}>{formattedJSON}</pre>
          </div>
          <div className={styles.divider} />
          <div className={styles.jsonPanel3}>
            <h3>辅助问答</h3>
            <div className={styles.answerContainer}>
              <p className={styles.answerText}>{answer}</p>
            </div>
            <div className={styles.questionOptions}>
              <Radio.Group value={selectedOption} onChange={handleOptionChange}>
                <Radio value="1" data-question-text="获取props.sSrcModelsId">1. 获取props.sSrcModelsId</Radio>
                <Radio value="2" data-question-text="获取界面上所有表格数据信息">2. 获取界面上所有表格数据信息</Radio>
                <Radio value="3" data-question-text="给出控制按钮亮与灰的实例代码">3. 给出控制按钮亮与灰的实例代码</Radio>
                {/* 可以添加更多选项 */}
              </Radio.Group>
            </div>
            <div className={styles.questionBox}>
              <textarea
                value={question}
                onChange={handleQuestionChange}
                onKeyPress={handleKeyPress}
                placeholder="输入你的问题"
                className={styles.questionInput}
              />
              <Button onClick={handleAsk}>提问</Button>
            </div>
            <div className={styles.historyIcon}>
              <Tooltip title="查看问答历史">
                <HistoryOutlined onClick={showModal} />
              </Tooltip>
            </div>
          </div>
        </div>
        <div className={styles.btnStyle}>
          <div style={{ textAlign: 'right', marginRight: '9px', marginBottom: '9px' }}>
            <Button type="primary" onClick={handleOk}>确定</Button>
          </div>
          <div style={{ textAlign: 'right', marginRight: '9px', marginBottom: '9px' }}>
            <Button onClick={handleCancel}>取消</Button>
          </div>
        </div>
        <Modal
          title="问答历史"
          visible={isModalVisible}
          onCancel={handleModalCancel}
          footer={null}
          mask
          maskClosable={true}
          maskStyle={{ backgroundColor: 'rgba(0, 0, 0, 0.7)' }}
        >
          <div className={styles.qaHistoryContainer}>
            {qaHistory.map((item, index) => (
              <div key={index} className={styles.qaHistoryItem}>
                <p className={styles.qaQuestion}>问题: {item.question}</p>
                <p className={styles.qaAnswer}>回答: {item.answer}</p>
              </div>
            ))}
          </div>
        </Modal>
      </div>
    );
  } catch (error) {
    return (
      <div className={styles.jsonMain}>
        <div className={styles.jsonFormatterContainer}>
          <div className={styles.jsonPanel}>
            <h3>原始 JSON</h3>
            <textarea
              value={jsonString}
              onChange={handleJsonChange}
              className={styles.jsonTextarea}
            />
          </div>
          <div className={styles.divider} />
          <div className={styles.jsonPanel2}>
            <h3>格式化后的 JSON</h3>
            <pre className={styles.formattedJson} style={{ color: 'red' }}>JSON 解析出错: {error.message}</pre>
          </div>
          <div className={styles.divider} />
          <div className={styles.jsonPanel3}>
            <h3>JSON 问答回复</h3>
            <div className={styles.answerContainer}>
              <p className={styles.answerText} style={{ color: 'red' }}>JSON 解析出错，请检查 JSON 格式。</p>
            </div>
            <div className={styles.questionOptions}>
              <Radio.Group value={selectedOption} onChange={handleOptionChange}>
                <Radio value="获取props.sSrcModelsId">A. 获取props.sSrcModelsId</Radio>
                {/* 可以添加更多选项 */}
              </Radio.Group>
            </div>
            <div className={styles.questionBox}>
              <textarea
                value={question}
                onChange={handleQuestionChange}
                onKeyPress={handleKeyPress}
                placeholder="输入你的问题"
                className={styles.questionInput}
              />
              <Button onClick={handleAsk}>提问</Button>
            </div>
            <div className={styles.historyIcon}>
              <Tooltip title="查看问答历史">
                <HistoryOutlined onClick={showModal} />
              </Tooltip>
            </div>
          </div>
        </div>
        <div className={styles.btnStyle}>
          <div style={{ textAlign: 'right', marginRight: '9px', marginBottom: '9px' }}>
            <Button type="primary" onClick={handleOk}>确定</Button>
          </div>
          <div style={{ textAlign: 'right', marginRight: '9px', marginBottom: '9px' }}>
            <Button onClick={handleCancel}>取消</Button>
          </div>
        </div>
        <Modal
          title="问答历史"
          visible={isModalVisible}
          onCancel={handleModalCancel}
          footer={null}
          mask
          maskClosable={true}
          maskStyle={{ backgroundColor: 'rgba(0, 0, 0, 0.7)' }}
        >
          <div className={styles.qaHistoryContainer}>
            {qaHistory.map((item, index) => (
              <div key={index} className={styles.qaHistoryItem}>
                <p className={styles.qaQuestion}>问题: {item.question}</p>
                <p className={styles.qaAnswer}>回答: {item.answer}</p>
              </div>
            ))}
          </div>
        </Modal>
      </div>
    );
  }
};

export default JSONFormatter;
