import React, { useState, useEffect } from 'react';
import { Modal, Button, Form, Input, Switch, message, Descriptions, Divider, Card, Tag } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { useIntl, FormattedMessage } from 'umi';
import styles from './userQuestionManage.less';
import { answerQuestion } from '@/servers/api/userQuestion';
// 引入字典
import {
  AnswerStatus,
  AnswerStatusText,
  AnswerStatusColor,
  PublishStatus,
  PublishStatusText,
  PublishStatusColor,
  TopStatus,
  TopStatusText,
  TopStatusColor
} from '@/dicts/userQuestionDict';

const { TextArea } = Input;

interface QuestionModalProps {
  visible: boolean;
  onCancel: () => void;
  question: any;
  mode: 'view' | 'answer' | 'edit';
  onSuccess: () => void;
}

/**
 * 问题模态框组件 - 整合了查看详情、回答问题和编辑回答功能
 */
const QuestionModal: React.FC<QuestionModalProps> = ({
  visible,
  onCancel,
  question,
  mode,
  onSuccess
}) => {
  const intl = useIntl();
  const [form] = Form.useForm();
  const [answerContent, setAnswerContent] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);

  // 初始化表单数据
  useEffect(() => {
    if (question) {
      setAnswerContent(question.answerContent || '');

      // 设置表单初始值
      form.setFieldsValue({
        answer: question.answerContent || '',
        isPublished: question.isPublished === 1,
        isTop: question.isTop === 1
      });
    }
  }, [question, form]);

  // 根据模式设置标题
  const getModalTitle = () => {
    switch (mode) {
      case 'answer':
        return intl.formatMessage({ id: 'questionModal.answer' });
      case 'edit':
        return intl.formatMessage({ id: 'questionModal.edit' });
      case 'view':
      default:
        return intl.formatMessage({ id: 'questionModal.view' });
    }
  };

  // 获取发布状态标签
  const getPublishTag = (isPublished: number) => {
    return isPublished === 1 ?
      <Tag color="green">{PublishStatusText[PublishStatus.YES]()}</Tag> :
      <Tag color="orange">{PublishStatusText[PublishStatus.NO]()}</Tag>;
  };

  // 获取置顶状态标签
  const getTopTag = (isTop: number) => {
    return isTop === 1 ?
      <Tag color="red">{TopStatusText[TopStatus.YES]()}</Tag> :
      <Tag color="default">{TopStatusText[TopStatus.NO]()}</Tag>;
  };

  // 获取回答状态标签
  const getAnswerStatusTag = (questionData: any) => {
    if (questionData.answerContent && questionData.answerContent.trim() !== '') {
      return <Tag color="green">{AnswerStatusText[AnswerStatus.ANSWERED]()}</Tag>;
    } else if (questionData.isAnswer === '1') {
      return <Tag color="blue">{AnswerStatusText[AnswerStatus.READ]()}</Tag>;
    } else {
      return <Tag color="orange">{AnswerStatusText[AnswerStatus.UNREAD]()}</Tag>;
    }
  };

  // 提交表单处理
  const handleSubmit = () => {
    form.validateFields().then(values => {
      if (!answerContent || answerContent.trim() === '') {
        message.error(intl.formatMessage({ id: 'questionModal.answerRequired' }));
        return;
      }

      const actionText = mode === 'answer' ?
        intl.formatMessage({ id: 'userQuestion.submitAnswer' }) :
        intl.formatMessage({ id: 'userQuestion.saveEdit' });

      Modal.confirm({
        title: mode === 'answer' ?
          intl.formatMessage({ id: 'userQuestion.confirmSubmit' }) :
          intl.formatMessage({ id: 'userQuestion.confirmEdit' }),
        icon: <ExclamationCircleOutlined />,
        content: mode === 'answer'
          ? intl.formatMessage({ id: 'userQuestion.submitConfirmText' })
          : intl.formatMessage({ id: 'userQuestion.editConfirmText' }),
        okText: intl.formatMessage({ id: 'readQuestion.confirm' }),
        cancelText: intl.formatMessage({ id: 'readQuestion.cancel' }),
        onOk: async () => {
          setLoading(true);
          try {
            // 调用回答问题API
            const response = await answerQuestion({
              id: question.id,
              answerContent,
              isPublished: values.isPublished ? 1 : 0,
              isTop: values.isTop ? 1 : 0
            });

            if (response && response.success) {
              if (mode === 'answer') {
                message.success(intl.formatMessage({ id: 'questionModal.answerSuccess' }));
              } else {
                message.success(intl.formatMessage({ id: 'questionModal.editSuccess' }));
              }
              onSuccess();
              onCancel();
            } else {
              if (mode === 'answer') {
                message.error(response.message || intl.formatMessage({ id: 'questionModal.answerFailed' }));
              } else {
                message.error(response.message || intl.formatMessage({ id: 'questionModal.editFailed' }));
              }
            }
          } catch (error) {
            console.error(`${actionText}失败:`, error);
            if (mode === 'answer') {
              message.error(intl.formatMessage({ id: 'questionModal.answerFailed' }));
            } else {
              message.error(intl.formatMessage({ id: 'questionModal.editFailed' }));
            }
          } finally {
            setLoading(false);
          }
        }
      });
    }).catch(errorInfo => {
      console.log('表单验证失败:', errorInfo);
    });
  };

  // 渲染查看模式内容
  const renderViewContent = () => {
    if (!question) return null;

    return (
      <div className={styles.questionDetailView}>
        <Descriptions bordered column={2} size="small">
          <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.title' })} span={2}>
            {question.title}
          </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.category' })}>
            {question.type}
          </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.askTime' })}>
            {question.askTime}
          </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.asker' })}>
            {question.userName}
          </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.company' })}>
            {question.companyName || '-'}
          </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.account' })}>
            {question.fullName || '-'}
          </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.contact' })}>
            {question.contactDetails || '-'}
          </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.email' })}>
            {question.email || '-'}
          </Descriptions.Item>

          {/* 只有已回答的问题才会显示以下字段 */}
          {question.isAnswer === '1' && (
            <>
              <Descriptions.Item label={intl.formatMessage({ id: 'readQuestion.status' })}>
                {getAnswerStatusTag(question)}
              </Descriptions.Item>
              <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.publishStatus' })}>
                {getPublishTag(question.isPublished)}
              </Descriptions.Item>
              <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.topStatus' })}>
                {getTopTag(question.isTop)}
              </Descriptions.Item>
              <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.answerTime' })}>
                {question.answerTime || '-'}
              </Descriptions.Item>
              <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.respondent' })}>
                {question.answerBy || '-'}
              </Descriptions.Item>
            </>
          )}
          {/* 未回答的问题显示状态 */}
          {question.isAnswer !== '1' && (
            <Descriptions.Item label={intl.formatMessage({ id: 'readQuestion.status' })} span={2}>
              {getAnswerStatusTag(question)}
            </Descriptions.Item>
          )}
        </Descriptions>

        <Divider orientation="left">{intl.formatMessage({ id: 'questionDetail.questionContent' })}</Divider>
        <Card size="small" bordered={false} className={styles.contentCard}>
          <div className={styles.questionContent}>
            {question.content}
          </div>
        </Card>

        {question.answerContent && (
          <>
            <Divider orientation="left">{intl.formatMessage({ id: 'questionDetail.answerContent' })}</Divider>
            <Card size="small" bordered={false} className={styles.contentCard}>
              <div className={styles.answerContent}>
                {question.answerContent}
              </div>
            </Card>
          </>
        )}
      </div>
    );
  };

  // 渲染编辑模式内容
  const renderEditContent = () => {
    if (!question) return null;

    return (
      <Form form={form} layout="vertical">
        <div className={styles.questionInfoSection}>
          <Descriptions bordered column={2} size="small">
            <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.title' })} span={2}>
              {question.title}
            </Descriptions.Item>
            <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.category' })}>
              {question.type}
            </Descriptions.Item>
            <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.askTime' })}>
              {question.askTime}
            </Descriptions.Item>
            <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.asker' })}>
              {question.userName}
            </Descriptions.Item>
            <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.company' })}>
              {question.companyName || '-'}
            </Descriptions.Item>
            <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.account' })}>
              {question.fullName || '-'}
            </Descriptions.Item>
            <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.contact' })}>
              {question.contactDetails || '-'}
            </Descriptions.Item>
            <Descriptions.Item label={intl.formatMessage({ id: 'questionDetail.email' })}>
              {question.email || '-'}
            </Descriptions.Item>
          </Descriptions>
        </div>

        <Divider orientation="left">{intl.formatMessage({ id: 'questionDetail.questionContent' })}</Divider>
        <Card size="small" bordered={false} className={styles.contentCard}>
          <div className={styles.questionContent}>
            {question.content}
          </div>
        </Card>

        <Divider orientation="left">{intl.formatMessage({ id: 'questionDetail.answerContent' })}</Divider>
        <Form.Item
          name="answer"
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'questionModal.answerRequired' }),
            },
          ]}
        >
          <TextArea
            rows={8}
            value={answerContent}
            onChange={(e) => setAnswerContent(e.target.value)}
          />
        </Form.Item>

        <div className={styles.questionSettings}>
          <Form.Item name="isPublished" valuePropName="checked">
            <Switch checkedChildren={intl.formatMessage({ id: 'questionModal.publishSwitch' })} />
          </Form.Item>

          <Form.Item name="isTop" valuePropName="checked">
            <Switch checkedChildren={intl.formatMessage({ id: 'questionModal.topSwitch' })} />
          </Form.Item>
        </div>
      </Form>
    );
  };

  // 根据模式渲染不同内容
  const renderContent = () => {
    switch (mode) {
      case 'answer':
      case 'edit':
        return renderEditContent();
      case 'view':
      default:
        return renderViewContent();
    }
  };

  // 渲染底部按钮
  const renderFooter = () => {
    switch (mode) {
      case 'answer':
      case 'edit':
        return [
          <Button key="cancel" onClick={onCancel}>
            {intl.formatMessage({ id: 'readQuestion.cancel' })}
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={loading}
            onClick={handleSubmit}
          >
            {mode === 'answer'
              ? intl.formatMessage({ id: 'questionModal.confirmSubmit' })
              : intl.formatMessage({ id: 'questionModal.confirmEdit' })}
          </Button>,
        ];
      case 'view':
      default:
        return [
          <Button key="close" type="primary" onClick={onCancel}>
            {intl.formatMessage({ id: 'questionModal.close' })}
          </Button>,
        ];
    }
  };

  return (
    <Modal
      title={getModalTitle()}
      visible={visible}
      onCancel={onCancel}
      width={800}
      footer={renderFooter()}
      maskClosable={false}
      destroyOnClose
    >
      {renderContent()}
    </Modal>
  );
};

export default QuestionModal;
