import React, { useState, useMemo, useEffect } from 'react';
import { Button } from '@easyv/antd';
import classNames from 'classnames';
import defaultTriggers from 'constants/default-triggers';
import { CollapseTabs, EasySelect, FormItem } from '@easyv/react-gui';
import ActionConfig from './ActionConfig';
import { generateId, updateDataByKey } from 'utils/utils';
import styles from './index.less';
import EasyvTooltip from 'components/EasyvTooltip';

const { TabPane } = CollapseTabs;

export const defaultAction = {
  name: '动作',
  action: 'show',
  actionData: {},
  component: [],
  stateId: '',
  componentScope: 'current',
  componentConfig: {},
  unmount: true,
  animation: {
    type: 'opacity',
    timingFunction: 'linear',
    duration: 1000,
    delay: 0
  },
  translate: {
    toX: 0,
    toY: 0
  },
  scale: {
    x: 1,
    y: 1,
    origin: '50% 50%',
    lock: true
  }
};

const EventConfig = (props) => {
  const { tooltipData, triggers = [], value = {}, onChange, onConditionEditShow, actionId } = props;
  const [activeKey, setActiveKey] = useState<string | number>();
  let actions = Array.isArray(value.actions) && value.actions.filter((d) => d.id && d.name);

  useEffect(() => {
    if (actionId && Array.isArray(actions)) {
      const value = actions.find((d) => d.id === actionId);
      value && setActiveKey(value.id);
    }
  }, [actions, actionId]);

  const { stateId, action, component, actionData, componentConfig, componentScope, scale, translate, unmount, animation, ...rest } = value;
  if (!Array.isArray(actions)) {
    actions = [
      {
        id: `action_${generateId()}`,
        name: '动作',
        component: Array.isArray(component) ? component : [],
        stateId: stateId,
        action: action,
        actionData: actionData,
        componentConfig: componentConfig,
        componentScope: componentScope,
        scale: scale,
        translate: translate,
        unmount: unmount,
        animation: animation
      }
    ];
  }

  const handleAdd = async (key) => {
    const newKey = `action_${generateId()}`;
    if (Array.isArray(value.actions)) {
      let newValue;
      // 如果当前有事件，则以当前事件来复制，没有的话则以默认值
      if (actions.length) {
        const action = actions.find((d) => d.id === key);
        newValue = { ...action, id: newKey };
      } else {
        newValue = { ...defaultAction, id: newKey };
      }

      await onChange({ paths: ['actions'], value: newValue, key: actions.length });
    } else {
      // 兼容老版本平铺的action
      const newAction = actions.concat();
      await onChange({
        paths: [],
        value: {
          ...rest,
          actions: newAction.concat({ ...newAction[0], id: newKey })
        }
      });
    }
    return newKey;
  };

  const handleDelete = async (key) => {
    if (Array.isArray(value.actions)) {
      const keyIndex = actions.findIndex((d) => d.id === key);
      const newKey = keyIndex > 0 ? actions[keyIndex - 1].id : actions[keyIndex + 1] ? actions[keyIndex + 1].id : '';
      await onChange({ paths: ['actions'], key: keyIndex });
      return newKey;
    } else {
      // 兼容老版本平铺的action
      await onChange({
        paths: [],
        value: {
          ...rest,
          actions: []
        }
      });
      return '';
    }
  };

  const handleSort = ({ oldIndex, newIndex }) => {
    if (Array.isArray(value.actions)) {
      const newEvents = actions.concat();
      const target = newEvents.splice(oldIndex, 1);
      newEvents.splice(newIndex, 0, target[0]);
      onChange({ paths: ['actions'], value: newEvents });
    } else {
      onChange({
        paths: [],
        value: {
          ...rest,
          actions: actions
        }
      });
    }
  };

  const handleActionChange = (index, updated) => {
    updated = Array.isArray(updated) ? updated : [updated];
    if (Array.isArray(value.actions)) {
      onChange(updated.map((d) => ({ ...d, paths: ['actions', index].concat(d.paths) })));
      // 兼容老版本平铺的action
    } else {
      let newAction = actions.concat();
      updated.map((d) => {
        newAction = updateDataByKey({ data: newAction, paths: [0].concat(d.paths), key: d.key, value: d.value });
      });
      onChange({
        paths: [],
        value: {
          ...rest,
          actions: newAction
        }
      });
    }
  };

  const triggerOptions = useMemo(() => defaultTriggers.concat(triggers), [triggers]);

  return (
    <>
      <FormItem label="事件类型">
        <EasySelect options={triggerOptions} value={value.trigger} onChange={(value) => onChange({ paths: [], value, key: 'trigger' })} />
      </FormItem>
      <FormItem label="条件">
        <div className={classNames(styles.conditions, { [styles.more]: value.conditions.length > 1 })}>
          {value.conditions.length > 0 && (
            <div className={classNames(styles.box, { [styles.only]: value.conditions.length === 1 })}>
              {value.conditions.map((o) => (
                <EasyvTooltip title={o.name} placement="top" key={o.id}>
                  <p className={styles.condition} onClick={() => onConditionEditShow(o.id)}>
                    <span className={styles.conditionName}>{o.name}</span>
                    <span>&gt;</span>
                  </p>
                </EasyvTooltip>
              ))}
              {value.conditions.length > 1 && <div className={styles.symbol}>{value.conditionType === 'all' ? '且' : '或'}</div>}
            </div>
          )}

          <Button type="primary" ghost style={{ height: 28, width: '100%', lineHeight: 1 }} onClick={() => onConditionEditShow()}>
            添加条件
          </Button>
        </div>
      </FormItem>

      <CollapseTabs
        header={<span style={{ flex: 1 }}>动作</span>}
        onAdd={handleAdd}
        onDelete={handleDelete}
        activeKey={activeKey}
        onSort={handleSort}
        bordered={false}
        defaultCollapsed={false}>
        {actions.map((d, i) => {
          return (
            <TabPane tab={`${d.name}${i + 1}`} key={d.id}>
              <ActionConfig key={d.id} value={d} tooltipData={tooltipData} onChange={(updated) => handleActionChange(i, updated)} />
            </TabPane>
          );
        })}
      </CollapseTabs>
    </>
  );
};

export default EventConfig;
