import React, { useEffect, useState } from 'react';
import {
  Modal,
  Form,
  Input,
  Grid,
  Space,
  Divider,
  Button,
  Table,
  TableColumnProps,
  Select,
  Message,
  Upload,
  Progress
} from '@arco-design/web-react';
import { IconPlus, IconEdit } from '@arco-design/web-react/icon';
import styles from './style/addComponentModal.module.less';
import EditorSection from '@/components/EditorSection';
import AddApiModal from '@/pages/componentDevelopment/componentList/addApiModal';
import { getComponentClassify } from '@/api/componentClassify';
import { compProjectValidate, compSubmit, getTagList } from '@/api/componentBase';
import { getComponentDesign, updateComponentDesign } from '@/api/componentDevelopProcess';

const FormItem = Form.Item;
const Option = Select.Option;


const AddComponentModal = ({ visible, baseInfo, setVisible, onReFresh }) => {
  const [selectedImage, setSelectedImage] = useState('');
  const [description, setDescription] = useState('');
  const [classifyList, setClassifyList] = useState([]);
  const [showSaveBtn, setShowSaveBtn] = useState(false);
  const [tagsList, setTagsList] = useState([]);
  const [componentData, setComponentData] = useState(null);
  const [componentDesignData, setComponentDesignData] = useState([]); // 新增状态用于存储接口设计数据
  const [selectedApiData, setSelectedApiData] = useState(null); // 新增状态用于存储选中的API数据
  const [showApiModal, setShowApiModal] = useState(false);
  const [file, setFile] = useState(null);
  const [form] = Form.useForm();

  const cs = `arco-upload-list-item${file && file.status === 'error' ? ' is-error' : ''}`;

  const columns: TableColumnProps[] = [
    {
      title: '接口名称',
      dataIndex: 'ident'
    },
    {
      title: '输入参数',
      dataIndex: 'parameters',
      render: (_, record) => {
        if (!record.parameters || record.parameters.length === 0) {
          return '-';
        }
        return record.parameters.map(param => param.ident).join(', ');
      }
    },
    {
      title: '输出参数',
      dataIndex: 'responses',
      render: (_, record) => {
        if (!record.responses || record.responses.length === 0) {
          return '-';
        }
        return record.responses.map(response => response.ident).join(', ');
      }
    },
    {
      title: '操作',
      dataIndex: 'op',
      width: 240,
      render: (_, record) => (
        <>
          <Button type="text" onClick={() => {
            // 设置选中的API数据，用于编辑时回显
            setSelectedApiData(record);
            setShowApiModal(true);
          }}>
            编辑
          </Button>
          <Button
            type="text"
            status="danger"
            onClick={async () => {
              // 显示删除确认框
              Modal.confirm({
                title: '确认删除',
                content: `确定要删除接口 "${record.ident}" 吗？此操作不可恢复。`,
                okButtonProps: { status: 'danger' },
                onOk: () => {
                  // 从 componentDesignData 中过滤掉要删除的记录
                  const updatedData = componentDesignData.filter(item => item.ident !== record.ident);

                  // 构造要提交的数据
                  const params = {
                    baseInfo: componentData || baseInfo,
                    operates: updatedData // 保持数组格式
                  };

                  // 调用接口更新数据
                  const res: any = updateComponentDesign(params);
                  try {
                    if (res.code === 200) {
                      Message.success('删除成功');
                      // 更新本地状态
                      setComponentDesignData(updatedData);
                    }
                    else {
                      Message.error(res.message || '删除失败');
                      // 删除失败时恢复数据
                      setComponentDesignData(componentDesignData);
                    }
                  } catch (error) {
                    console.error('删除失败:', error);
                    Message.error('删除失败');
                    // 删除失败时恢复数据
                    setComponentDesignData(componentDesignData);
                  }
                }
              });
            }}
          >
            删除
          </Button>
        </>
      )
    }
  ];


  const getComponentClassifyList = async () => {
    const res: any = await getComponentClassify('component');
    if (res.code === 200) {
      const data = [];
      res.data.forEach((item) => {
        data.push({
          label: item.classifyName,
          value: item.id
        });
      });
      setClassifyList(data);
    }
  };

  const getTageList = async () => {
    const res: any = await getTagList();
    if (res.code === 200) setTagsList(res.data);
  };

  const validateProjectId = async (projectId: string) => {
    if (!projectId) return;

    try {
      const res = await compProjectValidate(projectId);
      if (res.data === false) {
        // 项目标识已存在，设置表单字段错误
        form.setFields({
          projectId: {
            value: projectId,
            error: {
              message: '项目标识已存在'
            }
          }
        });
      }
      else {
        // 项目标识可用，清除错误
        form.setFields({
          projectId: {
            value: projectId,
            error: null
          }
        });
      }
    } catch (error) {
      // API调用出错
      form.setFields({
        projectId: {
          value: projectId,
          error: {
            message: '验证项目标识时发生错误'
          }
        }
      });
    }
  };

  const onSubmit = async () => {
    try {
      await form.validate();
      const formData = form.getFields();
      const params: any = {
        name: formData.name,
        projectId: formData.projectId,
        logoUrl: selectedImage,
        desc: description,
        componentClassify: formData.componentClassify,
        codeLanguage: formData.codeLanguage === 'Java:8' ? 'Java' : 'Python',
        type: formData.type === '普通组件' ? 'normal' : 'loop',
        tags: formData.tags
      };

      // 如果是编辑模式（baseInfo存在），则传递id
      if (baseInfo && baseInfo.id) {
        params.id = baseInfo.id;
      }

      const res: any = await compSubmit(params);
      if (res.code === 200) {
        setComponentData(res.data);
        setShowSaveBtn(true);
        Message.success(baseInfo ? '组件信息更新成功' : '组件信息提交完成，可继续组件接口设计');
        onReFresh();

        // 提交成功后获取组件设计数据
        if (res.data && res.data.id) {
          getComponentDesignData(res.data.id);
        }
      }
      else {
        Message.error(baseInfo ? '组件信息更新失败' : '组件信息提交失败');
      }
    } catch (error) {
      console.error('提交/更新失败:', error);
    }
  };

  const getComponentDesignData = async (componentBaseId) => {
    try {
      const res = await getComponentDesign(componentBaseId);
      if (res.data) {
        // 处理返回的数据，使其符合表格显示格式
        const processedData = res.data.operates.map(item => ({
          ...item,
          key: item.ident,
          name: item.ident // 使用ident作为名称显示
        }));
        setComponentDesignData(processedData);
      }
    } catch (error) {
      console.error('获取组件设计数据失败:', error);
      Message.error('获取组件设计数据失败');
    }
  };

  useEffect(() => {
    getComponentClassifyList();
    getTageList();
  }, []);

  // 当baseInfo或visible变化时，设置表单初始值
  useEffect(() => {
    if (visible && baseInfo) {
      // 设置表单字段值
      form.setFieldsValue({
        name: baseInfo.name || '',
        projectId: baseInfo.projectId || '',
        componentClassify: baseInfo.componentClassify || '',
        codeLanguage: baseInfo.codeLanguage || '',
        tags: baseInfo.tags || [],
        type: baseInfo.type || ''
      });

      // 设置其他状态
      setSelectedImage(baseInfo.logoUrl || '');
      setDescription(baseInfo.desc || '');
      setShowSaveBtn(true);

      // 获取组件设计数据
      getComponentDesignData(baseInfo.id);
    }
    else if (visible) {
      // 重置表单
      form.resetFields();
      setSelectedImage('');
      setDescription('');
      setShowSaveBtn(false);
      setComponentDesignData([]); // 清空接口设计数据
    }
  }, [baseInfo, visible, form]);

  const modalFooter = () => {
    const isEditMode = !!baseInfo; // 判断是否为编辑模式

    return (
      <Space size={30}>
        <Button size="small" type="outline" style={{ borderRadius: 5 }} onClick={() => setVisible(false)}>取消</Button>
        {showSaveBtn ? (
          <Button size="small" type="primary" style={{ borderRadius: 5 }} onClick={() => onSubmit()}>
            {isEditMode ? '更新' : '保存'}
          </Button>
        ) : (
          <Button size="small" type="primary" style={{ borderRadius: 5 }} onClick={() => onSubmit()}>
            {isEditMode ? '更新组件信息' : '提交组件信息'}
          </Button>
        )}
      </Space>
    );
  };

  const UploadImage = () => {
    // 如果是编辑模式且有baseInfo.logoUrl，则使用baseInfo中的logoUrl
    const initialImageUrl = baseInfo && baseInfo.logoUrl ? baseInfo.logoUrl : null;

    return (
      <Upload
        action="/api/v1/bpms-workbench/fileSystem/fileUpload"
        fileList={file ? [file] : initialImageUrl ? [{ url: initialImageUrl, status: 'done' }] : []}
        showUploadList={false}
        onChange={(_, currentFile: any) => {
          setFile({
            ...currentFile,
            url: URL.createObjectURL(currentFile.originFile)
          });
          if (currentFile.status === 'done') setSelectedImage(currentFile.response.data.link);
        }}
        onProgress={(currentFile) => {
          setFile(currentFile);
        }}
      >
        <div className={cs}>
          {(file && file.url) || initialImageUrl ? (
            <div className="arco-upload-list-item-picture custom-upload-avatar">
              <img src={file?.url || initialImageUrl} />
              <div className="arco-upload-list-item-picture-mask">
                <IconEdit />
              </div>
              {file && file.status === 'uploading' && file.percent < 100 && (
                <Progress
                  percent={file.percent}
                  type="circle"
                  size="mini"
                  style={{
                    position: 'absolute',
                    left: '50%',
                    top: '50%',
                    transform: 'translateX(-50%) translateY(-50%)'
                  }}
                />
              )}
            </div>
          ) : (
            <div className="arco-upload-trigger-picture">
              <div className="arco-upload-trigger-picture-text">
                <IconPlus />
              </div>
            </div>
          )}
        </div>
      </Upload>
    );
  };

  return (
    <Modal
      className={styles['add-component-modal']}
      title={baseInfo ? '编辑组件' : '新增组件'}
      visible={visible}
      autoFocus={false}
      focusLock={true}
      style={{ width: '60%' }}
      footer={modalFooter}
      onCancel={() => setVisible(false)}
      afterClose={() => {
        // 关闭模态框后重置表单
        form.resetFields();
        setSelectedImage('');
        setDescription('');
        setShowSaveBtn(false);
        setFile(null);
      }}
    >
      <Form form={form} className={styles['add-component-container']}>
        <div className={styles['first-half']}>
          <div className={styles['component-preview']}>
            <FormItem label="图标：" field="logoUrl">
              <UploadImage />
            </FormItem>
            <FormItem label="组件预览：">
              <div
                style={{
                  width: '80%',
                  height: 200,
                  border: '1px solid #dcdfe6',
                  borderRadius: 5
                }}
              >组件外壳
              </div>
            </FormItem>
          </div>
          <div className={styles['component-info']}>
            <Grid.Row gutter={8}>
              <Grid.Col span={12}>
                <FormItem label="名称：" field="name" required rules={[
                  {
                    validator(value, cb) {
                      if (!value) {
                        return cb('请输入名称');
                      }

                      return cb();
                    }
                  }
                ]}>
                  <Input style={{ width: '90%' }} allowClear placeholder="请输入名称" />
                </FormItem>
              </Grid.Col>
              <Grid.Col span={12}>
                <FormItem label="代码标识：" field="projectId" required rules={[
                  {
                    validator(value, cb) {
                      if (!value) {
                        return cb('请输入代码标识');
                      }

                      return cb();
                    }
                  }
                ]}>
                  <Input
                    style={{ width: '90%' }}
                    allowClear
                    placeholder="请输入代码标识"
                    onChange={(e) => validateProjectId(e)}
                  />
                </FormItem>
              </Grid.Col>
            </Grid.Row>
            <Grid.Row gutter={8}>
              <Grid.Col span={12}>
                <FormItem label="分类：" field="componentClassify" required rules={[
                  {
                    validator(value, cb) {
                      if (!value) {
                        return cb('请选择分类');
                      }

                      return cb();
                    }
                  }
                ]}>
                  <Select
                    placeholder="请选择分类"
                    style={{ width: '90%' }}
                  >
                    {classifyList.map((option, index) => (
                      <Option key={option.id} value={option.label}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                </FormItem>
              </Grid.Col>
              <Grid.Col span={12}>
                <FormItem label="组件语言：" field="codeLanguage" required rules={[
                  {
                    validator(value, cb) {
                      if (!value) {
                        return cb('请选择组件语言');
                      }

                      return cb();
                    }
                  }
                ]}>
                  <Select
                    placeholder="请选择组件语言"
                    style={{ width: '90%' }}
                  >
                    {['Java:8', 'Python:3.10.12'].map((option, index) => (
                      <Option key={option} disabled={index === 3} value={option}>
                        {option}
                      </Option>
                    ))}
                  </Select>
                </FormItem>
              </Grid.Col>
            </Grid.Row>
            <Grid.Row gutter={8}>
              <Grid.Col span={12}>
                <FormItem label="标签：" field="tags">
                  <Select
                    placeholder="请选择标签"
                    allowCreate
                    mode="multiple"
                    style={{ width: '90%' }}
                  >
                    {tagsList.map((option, index) => (
                      <Option key={option.value} value={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                </FormItem>
              </Grid.Col>
              <Grid.Col span={12}>
                <FormItem label="组件类型：" field="type" required rules={[
                  {
                    validator(value, cb) {
                      if (!value) {
                        return cb('请选择组件类型');
                      }

                      return cb();
                    }
                  }
                ]}>
                  <Select
                    placeholder="请选择组件类型"
                    style={{ width: '90%' }}
                  >
                    {['普通组件', '监听组件'].map((option, index) => (
                      <Option key={option} disabled={index === 3} value={option}>
                        {option}
                      </Option>
                    ))}
                  </Select>
                </FormItem>
              </Grid.Col>
            </Grid.Row>

            <div className={styles['markdown-editor']}>
              <div className={styles['markdown-label']}>描述：</div>
              <EditorSection initialContent={description} />
            </div>
          </div>
        </div>

        {showSaveBtn && <div className={styles['last-half']}>
          <div className={styles['last-half-header']}>
            <p> 组件接口</p>
            <Space split={<Divider type="vertical" />}>
              <Button size="small" type="secondary" style={{ borderRadius: 5 }} disabled={true}>代码初始化</Button>
              <Button
                size="mini"
                type="primary"
                style={{ borderRadius: 5 }}
                onClick={() => {
                  setSelectedApiData(null); // 确保新增时清空选中的API数据
                  setShowApiModal(true);
                }}
              >
                + 新增接口
              </Button>
            </Space>
          </div>

          <Table columns={columns} data={componentDesignData} pagination={false} />

          <AddApiModal
            visible={showApiModal}
            baseInfo={componentData || baseInfo}
            componentDesignProgress={selectedApiData} // 添加这一行
            componentDesignData={componentDesignData}
            onUpdateComponentDesign={(params) => {
              // 更新成功后重新获取组件设计数据
              if ((componentData && componentData.id) || (baseInfo && baseInfo.id)) {
                getComponentDesignData(componentData?.id || baseInfo.id);
              }
            }}
            onCancel={() => {
              setShowApiModal(false);
              setSelectedApiData(null); // 重置选中的API数据
            }}
            onOk={() => {
              setShowApiModal(false);
              setSelectedApiData(null); // 重置选中的API数据
            }}
          />
        </div>}
      </Form>
    </Modal>
  );
};

export default AddComponentModal;