import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Radio,
  Button,
  message,
  Row,
  Col,
  Divider,
  Space,
  Switch,
  Typography,
  Spin,
  Modal,
} from 'antd';
import { history, useLocation, useIntl } from 'umi';
import { ArrowLeftOutlined, SaveOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import EvaluateTemplateTable from '@/components/EvaluateTemplateTable';
import CategorySelector from '@/components/CategorySelector';
import {
  CategoryLimitationType,
  CategoryLimitationTypeText,
  TemplateStatus,
  TemplateStatusText,
  StarLevel,
  IndicatorAddOption
} from '@/dicts/supplierTemplateDict';
import {
  getTemplateDetail,
  getAllTemplates,
  updateTemplate,
  addTemplate
} from '@/servers/api/supplierEvaluate';
import styles from './supplierTemplateManage.less';

const { Option } = Select;
const { confirm } = Modal;

interface LocationState {
  isEdit?: boolean;
  editData?: SupplierEvaluate.TemplateRecord;
}

const { Title } = Typography;

const SupplierTemplateManageAdd: React.FC = () => {
  const intl = useIntl();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [templateData, setTemplateData] = useState<any[]>([]);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [templateDetail, setTemplateDetail] = useState<SupplierEvaluate.TemplateDetail>();
  const [templateList, setTemplateList] = useState<SupplierEvaluate.TemplateItem[]>([]);

  // 添加控制开关的状态
  const [indicatorStMore, setIndicatorStMore] = useState<string>(IndicatorAddOption.CAN_ADD);
  const [indicatorNdMore, setIndicatorNdMore] = useState<string>(IndicatorAddOption.CAN_ADD);

  // 获取路由传递的数据
  const location = useLocation<LocationState>();

  // 获取所有模板列表
  const fetchTemplateList = async () => {
    try {
      const res = await getAllTemplates();
      if (res.success && res.data) {
        setTemplateList(res.data);
      } else {
        message.error(intl.formatMessage({ id: 'supplierTemplateManage.message.getTemplateListFailed' }) || res.message);
      }
    } catch (error) {
      console.error('获取模板列表失败:', error);
      message.error(intl.formatMessage({ id: 'supplierTemplateManage.message.getTemplateListFailed' }));
    }
  };

  // 获取模板详情
  const fetchTemplateDetail = async (templateId: string) => {
    try {
      setLoading(true);
      const res = await getTemplateDetail(templateId);
      if (res.success && res.data) {
        setTemplateDetail(res.data as any);

        // 设置表单数据
        form.setFieldsValue({
          templateName: res.data.templateName,
          categoryLimitation: res.data.categoryLimitation,
          categoryId: res.data.categoryId,
          status: res.data.status,
          copyTemplateId: res.data.templateType,
          indicatorStMore: res.data.indicatorStMore || IndicatorAddOption.CAN_ADD,
          indicatorNdMore: res.data.indicatorNdMore || IndicatorAddOption.CAN_ADD,
        });

        // 直接设置指标数据，无需转换
        if (res.data.indicatorStList && res.data.indicatorStList.length > 0) {
          setTemplateData(res.data.indicatorStList);
        }
      } else {
        message.error(intl.formatMessage({ id: 'supplierTemplateManage.message.getDetailFailed' }) || res.message);
      }
    } catch (error) {
      console.error('获取模板详情失败:', error);
      message.error(intl.formatMessage({ id: 'supplierTemplateManage.message.getDetailFailed' }));
    } finally {
      setLoading(false);
    }
  };

  // 初始化编辑数据
  useEffect(() => {
    // 获取所有模板列表
    fetchTemplateList();

    // 如果是编辑模式，加载编辑数据
    if (location.state?.isEdit && location.state?.editData) {
      setIsEdit(true);

      // 获取模板详情
      if (location.state.editData.id) {
        fetchTemplateDetail(location.state.editData.id);
      }
    }
  }, []);

  // 处理返回
  const handleBack = () => {
    history.goBack();
  };

  // 提交数据的函数
  const handleDataSubmit = async (values: any) => {
    // 准备提交数据
    const selectedTemplate = templateList.find(template => template.id === values.copyTemplateId);
    const dataToSubmit: any = {
      ...values,
      templateType: selectedTemplate?.templateType || '',
      indicatorStList: templateData,
      indicatorTypeMore: IndicatorAddOption.CAN_ADD,
      status: parseInt(values.status, 10)
    };

    // 如果是编辑模式，添加ID
    if (isEdit && templateDetail) {
      dataToSubmit.id = templateDetail.id;
    }

    setLoading(true);
    try {
      // 调用API接口
      let res;
      if (isEdit) {
        res = await updateTemplate(dataToSubmit);
      } else {
        res = await addTemplate(dataToSubmit);
      }

      if (res.success) {
        message.success(isEdit
          ? intl.formatMessage({ id: 'supplierTemplateManage.message.updateSuccess' })
          : intl.formatMessage({ id: 'supplierTemplateManage.message.saveSuccess' })
        );
        history.goBack();
      } else {
        message.error(res.message || (isEdit
          ? intl.formatMessage({ id: 'supplierTemplateManage.message.updateFailed' })
          : intl.formatMessage({ id: 'supplierTemplateManage.message.saveFailed' })
        ));
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error(intl.formatMessage({ id: 'supplierTemplateManage.message.submitFailed' }));
    } finally {
      setLoading(false);
    }
  };

  // 处理表单提交
  const handleSubmit = (values: any) => {
    // 验证指标数据
    if (!templateData || templateData.length === 0) {
      message.error(intl.formatMessage({ id: 'supplierTemplateManage.message.addIndicator' }));
      return;
    }

    // 显示确认对话框
    confirm({
      title: isEdit
        ? intl.formatMessage({ id: 'supplierTemplateManage.confirm.update.title' })
        : intl.formatMessage({ id: 'supplierTemplateManage.confirm.save.title' }),
      icon: <ExclamationCircleOutlined />,
      content: isEdit
        ? intl.formatMessage({ id: 'supplierTemplateManage.confirm.update.content' })
        : intl.formatMessage({ id: 'supplierTemplateManage.confirm.save.content' }),
      okText: intl.formatMessage({ id: 'supplierTemplateManage.confirm.ok' }),
      cancelText: intl.formatMessage({ id: 'supplierTemplateManage.confirm.cancel' }),
      onOk() {
        // 用户点击确认，执行提交操作
        handleDataSubmit(values);
      },
    });
  };

  // 处理指标数据变更
  const handleTemplateDataChange = (data: any[]) => {
    setTemplateData(data);
  };

  // 处理开关变化
  const handleSwitchChange = (field: string, value: boolean) => {
    const newValue = value ? IndicatorAddOption.CAN_ADD : IndicatorAddOption.CANNOT_ADD;
    switch (field) {
      case 'indicatorStMore':
        setIndicatorStMore(newValue);
        form.setFieldsValue({ indicatorStMore: newValue });
        break;
      case 'indicatorNdMore':
        setIndicatorNdMore(newValue);
        form.setFieldsValue({ indicatorNdMore: newValue });
        break;
      default:
        break;
    }
  };

  // 处理模板选择
  const handleTemplateSelect = async (templateId: string) => {
    // 如果是新建模式，并且选择了模板，获取模板详情作为基础数据
    if (!isEdit && templateId) {
      try {
        setLoading(true);
        const res = await getTemplateDetail(templateId);
        if (res.success && res.data) {
          // 只复制指标数据，不复制基础信息
          if (res.data.indicatorStList && res.data.indicatorStList.length > 0) {
            // 复制模板数据，但清除ID以创建新记录
            const copiedIndicatorStList = JSON.parse(JSON.stringify(res.data.indicatorStList)).map((stItem: any) => {
              // 删除ID而不是设为undefined
              delete stItem.id;
              stItem.indicatorNdList = stItem.indicatorNdList.map((ndItem: any) => {
                delete ndItem.id;
                return ndItem;
              });
              return stItem;
            });

            setTemplateData(copiedIndicatorStList);
          }
        } else {
          message.error(intl.formatMessage({ id: 'supplierTemplateManage.message.getDetailFailed' }) || res.message);
        }
      } catch (error) {
        console.error('获取模板详情失败:', error);
        message.error(intl.formatMessage({ id: 'supplierTemplateManage.message.getDetailFailed' }));
      } finally {
        setLoading(false);
      }
    }
  };

  return (
    <div className="common-container">
        <div className={styles.pageHeader}>
          <Title level={4} style={{ margin: 0 }}>
            {isEdit
              ? intl.formatMessage({ id: 'supplierTemplateManage.edit.title' })
              : intl.formatMessage({ id: 'supplierTemplateManage.add.title' })
            }
          </Title>
          <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            {intl.formatMessage({ id: 'supplierTemplateManage.button.back' })}
          </Button>
        </div>

        <Form
          form={form}
          onFinish={handleSubmit}
          initialValues={{
            categoryLimitation: CategoryLimitationType.UNIVERSAL,
            status: TemplateStatus.DRAFT,
            indicatorStMore: IndicatorAddOption.CAN_ADD,
            indicatorNdMore: IndicatorAddOption.CAN_ADD,
          }}
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 17 }}
        >
          <Spin spinning={loading}>
            <Card title={intl.formatMessage({ id: 'supplierTemplateManage.card.basicInfo' })} bordered={false} className={styles.innerCard}>
              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item
                    label={intl.formatMessage({ id: 'supplierTemplateManage.form.templateName' })}
                    name="templateName"
                    rules={[{ required: true, message: intl.formatMessage({ id: 'supplierTemplateManage.rule.templateName' }) }]}
                  >
                    <Input placeholder={intl.formatMessage({ id: 'supplierTemplateManage.placeholder.templateName' })} maxLength={50} />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label={intl.formatMessage({ id: 'supplierTemplateManage.form.categoryLimitation' })}
                    name="categoryLimitation"
                    rules={[{ required: true, message: intl.formatMessage({ id: 'supplierTemplateManage.rule.categoryLimitation' }) }]}
                  >
                    <Radio.Group>
                      <Radio value={CategoryLimitationType.UNIVERSAL}>{CategoryLimitationTypeText[CategoryLimitationType.UNIVERSAL]}</Radio>
                      <Radio value={CategoryLimitationType.LIMITED}>{CategoryLimitationTypeText[CategoryLimitationType.LIMITED]}</Radio>
                    </Radio.Group>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) =>
                      prevValues.categoryLimitation !== currentValues.categoryLimitation
                    }
                  >
                    {({ getFieldValue }) => {
                      const categoryLimitation = getFieldValue('categoryLimitation');
                      return categoryLimitation === CategoryLimitationType.LIMITED ? (
                        <Form.Item
                          label={intl.formatMessage({ id: 'supplierTemplateManage.form.selectCategory' })}
                          name="categoryId"
                          rules={[{ required: true, message: intl.formatMessage({ id: 'supplierTemplateManage.rule.category' }) }]}
                        >
                          <CategorySelector value={categoryLimitation} multiple={false} />
                        </Form.Item>
                      ) : null;
                    }}
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item
                    label={intl.formatMessage({ id: 'supplierTemplateManage.form.selectTemplate' })}
                    name="copyTemplateId"
                  >
                    <Select
                      placeholder={intl.formatMessage({ id: 'supplierTemplateManage.form.selectTemplate' })}
                      loading={templateList.length === 0}
                      onSelect={handleTemplateSelect}
                    >
                      {templateList.map(template => (
                        template.id ? (
                          <Option key={template.id} value={template.id}>
                            {template.templateName}
                          </Option>
                        ) : null
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label={intl.formatMessage({ id: 'supplierTemplateManage.form.status' })}
                    name="status"
                    rules={[{ required: true, message: intl.formatMessage({ id: 'supplierTemplateManage.rule.status' }, { defaultMessage: '请选择是否启用' }) }]}
                  >
                    <Radio.Group>
                      <Radio value={TemplateStatus.DRAFT}>{TemplateStatusText[TemplateStatus.DRAFT]}</Radio>
                      <Radio value={TemplateStatus.ENABLED}>{TemplateStatusText[TemplateStatus.ENABLED]}</Radio>
                      <Radio value={TemplateStatus.DISABLED}>{TemplateStatusText[TemplateStatus.DISABLED]}</Radio>
                    </Radio.Group>
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item
                    label={intl.formatMessage({ id: 'supplierTemplateManage.form.indicatorStMore' })}
                    name="indicatorStMore"
                    valuePropName="checked"
                    getValueProps={(value) => ({ checked: value === IndicatorAddOption.CAN_ADD })}
                  >
                    <Switch
                      checked={indicatorStMore === IndicatorAddOption.CAN_ADD}
                      onChange={(checked) => handleSwitchChange('indicatorStMore', checked)}
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label={intl.formatMessage({ id: 'supplierTemplateManage.form.indicatorNdMore' })}
                    name="indicatorNdMore"
                    valuePropName="checked"
                    getValueProps={(value) => ({ checked: value === IndicatorAddOption.CAN_ADD })}
                  >
                    <Switch
                      checked={indicatorNdMore === IndicatorAddOption.CAN_ADD}
                      onChange={(checked) => handleSwitchChange('indicatorNdMore', checked)}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Card>

            <Divider />

            <Card title={intl.formatMessage({ id: 'supplierTemplateManage.card.indicatorInfo' })} bordered={false} className={styles.innerCard}>
              <EvaluateTemplateTable
                onChange={handleTemplateDataChange}
                value={templateData}
              />
            </Card>
          </Spin>

          <div className={styles.formActions}>
            <Space>
              <Button onClick={handleBack}>
                {intl.formatMessage({ id: 'supplierTemplateManage.button.cancel' })}
              </Button>
              <Button type="primary" htmlType="submit" loading={loading} icon={<SaveOutlined />}>
                {isEdit
                  ? intl.formatMessage({ id: 'supplierTemplateManage.button.update' })
                  : intl.formatMessage({ id: 'supplierTemplateManage.button.save' })
                }
              </Button>
            </Space>
          </div>
        </Form>
    </div>
  );
};

export default SupplierTemplateManageAdd;
