import React, { Fragment, useEffect } from 'react';
import { connect } from 'react-redux';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { updateLayersKey } from 'models/screen';
import { findLayerById } from 'utils/layer';
import { isGroup } from 'utils/utils';
import { Icon, Collapse, EasyNumber, EasyRange, FormItem, FormGroup, Tooltip, EasySelect, EasyPosition } from '@easyv/react-gui';

const { Col } = FormGroup;

const typeOptions = [
  {
    name: '自定义',
    value: 'custom'
  },
  {
    name: '等角-上方（斜向下）',
    value: '1'
  },
  {
    name: '等角-上方（斜向上）',
    value: '2'
  },
  {
    name: '等角-左方',
    value: '3'
  },
  {
    name: '等角-右方',
    value: '4'
  }
];

function Header({ open, onChange }) {
  return (
    <div className="flex-between" style={{ flex: 1 }}>
      <span>
        <span style={{ marginRight: 6 }}>3D变换</span>
        <Tooltip title="当前阶段，组件3D变换与样式内混合模式可能存在冲突，导致图层混合不生效（如滤色去黑色背景），若组件内有运用可先行关闭；">
          <QuestionCircleOutlined className="whiteHover" />
        </Tooltip>
      </span>

      <span
        style={{ cursor: 'pointer' }}
        onClick={(e) => {
          e.stopPropagation();
          onChange({ open: !open });
        }}>
        <Icon type={open ? 'eye_on' : 'eye_off'} />
      </span>
    </div>
  );
}

let localConf = {};
function TransformConfig({ id, ids, config = {}, updateLayersKey }: { id: any; ids: any; config: any; updateLayersKey: (param) => any }) {
  const {
    rotate = {},
    scale = {},
    skewX = 0,
    skewY = 0,
    translate = {},
    perspective = 500,
    open = false,
    type = 'custom',
    perspectiveOrigin = [0.5, 0.5]
  } = config;
  const { x: rotateX = 0, y: rotateY = 0, z: rotateZ = 0 } = rotate;
  const { x: scaleX = 1, y: scaleY = 1, lock = true } = scale;
  const { x: translateX = 0, y: translateY = 0, z: translateZ = 0 } = translate;

  if (ids.length <= 0) {
    ids.push(id);
  }

  useEffect(() => {
    localConf = JSON.parse(JSON.stringify(config));
  }, [config]);

  const handleChange = (value) => {
    const values = ids.map((id) => {
      return {
        id,
        key: 'transform',
        value: {
          ...localConf,
          ...value
        }
      };
    });
    updateLayersKey({ values });
  };

  return (
    <Collapse disabled={!open} header={<Header open={open} onChange={handleChange} />}>
      {open && (
        <Fragment>
          <FormItem label="类型">
            <EasySelect value={type} options={typeOptions} onChange={(value) => handleChange({ type: value })} />
          </FormItem>
          {type === 'custom' && (
            <Fragment>
              <FormItem label="透视距离">
                <EasyNumber value={perspective} showStep={true} onChange={(value) => handleChange({ perspective: value })} suffix="px" />
              </FormItem>
              <FormItem label="视点位置">
                <EasyPosition
                  value={perspectiveOrigin}
                  onChange={(value) => {
                    handleChange({ perspectiveOrigin: value });
                  }}
                />
              </FormItem>
              <FormItem label="旋转">
                <FormGroup>
                  <Col span={24}>
                    <FormItem mode="vertical" label="绕X轴" align="left" style={{ padding: 0 }}>
                      <EasyRange
                        value={rotateX}
                        min={-180}
                        max={180}
                        onChange={(value) => handleChange({ rotate: { ...rotate, x: value } })}
                        suffix="°"
                      />
                    </FormItem>
                  </Col>
                  <Col span={24}>
                    <FormItem mode="vertical" label="绕Y轴" align="left" style={{ padding: 0 }}>
                      <EasyRange
                        value={rotateY}
                        min={-180}
                        max={180}
                        onChange={(value) => handleChange({ rotate: { ...rotate, y: value } })}
                        suffix="°"
                      />
                    </FormItem>
                  </Col>
                  <Col span={24}>
                    <FormItem mode="vertical" label="绕Z轴" align="left" style={{ padding: 0 }}>
                      <EasyRange
                        value={rotateZ}
                        min={-180}
                        max={180}
                        onChange={(value) => handleChange({ rotate: { ...rotate, z: value } })}
                        suffix="°"
                      />
                    </FormItem>
                  </Col>
                </FormGroup>
              </FormItem>
              <FormItem label="缩放">
                <FormGroup>
                  <Col span={11}>
                    <FormItem mode="vertical" label="X" style={{ padding: 0 }}>
                      <EasyNumber
                        min={0}
                        value={Math.round(scaleX * 100)}
                        onChange={(value) => {
                          let ratio = scaleX / scaleY;
                          ratio = isNaN(ratio) || ratio === Infinity ? 1 : ratio;

                          handleChange({
                            scale: { ...scale, x: value / 100, y: lock ? value / 100 / ratio : scaleY }
                          });
                        }}
                        suffix="%"
                        showStep={false}
                      />
                    </FormItem>
                  </Col>
                  <Col span={2} style={{ textAlign: 'center' }}>
                    <Icon
                      type={lock ? 'lock_on' : 'lock_off'}
                      style={{ fontSize: 20, marginLeft: -6, cursor: 'pointer' }}
                      onClick={() => handleChange({ scale: { ...scale, lock: !lock } })}
                    />
                  </Col>
                  <Col span={11}>
                    <FormItem mode="vertical" label="Y" style={{ padding: 0 }}>
                      <EasyNumber
                        min={0}
                        value={Math.round(scaleY * 100)}
                        onChange={(value) => {
                          let ratio = scaleX / scaleY;
                          ratio = isNaN(ratio) || ratio === Infinity ? 1 : ratio;
                          handleChange({
                            scale: { ...scale, y: value / 100, x: lock ? ratio * (value / 100) : scaleX }
                          });
                        }}
                        suffix="%"
                        showStep={false}
                      />
                    </FormItem>
                  </Col>
                </FormGroup>
              </FormItem>
              <FormItem label="斜切">
                <FormGroup>
                  <Col span={24}>
                    <FormItem mode="vertical" label="X方向[-90,90]" align="left" style={{ padding: 0 }}>
                      <EasyRange min={-90} max={90} value={skewX} onChange={(value) => handleChange({ skewX: value })} suffix="°" />
                    </FormItem>
                  </Col>
                  <Col span={24}>
                    <FormItem mode="vertical" label="Y方向[-90,90]" align="left" style={{ padding: 0 }}>
                      <EasyRange min={-90} max={90} value={skewY} onChange={(value) => handleChange({ skewY: value })} suffix="°" />
                    </FormItem>
                  </Col>
                </FormGroup>
              </FormItem>
              <FormItem label="平移">
                <FormGroup>
                  <Col span={8}>
                    <FormItem mode="vertical" label="X" style={{ padding: 0 }}>
                      <EasyNumber value={translateX} onChange={(value) => handleChange({ translate: { ...translate, x: value } })} />
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem mode="vertical" label="Y" style={{ padding: 0 }}>
                      <EasyNumber value={translateY} onChange={(value) => handleChange({ translate: { ...translate, y: value } })} />
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem mode="vertical" label="Z" style={{ padding: 0 }}>
                      <EasyNumber value={translateZ} onChange={(value) => handleChange({ translate: { ...translate, z: value } })} />
                    </FormItem>
                  </Col>
                </FormGroup>
              </FormItem>
            </Fragment>
          )}
        </Fragment>
      )}
    </Collapse>
  );
}

const mapStateToProps = ({ createApp, screensById }) => {
  const { id, layersSelected } = createApp;
  const screen = screensById[id];
  const layerId = layersSelected[0];
  const layerIds = layersSelected.filter((id) => isGroup(id));

  let config;
  if (screen) {
    const { layers } = screen;
    const layer = findLayerById({ id: layerId, layers });
    config = layer.transform;
  }
  return {
    id: layerId,
    ids: layerIds,
    config
  };
};

const mapDispatchToProps = {
  updateLayersKey
};

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