import React, { useState, useEffect } from 'react';
import { Button, Input, message } from 'antd';
import produce from 'immer';
import { PREFIX_CLS } from '../../../config';
import { guid, getElementById, SysModel } from '../../../utils';
import './index.less';

const prefixCls = `${PREFIX_CLS}-scroll-to-editor`;
const ScrollTo = ({ event = {}, propValue = {}, node, dispatch, onChange }) => {
  const [value, setValue] = useState(event.targetId);
  const handleChange = e => {
    setValue(e.target.value);
  };
  const add = () => {
    const { type } = event;
    let pluginEvents = propValue[type] || [];
    const newEvent = {
      id: guid(),
      name: 'scrollTo',
      targetId: value,
    };
    pluginEvents = [...pluginEvents, newEvent];
    dispatch({
      type: 'tree/updateByKey',
      payload: {
        key: `events.${type}`,
        id: node.id,
        value: pluginEvents,
      },
    });
    if (onChange) {
      onChange(type, pluginEvents);
    }
  };
  const update = () => {
    const { type, id } = event;
    const nextPropValue = produce(propValue, draft => {
      const existEvent = draft[type].find(p => p.id === id);
      existEvent.targetId = value;
    });
    const pluginEvents = nextPropValue[type];
    dispatch({
      type: 'tree/updateByKey',
      payload: {
        key: `events.${type}`,
        id: node.id,
        value: pluginEvents,
      },
    });
    if (onChange) {
      onChange(type, pluginEvents);
    }
  };
  const handleOk = () => {
    if (!value) {
      message.error('请填写Id');
      return;
    }
    const dom = getElementById(SysModel.DEV, value);
    if (!dom) {
      message.error(`未查找到有id为${value}的组件`);
      return;
    }
    const { id } = event;
    if (id) {
      update();
    } else {
      add();
    }
  };
  useEffect(() => {
    setValue(event.targetId);
  }, [event, propValue]);
  return (
    <>
      <div>滚动到组件ID</div>
      <div>
        <Input value={value} onChange={handleChange} />
      </div>
      <div className={`${prefixCls}__ok`}>
        <Button type="primary" onClick={handleOk}>
          确定
        </Button>
      </div>
    </>
  );
};

export default ScrollTo;
