import React, { useState } from 'react';
import EasyGUI, { Utils } from '@easyv/react-gui';
import customTrigger from 'constants/default-custom-triggers';
import { generateId } from 'utils/utils';
import { updateTriggers } from 'models/component';
import { connect } from 'react-redux';

interface triggerItem {
  name: string;
  value: string;
}
const { updateArrayConfig, transformConfig } = Utils;

const { template } = customTrigger[0].config;

function CustomTrigger({
  triggers,
  onChange,
  componentId,
}: {
  triggers: triggerItem[];
  componentId: number;
  onChange: ({ triggers: any, id: number }) => Promise<any>;
}): React.ReactElement {
  const [config, setConfig] = useState(() => {
    return customTrigger.map((d) => {
      return {
        ...d,
        value: triggers.map((d) => {
          return {
            ...template[0],
            name: `${template[0].name}_${generateId()}`,
            value: [
              {
                ...template[0].value[0],
                value: d.name,
              },
              {
                ...template[0].value[1],
                value: d.value,
              },
            ],
          };
        }),
      };
    });
  });

  const getTriggers = (newInteractionConfig) => {
    const [newConfig] = transformConfig(newInteractionConfig);
    let _triggers = newConfig
      ? newConfig?.value.map((d) => {
          const [nameItem, valueItem] = d.value;
          return {
            name: nameItem.value,
            value: valueItem.value,
          };
        })
      : [];
    if (!_triggers.filter((d) => d.name && d.value).length) {
      // 有效值小于0
      _triggers = [];
    }
    return _triggers;
  };
  const handleFieldsChange = async (updates) => {
    const newConfig = updateArrayConfig(config, updates);
    const _triggers = getTriggers(newConfig);
    setConfig(newConfig);
    onChange({ triggers: _triggers, id: componentId });
  };
  return <EasyGUI config={config} onFieldsChange={handleFieldsChange} />;
}

export default connect(undefined, {
  onChange: updateTriggers,
})(CustomTrigger);
