import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Message } from '@arco-design/web-react';
import EditableTable from '@/pages/componentDevelopment/componentList/editableTable';
import { updateComponentDesign } from '@/api/componentDevelopProcess';

const FormItem = Form.Item;
const TextArea = Input.TextArea;

const AddApiModal = ({
                       visible,
                       baseInfo,
                       componentDesignProgress,
                       componentDesignData,
                       onUpdateComponentDesign,
                       onCancel,
                       onOk
                     }) => {
  const [form] = Form.useForm();
  const [parametersData, setParametersData] = useState([]);
  const [responsesData, setResponsesData] = useState([]);

  // 当 visible 或 componentDesignProgress 变化时，设置表单初始值
  useEffect(() => {
    if (visible && componentDesignProgress) {
      // 设置表单字段值
      form.setFieldsValue({
        ident: componentDesignProgress.ident || '',
        desc: componentDesignProgress.desc || ''
      });

      // 设置参数表格数据
      if (componentDesignProgress.parameters && Array.isArray(componentDesignProgress.parameters)) {
        setParametersData(componentDesignProgress.parameters.map((param, index) => ({
          key: param.id || index,
          ...param
        })));
      }
      else {
        setParametersData([]);
      }

      // 设置响应表格数据
      if (componentDesignProgress.responses && Array.isArray(componentDesignProgress.responses)) {
        setResponsesData(componentDesignProgress.responses.map((response, index) => ({
          key: response.id || index,
          ...response
        })));
      }
      else {
        setResponsesData([]);
      }
    }
    else if (visible) {
      // 重置表单和表格数据
      form.resetFields();
      setParametersData([]);
      setResponsesData([]);
    }
  }, [visible, componentDesignProgress, form]);

  const submit = async () => {
    try {
      await form.validate();
      const formData = form.getFields();

      // 构造要提交的数据
      const params = {
        baseInfo
      };

      // 如果是编辑模式且有完整的组件设计数据，需要更新对应的记录
      if (componentDesignProgress && componentDesignData && Array.isArray(componentDesignData)) {
        // 更新对应的记录
        const updatedOperates = componentDesignData.map(item => {
          if (item.ident === componentDesignProgress.ident) {
            // 更新记录
            return {
              ...formData,
              type: 'EVENT',
              parameters: parametersData,
              responses: responsesData
            };
          }
          return item;
        });

        params['operates'] = updatedOperates;
      }
      else if (componentDesignData && Array.isArray(componentDesignData)) {
        // 新增模式，将新记录添加到现有数据中
        const newOperate = {
          ...formData,
          type: 'EVENT',
          parameters: parametersData,
          responses: responsesData
        };

        params['operates'] = [...componentDesignData, newOperate];
      }
      else {
        // 没有现有数据时，创建包含单个元素的数组
        params['operates'] = [{
          ...formData,
          type: 'EVENT',
          parameters: parametersData,
          responses: responsesData
        }];
      }

      const res: any = await updateComponentDesign(params);

      if (res.code === 200) {
        Message.success(componentDesignProgress ? '更新成功' : '新增成功');
        // 调用父组件传递的 onUpdateComponentDesign 回调，用于更新父组件中的数据
        onUpdateComponentDesign && onUpdateComponentDesign(params);
      }
      else {
        Message.error(res.message);
      }

      // 调用父组件传递的 onOk 回调，并传递数据
      onOk && onOk(params);
    } catch (error) {
      console.error('表单验证失败:', error);
      Message.error('请检查表单填写是否正确');
    }
  };

  return (
    <Modal
      title={componentDesignProgress ? '编辑接口' : '新增接口'}
      visible={visible}
      onCancel={onCancel}
      onOk={submit}
      style={{ width: '50%' }}
      okButtonProps={{ disabled: !visible }}
    >
      <Form form={form} layout="vertical">
        <FormItem
          label="接口名称"
          field="ident"
          required
          rules={[
            {
              required: true,
              message: '请输入接口名称'
            },
            {
              validator: (value, cb) => {
                if (!value) {
                  return cb();
                }
                // 只允许英文字母、数字和下划线
                const pattern = /^[a-zA-Z0-9_]+$/;
                if (!pattern.test(value)) {
                  return cb('接口名称只能包含英文字母、数字和下划线');
                }
                return cb();
              }
            }
          ]}
        >
          <Input placeholder="请输入接口名称（仅支持英文字母、数字和下划线）" />
        </FormItem>
        <FormItem label="描述" field="desc">
          <TextArea placeholder="请输入描述" />
        </FormItem>
        <FormItem label="输入参数" field="parameters">
          <EditableTable
            onDataUpdate={setParametersData}
            initialData={componentDesignProgress?.parameters || []}
            visible={visible}
          />
        </FormItem>
        <FormItem label="输出参数" field="responses">
          <EditableTable
            onDataUpdate={setResponsesData}
            initialData={componentDesignProgress?.responses || []}
            visible={visible}
          />
        </FormItem>
      </Form>
    </Modal>
  );
};

export default AddApiModal;