import React, { Fragment } from 'react';
import { connect } from 'react-redux';
import QuestionCircleOutlined from '@ant-design/icons/QuestionCircleOutlined';
import { updateSizePositionForSelectedLayers } from 'models/component';
import { updateLayersKey } from 'models/screen';
import MountAnimationConfig from '../Animation/Mount';
import TransformConfig from '../Transform';
import { EasyInput, EasyNumber, EasyBoolean, EasyRange, FormItem, FormGroup, Collapse, Tooltip, EasySelect, Icon } from '@easyv/react-gui';
import { getId } from 'utils/interaction';
import { isGeneralPanel, isGroup, isComponent } from 'utils/utils';
import { flattenToObject, getGroupDimension, getComponentDimension } from 'utils/component';

import styles from '../index.less';

const { Col } = FormGroup;

const timingFunctionOptions = [
  {
    name: '匀速',
    value: 'linear'
  },
  {
    name: '慢快慢',
    value: 'ease'
  },
  {
    name: '慢速开始',
    value: 'ease-in'
  },
  {
    name: '慢速结束',
    value: 'ease-out'
  },
  {
    name: '慢速开始和结束',
    value: 'ease-in-out'
  }
];

function GroupConfiguration({
  groupIds,
  width,
  height,
  top,
  left,
  lock,
  count,
  movable,
  topKey,
  leftKey,
  leftOffset = 0,
  topOffset = 0,
  transitionTime = 0,
  opacity = 1,
  transitionTimingFunction = 'linear',
  transitionDelay = 0,
  hideDefault,
  updateLayersKey,
  onSizePositionChange
}) {
  const updateMultiLayersKey = (key: string, value: string | number | boolean) => {
    const values = groupIds.map((id: string) => {
      return {
        id,
        key,
        value
      };
    });
    updateLayersKey({ values });
  };

  return (
    <div>
      <div className={styles.title}>组配置</div>
      {count > 0 ? (
        <>
          <div className={styles.content} style={{ paddingBottom: 12 }}>
            <FormItem label="位置尺寸">
              <FormGroup>
                <Col span={11}>
                  <EasyNumber
                    min={Number.MIN_SAFE_INTEGER}
                    value={left}
                    onChange={(value: number) => onSizePositionChange({ deltaX: value - left })}
                    suffix="X"
                    showStep={false}
                  />
                </Col>
                <Col span={2} />
                <Col span={11}>
                  <EasyNumber
                    min={Number.MIN_SAFE_INTEGER}
                    value={top}
                    onChange={(value: number) => onSizePositionChange({ deltaY: value - top })}
                    suffix="Y"
                    showStep={false}
                  />
                </Col>
                <Col span={11}>
                  <EasyNumber
                    value={width}
                    min={1}
                    onChange={(value: number) => {
                      if (lock && width && height) {
                        onSizePositionChange({ x: left, y: top, scaleWidth: value / width, scaleHeight: value / width });
                      } else {
                        onSizePositionChange({ x: left, y: top, scaleWidth: value / width });
                      }
                    }}
                    suffix="W"
                    showStep={false}
                  />
                </Col>
                <Col span={2}>
                  <Icon
                    type={lock ? 'lock_on' : 'lock_off'}
                    style={{ fontSize: 20, marginLeft: -6, cursor: 'pointer' }}
                    onClick={() => updateMultiLayersKey('dimensionLock', !lock)}
                  />
                </Col>
                <Col span={11}>
                  <EasyNumber
                    value={height}
                    min={1}
                    onChange={(value: number) => {
                      if (lock && width && height) {
                        onSizePositionChange({ x: left, y: top, scaleHeight: value / height, scaleWidth: value / height });
                      } else {
                        onSizePositionChange({ x: left, y: top, scaleHeight: value / height });
                      }
                    }}
                    suffix="H"
                    showStep={false}
                  />
                </Col>
              </FormGroup>
            </FormItem>

            <FormItem label="默认隐藏">
              <EasyBoolean value={hideDefault} onChange={(value: boolean) => updateMultiLayersKey('hideDefault', value)} />
            </FormItem>
            <FormItem label="透明度">
              <EasyRange
                min={0}
                max={100}
                value={Math.round(opacity * 100)}
                suffix="%"
                onChange={(value: number) => updateMultiLayersKey('opacity', value / 100)}
              />
            </FormItem>
          </div>
          <Collapse
            disabled={!movable}
            header={
              <div className="flex-between" style={{ flex: 1 }}>
                <span>
                  动态坐标{' '}
                  <Tooltip title="组的位置通过回调值来显示">
                    <QuestionCircleOutlined className="whiteHover" style={{ cursor: 'pointer' }} />
                  </Tooltip>
                </span>

                <i
                  className={`icon iconfont icon-${movable ? 'eye_on' : 'eye_off'}`}
                  style={{ cursor: 'pointer' }}
                  onClick={(e) => {
                    e.stopPropagation();
                    updateMultiLayersKey('movable', !movable);
                  }}
                />
              </div>
            }>
            {movable && (
              <Fragment>
                <FormItem label="回调字段">
                  <FormGroup>
                    <Col span={12}>
                      <FormItem label="坐标X" mode="vertical" style={{ padding: 0 }}>
                        <EasyInput value={leftKey} onChange={(value: string) => updateMultiLayersKey('leftKey', value)} />
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem label="坐标Y" mode="vertical" style={{ padding: 0 }}>
                        <EasyInput value={topKey} onChange={(value: string) => updateMultiLayersKey('topKey', value)} />
                      </FormItem>
                    </Col>
                  </FormGroup>
                </FormItem>
                <FormItem label="偏移量">
                  <FormGroup>
                    <Col span={12}>
                      <FormItem label="X方向" mode="vertical" style={{ padding: 0 }}>
                        <EasyNumber value={leftOffset} onChange={(value: string) => updateMultiLayersKey('leftOffset', value)} />
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem label="Y方向" mode="vertical" style={{ padding: 0 }}>
                        <EasyNumber value={topOffset} onChange={(value: string) => updateMultiLayersKey('topOffset', value)} />
                      </FormItem>
                    </Col>
                  </FormGroup>
                </FormItem>

                <FormItem label="动效">
                  <FormGroup>
                    <Col span={24}>
                      {/* <FormItem label="速率" mode="vertical" style={{ padding: 0 }}> */}
                      <EasySelect
                        value={transitionTimingFunction}
                        options={timingFunctionOptions}
                        onChange={(value: string) => updateMultiLayersKey('transitionTimingFunction', value)}
                      />
                      {/* </FormItem> */}
                    </Col>
                    <Col span={12}>
                      <FormItem label="动画时长" mode="vertical" style={{ padding: 0 }}>
                        <EasyNumber
                          suffix="s"
                          showStep={true}
                          value={transitionTime}
                          onChange={(value: number) => updateMultiLayersKey('transitionTime', value)}
                        />
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem label="延迟" mode="vertical" style={{ padding: 0 }}>
                        <EasyNumber
                          suffix="s"
                          showStep={true}
                          value={transitionDelay}
                          onChange={(value: number) => updateMultiLayersKey('transitionDelay', value)}
                        />
                      </FormItem>
                    </Col>
                  </FormGroup>
                </FormItem>
              </Fragment>
            )}
          </Collapse>
          {/* 3D变换 */}
          <TransformConfig />
          {/* 载入动画 */}
          <MountAnimationConfig />
        </>
      ) : (
        <div className={styles.none}>组内无组件</div>
      )}
    </div>
  );
}

function mapStateToProps({ createApp, panelsById, componentsById, screensById }) {
  const { layersSelected, id: screenId } = createApp;
  const layersById = flattenToObject(screensById[screenId].layers);
  const groupId = layersSelected[0];
  const groupIds = layersSelected.filter((id) => isGroup(id));
  const groupInfo = layersById[groupId] || {};

  const {
    movable,
    topKey,
    leftKey,
    topOffset,
    leftOffset,
    transitionTime,
    hideDefault,
    opacity,
    transitionTimingFunction,
    transitionDelay,
    dimensionLock
  } = groupInfo;

  const getGroupComponentsDimension = (components = []) => {
    return components.reduce((all: any, item: any) => {
      if (isComponent(item.id)) {
        if (componentsById[item.id]) {
          return all.concat({ id: item.id, ...getComponentDimension(componentsById[item.id].config) });
        } else {
          return all;
        }
      } else if (isGroup(item.id)) {
        return all.concat(getGroupComponentsDimension(item.components));
      } else if (isGeneralPanel(item.id)) {
        const panel = panelsById[getId(item.id) as number];
        if (panel) {
          const { config } = panel;
          const { width, height, left, top } = config;

          return all.concat({
            id: item.id,
            width,
            height,
            left,
            top,
            config
          });
        } else {
          return all;
        }
      }
    }, []);
  };
  const dimensions = getGroupComponentsDimension(groupInfo.components);
  const { width, height, top, left } = getGroupDimension(dimensions);

  return {
    groupId,
    groupIds,
    width,
    height,
    top,
    left,
    lock: dimensionLock,
    count: dimensions.length,
    movable,
    topKey,
    leftKey,
    topOffset,
    leftOffset,
    transitionTime,
    hideDefault,
    opacity,
    transitionTimingFunction,
    transitionDelay
  };
}

const mapDispatchToProps = {
  onSizePositionChange: updateSizePositionForSelectedLayers,
  updateLayersKey
};

export default connect(mapStateToProps, mapDispatchToProps)(GroupConfiguration);
