import React from 'react';
import { connect } from 'react-redux';
import set from 'lodash/set';
import cloneDeep from 'lodash/cloneDeep';
import StyleConfig from '../Component/StyleConfig';
import { getId } from 'utils/interaction';
import { InteractionConfigProvider } from '../Context';
import { Drawer, Utils } from '@easyv/react-gui';
import message from 'components/message';
const { updateArrayWithObject } = Utils;

function ComponentConfig({ visible, id, config = {}, componentsById, onClose, onChange }) {
  if (!id) {
    return null;
  }

  if (Array.isArray(id)) {
    id = id[0];
  }

  id = getId(id);
  const component = componentsById[id];
  const completeConfig =
    component && component.config.filter((d) => (d.name && d.name !== 'interaction') || (d._name && d._name !== 'interaction'));
  const resultConfig = completeConfig && updateArrayWithObject(completeConfig, config);

  const handleStyleChange = (updates) => {
    updates = Array.isArray(updates) ? updates : [updates];
    if (updates.some((d) => d.type === 'add' || d.type === 'delete')) {
      message.error('暂只支持修改配置');
      return;
    }

    const result = cloneDeep(config);

    updates.map((d) => {
      const { path, value } = d;
      set(result, path, value);
    });

    onChange({ value: result, paths: [], key: 'componentConfig' });
  };

  return (
    <Drawer title="组件样式" placement="right" onClose={onClose} visible={visible} width={330}>
      <InteractionConfigProvider updateOnly={true}>
        {resultConfig && <StyleConfig config={resultConfig} onChange={handleStyleChange} />}
      </InteractionConfigProvider>
    </Drawer>
  );
}

const mapStateToProps = ({ componentsById }) => {
  return {
    componentsById
  };
};

export default connect(mapStateToProps)(ComponentConfig);
