import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { NodeEditorProps } from './index';
import { Form, Input, Select, Typography } from '@arco-design/web-react';
import { IconUnorderedList } from '@arco-design/web-react/icon';
import ParamsTable from '@/components/FlowEditor/nodeEditors/components/ParamsTable';
import { queryInstance } from '@/api/components';

const Option = Select.Option;

const BasicNodeEditor: React.FC<NodeEditorProps> = ({
                                                      node,
                                                      nodeData,
                                                      updateNodeData
                                                    }) => {
  const [currentCompInfo, setCurrentCompInfo] = useState(null);
  const [options, setOptions] = useState([]);
  const { projectComponentData, info, currentAppData } = useSelector(state => state.ideContainer);

  const getCurrentProjectStoreData = () => {
    const compData = projectComponentData[currentAppData.sceneId] || {};

    const result: any[] = [];

    // 处理projectCompDto中的数据
    if (compData.projectCompDto) {
      const { mineComp = [], pubComp = [], teamWorkComp = [] } = compData.projectCompDto;

      // 添加mineComp数据
      mineComp.forEach((item: any) => {
        result.push({
          ...item,
          type: 'mineComp'
        });
      });

      // 添加pubComp数据
      pubComp.forEach((item: any) => {
        result.push({
          ...item,
          type: 'pubComp'
        });
      });

      // 添加teamWorkComp数据
      teamWorkComp.forEach((item: any) => {
        result.push({
          ...item,
          type: 'teamWorkComp'
        });
      });
    }

    // 处理projectFlowDto中的数据
    if (compData.projectFlowDto) {
      const { mineFlow = [], pubFlow = [] } = compData.projectFlowDto;

      // 添加mineFlow数据
      mineFlow.forEach((item: any) => {
        result.push({
          ...item,
          type: 'mineFlow'
        });
      });

      // 添加pubFlow数据
      pubFlow.forEach((item: any) => {
        result.push({
          ...item,
          type: 'pubFlow'
        });
      });
    }

    return result;
  };

  const getCompInfo = () => {
    const flatData = getCurrentProjectStoreData();
    const compInfo = flatData.find((item: any) => item.id === nodeData.compId);
    setCurrentCompInfo(compInfo);
  };
  const getCompInstance = async () => {
    const res: any = await queryInstance(nodeData.compId);
    if (res.code === 200) {
      const newOptions = res.data.map((item: any) => {
        return {
          label: item.identifier,
          value: item.identifier,
          runStatus: item.runStatus,
          runType: item.runType
        };
      });
      setOptions(newOptions);
    }
  };
  useEffect(() => {
    getCompInfo();
    getCompInstance();
  }, []);

  // 判断是否为基础组件（基础组件只允许修改默认值）
  const isBaseComponent = nodeData.type === 'BASIC';

  return (
    <Form layout="vertical">
      <Form.Item label="节点标题">
        <Input
          value={nodeData.title || ''}
          onChange={(value) => updateNodeData('title', value)}
        />
      </Form.Item>
      {/*<Form.Item label="描述">*/}
      {/*  <Input.TextArea*/}
      {/*    value={nodeData.description || ''}*/}
      {/*    onChange={(value) => updateNodeData('description', value)}*/}
      {/*  />*/}
      {/*</Form.Item>*/}
      <Typography.Title heading={5}><IconUnorderedList style={{ marginRight: 5 }} />组件信息</Typography.Title>
      <div style={{ display: 'flex', marginTop: 10, marginBottom: 10 }}>
        <span>组件类型：</span>
        <div>{currentCompInfo?.type}</div>
      </div>
      <div style={{ display: 'flex', marginTop: 10, marginBottom: 10 }}>
        <span>组件名称：</span>
        <div>{currentCompInfo?.name}</div>
      </div>
      <div style={{ display: 'flex', marginTop: 10, marginBottom: 10 }}>
        <span>组件描述：</span>
        <div>{currentCompInfo?.description}</div>
      </div>
      <Form.Item label="运行实例（非运行中的实例无法选择）">
        <Select
          value={nodeData?.component?.compIdentifier || ''}
          onChange={(value) => {
            updateNodeData('component', {
              ...nodeData.component,
              compIdentifier: value,
              compInstanceIdentifier: value
            });
          }}
        >
          {options.map((option, index) => (
            <Option key={option.id} value={option.value} disabled={option.runStatus !== 'run'}>
              {option.value}
            </Option>
          ))}
        </Select>
      </Form.Item>
      <Typography.Title heading={5}><IconUnorderedList style={{ marginRight: 5 }} />输入参数</Typography.Title>
      <ParamsTable
        initialData={nodeData.parameters.dataIns || []}
        onUpdateData={(data) => {
          updateNodeData('parameters', {
            ...nodeData.parameters,
            dataIns: data
          });
        }}
        readonly={isBaseComponent}
      />
      <Typography.Title heading={5}><IconUnorderedList style={{ marginRight: 5 }} />输出参数</Typography.Title>
      <ParamsTable
        initialData={nodeData.parameters.dataOuts || []}
        onUpdateData={(data) => {
          updateNodeData('parameters', {
            ...nodeData.parameters,
            dataOuts: data
          });
        }}
        readonly={isBaseComponent}
      />
    </Form>
  );
};

export default BasicNodeEditor;