import React, { useState, useEffect } from 'react';
import { Form, Input, Switch, Tabs, message, Button } from 'antd';
import { useIntl } from 'umi';
import WangEditor from '@/components/WangEidtor/WangEidtor';
import { TopStatus, EnglishSetting } from '@/dicts/policyManageDict';
import { addPolicy, updatePolicy, getPolicyDetail } from '@/servers/api/policy';

const { TabPane } = Tabs;

interface PolicyManageFormProps {
  id?: string;
  isEdit: boolean;
  onSuccess: () => void;
}

const PolicyManageForm: React.FC<PolicyManageFormProps> = ({ id, isEdit, onSuccess }) => {
  const [form] = Form.useForm();
  const [activeTabKey, setActiveTabKey] = useState<string>('zh');
  const [loading, setLoading] = useState<boolean>(false);
  const intl = useIntl();

  // 获取详情数据
  useEffect(() => {
    const fetchPolicyDetail = async (policyId: string) => {
      setLoading(true);
      try {
        const response = await getPolicyDetail(policyId);
        if (response && response.success) {
          const detail = response.data;
          form.setFieldsValue({
            isTop: detail.isTop === TopStatus.YES,
            titleZh: detail.title,
            titleEn: detail.titleEn,
            contentZh: detail.content,
            contentEn: detail.contentEn,
          });
        } else {
          message.error(response.message || intl.formatMessage({ id: 'policyManage.fetchDetailFailed' }));
        }
      } catch (error) {
        console.error('获取政策详情失败:', error);
        message.error(intl.formatMessage({ id: 'policyManage.fetchDetailFailed' }));
      } finally {
        setLoading(false);
      }
    };

    if (isEdit && id) {
      fetchPolicyDetail(id);
    }
  }, [isEdit, id, form, intl]);

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

  // 提交表单
  const handleSubmit = async () => {
    setLoading(true);
    try {
      // 一次性验证所有表单项
      try {
        await form.validateFields();
      } catch (error: any) {
        console.log(error);
        // 如果有验证错误，自动切换到相应Tab
        if (error.errorFields && error.errorFields.length > 0) {
          // 获取第一个错误字段
          const firstError = error.errorFields[0];
          const fieldName = firstError.name[0];

          // 根据字段名判断应该切换到哪个Tab
          if (fieldName === 'titleZh' || fieldName === 'contentZh') {
            setActiveTabKey('zh');
          } else if (fieldName === 'titleEn' || fieldName === 'contentEn') {
            setActiveTabKey('en');
          }
        }

        throw error;
      }

      // 获取所有表单值
      const values = form.getFieldsValue();

      // 转换表单数据为API需要的格式
      const requestData = {
        title: values.titleZh,
        titleEn: values.titleEn || '',
        content: values.contentZh,
        contentEn: values.contentEn || '',
        isTop: values.isTop ? TopStatus.YES : TopStatus.NO,
        settingEn: values.titleEn && values.contentEn ? EnglishSetting.YES : EnglishSetting.NO,
      };

      let response;
      if (isEdit && id) {
        response = await updatePolicy(id, requestData);
      } else {
        response = await addPolicy(requestData);
      }

      if (response && response.success) {
        message.success(isEdit
          ? intl.formatMessage({ id: 'policyManage.form.updateSuccess' })
          : intl.formatMessage({ id: 'policyManage.form.addSuccess' }));
        onSuccess(); // 回调父组件
      } else {
        message.error(response.message || (isEdit
          ? intl.formatMessage({ id: 'policyManage.form.updateFailed' })
          : intl.formatMessage({ id: 'policyManage.form.addFailed' })));
      }
    } catch (error: any) {
      console.error('表单验证或提交失败:', error);
      // 错误已在前面处理
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <Form form={form} layout="vertical" name="policyForm" preserve={false}>
        <Form.Item
          name="isTop"
          label={intl.formatMessage({ id: 'policyManage.form.isTop' })}
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>

        <Tabs activeKey={activeTabKey} onChange={handleTabChange}>
          <TabPane tab={intl.formatMessage({ id: 'policyManage.form.chineseTab' })} key="zh" forceRender={true}>
            <Form.Item
              name="titleZh"
              label={intl.formatMessage({ id: 'policyManage.form.titleZh' })}
              rules={[{ required: true, message: intl.formatMessage({ id: 'policyManage.form.titleZhRequired' }) }]}
            >
              <Input placeholder={intl.formatMessage({ id: 'policyManage.form.titleZhPlaceholder' })} />
            </Form.Item>

            <Form.Item
              name="contentZh"
              label={intl.formatMessage({ id: 'policyManage.form.contentZh' })}
              rules={[{ required: true, message: intl.formatMessage({ id: 'policyManage.form.contentZhRequired' }) }]}
            >
              <WangEditor
                language="zh-CN"
                height="300px"
                placeholder={intl.formatMessage({ id: 'policyManage.form.contentZhPlaceholder' })}
              />
            </Form.Item>
          </TabPane>
          <TabPane tab={intl.formatMessage({ id: 'policyManage.form.englishTab' })} key="en" forceRender={true}>
            <Form.Item
              name="titleEn"
              label={intl.formatMessage({ id: 'policyManage.form.titleEn' })}
              rules={[{ required: true, message: intl.formatMessage({ id: 'policyManage.form.titleEnRequired' }) }]}
            >
              <Input placeholder={intl.formatMessage({ id: 'policyManage.form.titleEnPlaceholder' })} />
            </Form.Item>

            <Form.Item
              name="contentEn"
              label={intl.formatMessage({ id: 'policyManage.form.contentEn' })}
              rules={[{ required: true, message: intl.formatMessage({ id: 'policyManage.form.contentEnRequired' }) }]}
            >
              <WangEditor
                language="en"
                height="300px"
                placeholder={intl.formatMessage({ id: 'policyManage.form.contentEnPlaceholder' })}
              />
            </Form.Item>
          </TabPane>
        </Tabs>
      </Form>
      <div style={{ textAlign: 'right', marginTop: '20px' }}>
        <Button onClick={() => onSuccess()}>
          {intl.formatMessage({ id: 'policyManage.cancel' })}
        </Button>
        <Button
          type="primary"
          loading={loading}
          onClick={handleSubmit}
          style={{ marginLeft: '8px' }}
        >
          {intl.formatMessage({ id: 'policyManage.submit' })}
        </Button>
      </div>
    </div>
  );
};

export default PolicyManageForm;
