import React, { useState, useEffect } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { Card, Form, Input, Button, message, Tabs, Spin } from 'antd';
import WangEditor from '@/components/WangEidtor/WangEidtor';
import { getAboutUs, updateAboutUs, AboutUsRequest } from '@/servers/api/about';
import styles from './aboutManage.less';

const { TabPane } = Tabs;

interface ErrorInfo {
  errorFields: {
    name: string[];
    errors: string[];
  }[];
  values: Record<string, any>;
}

const AboutManage: React.FC = () => {
  const intl = useIntl();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [activeTabKey, setActiveTabKey] = useState<string>('zh');
  const [aboutData, setAboutData] = useState<AboutUsRequest | null>(null);

  // 获取关于我们详情数据
  const fetchAboutData = async () => {
    setLoading(true);
    try {
      const response = await getAboutUs();
      if (response && response.success) {
        setAboutData(response.data);
        // 设置表单初始值
        form.setFieldsValue({
          title: response.data.title,
          titleEn: response.data.titleEn,
          content: response.data.content,
          contentEn: response.data.contentEn,
          address: response.data.address,
          addressEn: response.data.addressEn,
          contactsPhone: response.data.contactsPhone,
          contactsPhoneEn: response.data.contactsPhoneEn,
          contactsEmail: response.data.contactsEmail,
          contactsEmailEn: response.data.contactsEmailEn,
          contactsConsult: response.data.contactsConsult,
          contactsConsultEn: response.data.contactsConsultEn,
        });
      } else {
        message.error(response.message || intl.formatMessage({ id: 'aboutManage.fetchFailed' }));
      }
    } catch (error) {
      console.error('获取关于我们数据失败:', error);
      message.error(intl.formatMessage({ id: 'aboutManage.fetchFailed' }));
    } finally {
      setLoading(false);
    }
  };

  // 首次加载时获取数据
  useEffect(() => {
    fetchAboutData();
  }, []);

  // 处理Tab切换
  const handleTabChange = (key: string) => {
    setActiveTabKey(key);
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setSubmitting(true);

      // 准备提交数据
      const submitData: AboutUsRequest = {
        ...aboutData,
        ...values,
      };

      // 保留原有的addressImg，如果没有则设置为空字符串
      submitData.addressImg = aboutData?.addressImg || '';

      const response = await updateAboutUs(submitData);
      if (response && response.success) {
        message.success(intl.formatMessage({ id: 'aboutManage.saveSuccess' }));
        fetchAboutData(); // 刷新数据
      } else {
        message.error(response.message || intl.formatMessage({ id: 'aboutManage.saveFailed' }));
      }
    } catch (errorInfo: any) {
      // 获取所有字段的错误信息
      const errorFields = errorInfo.errorFields || [];

      // 检查是否有中文标题或内容的错误
      const hasZhError = errorFields.some((field: any) => {
        if (!field.name) return false;
        const fieldName = Array.isArray(field.name) ? field.name.join('.') : String(field.name);
        return !fieldName.includes('En');
      });

      // 检查是否有英文标题或内容的错误
      const hasEnError = errorFields.some((field: any) => {
        if (!field.name) return false;
        const fieldName = Array.isArray(field.name) ? field.name.join('.') : String(field.name);
        return fieldName.includes('En');
      });

      // 如果有中文字段错误，切换到中文Tab
      if (hasZhError) {
        setActiveTabKey('zh');
      }
      // 如果只有英文字段错误，切换到英文Tab
      else if (hasEnError && !hasZhError) {
        setActiveTabKey('en');
      }

      console.log('表单验证失败:', errorInfo);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="common-container">
      <Card
        title={intl.formatMessage({ id: 'aboutManage.title' })}
        extra={
          <Button
            type="primary"
            onClick={handleSubmit}
            loading={submitting}
          >
            {intl.formatMessage({ id: 'aboutManage.save' })}
          </Button>
        }
      >
        <Spin spinning={loading}>
          <Form
            form={form}
            layout="vertical"
            initialValues={aboutData || {}}
          >
            <Tabs activeKey={activeTabKey} onChange={handleTabChange}>
              <TabPane tab={intl.formatMessage({ id: 'aboutManage.form.chineseTab' })} key="zh">
                <Form.Item
                  name="title"
                  label={intl.formatMessage({ id: 'aboutManage.form.title' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'aboutManage.form.titleRequired' }) }]}
                >
                  <Input placeholder={intl.formatMessage({ id: 'aboutManage.form.titlePlaceholder' })} />
                </Form.Item>

                <Form.Item
                  name="content"
                  label={intl.formatMessage({ id: 'aboutManage.form.content' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'aboutManage.form.contentRequired' }) }]}
                >
                  <WangEditor
                    language="zh-CN"
                    height="400px"
                    placeholder={intl.formatMessage({ id: 'aboutManage.form.contentPlaceholder' })}
                  />
                </Form.Item>

                <Form.Item
                  name="address"
                  label={intl.formatMessage({ id: 'aboutManage.form.address' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'aboutManage.form.addressRequired' }) }]}
                >
                  <Input placeholder={intl.formatMessage({ id: 'aboutManage.form.addressPlaceholder' })} />
                </Form.Item>

                <Form.Item
                  name="contactsPhone"
                  label={intl.formatMessage({ id: 'aboutManage.form.contactsPhone' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'aboutManage.form.contactsPhoneRequired' }) }]}
                >
                  <Input placeholder={intl.formatMessage({ id: 'aboutManage.form.contactsPhonePlaceholder' })} />
                </Form.Item>

                <Form.Item
                  name="contactsEmail"
                  label={intl.formatMessage({ id: 'aboutManage.form.contactsEmail' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'aboutManage.form.contactsEmailRequired' }) }]}
                >
                  <Input placeholder={intl.formatMessage({ id: 'aboutManage.form.contactsEmailPlaceholder' })} />
                </Form.Item>

                <Form.Item
                  name="contactsConsult"
                  label={intl.formatMessage({ id: 'aboutManage.form.contactsConsult' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'aboutManage.form.contactsConsultRequired' }) }]}
                >
                  <Input placeholder={intl.formatMessage({ id: 'aboutManage.form.contactsConsultPlaceholder' })} />
                </Form.Item>
              </TabPane>
              <TabPane tab={intl.formatMessage({ id: 'aboutManage.form.englishTab' })} key="en">
                <Form.Item
                  name="titleEn"
                  label={intl.formatMessage({ id: 'aboutManage.form.titleEn' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'aboutManage.form.titleEnRequired' }) }]}
                >
                  <Input placeholder={intl.formatMessage({ id: 'aboutManage.form.titleEnPlaceholder' })} />
                </Form.Item>

                <Form.Item
                  name="contentEn"
                  label={intl.formatMessage({ id: 'aboutManage.form.contentEn' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'aboutManage.form.contentEnRequired' }) }]}
                >
                  <WangEditor
                    language="en"
                    height="400px"
                    placeholder={intl.formatMessage({ id: 'aboutManage.form.contentEnPlaceholder' })}
                  />
                </Form.Item>

                <Form.Item
                  name="addressEn"
                  label={intl.formatMessage({ id: 'aboutManage.form.addressEn' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'aboutManage.form.addressEnRequired' }) }]}
                >
                  <Input placeholder={intl.formatMessage({ id: 'aboutManage.form.addressEnPlaceholder' })} />
                </Form.Item>

                <Form.Item
                  name="contactsPhoneEn"
                  label={intl.formatMessage({ id: 'aboutManage.form.contactsPhoneEn' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'aboutManage.form.contactsPhoneEnRequired' }) }]}
                >
                  <Input placeholder={intl.formatMessage({ id: 'aboutManage.form.contactsPhoneEnPlaceholder' })} />
                </Form.Item>

                <Form.Item
                  name="contactsEmailEn"
                  label={intl.formatMessage({ id: 'aboutManage.form.contactsEmailEn' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'aboutManage.form.contactsEmailEnRequired' }) }]}
                >
                  <Input placeholder={intl.formatMessage({ id: 'aboutManage.form.contactsEmailEnPlaceholder' })} />
                </Form.Item>

                <Form.Item
                  name="contactsConsultEn"
                  label={intl.formatMessage({ id: 'aboutManage.form.contactsConsultEn' })}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'aboutManage.form.contactsConsultEnRequired' }) }]}
                >
                  <Input placeholder={intl.formatMessage({ id: 'aboutManage.form.contactsConsultEnPlaceholder' })} />
                </Form.Item>
              </TabPane>
            </Tabs>
          </Form>
        </Spin>
        <div className={styles.saveBtnWrapper}>
          <Button
            type="primary"
            onClick={handleSubmit}
            loading={submitting}
          >
            {intl.formatMessage({ id: 'aboutManage.save' })}
          </Button>
        </div>
      </Card>
    </div>
  );
};

export default AboutManage;
