import React, { Fragment, useMemo } from 'react';
import { connect } from 'react-redux';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { updateLayersKey } from 'models/screen';
import { updateVersion } from 'models/updateVersion';
import { findLayerById } from 'utils/layer';
import style from './Mount.less';
import { redirectToUpgrade, isGroup } from 'utils/utils';
import { Collapse, EasySelect, FormItem, EasyNumber, EasyBoolean, Tooltip } from '@easyv/react-gui';
import IconButton from 'components/IconButton';
import { useProductionInfo } from 'components/easyUse';
import { useAuth } from 'components/easyUse';

function Header({ productVersion, updateVersion }: { updateVersion: (x: any) => void; productVersion: string | false }) {
  const productionInfo = useProductionInfo();
  const { isRenew } = productionInfo;
  const { checkAuth } = useAuth();
  const onUpdateChange = (e) => {
    e.stopPropagation();
    if (productVersion) {
      updateVersion({
        show: true,
        targetVersion: 'saas_advanced'
      });
    }
  };
  return (
    <div>
      <span style={{ marginRight: 6 }}>载入动画</span>
      <Tooltip title="当前阶段，组件载入动画与样式内混合模式可能存在冲突，导致图层混合不生效（如滤色去黑色背景），若组件内有运用可先行关闭；">
        <QuestionCircleOutlined className="whiteHover" />
      </Tooltip>
      {window.appConfig.LOCAL || checkAuth('mountAnimation') ? null : (
        <span onClick={onUpdateChange} style={{ marginLeft: 6 }} className={style.editionLock}>
          <IconButton style={{ display: 'inline-block' }} type={isRenew ? 'renew_advanced' : 'saas_advanced'} />
        </span>
      )}
    </div>
  );
}

function MountAnimationConfig({
  id,
  ids,
  config = {},
  supportAnimation,
  updateLayersKey,
  updateVersion,
  productVersion,
  skuId
}: {
  id: number;
  ids: number[];
  config: any;
  productVersion: string;
  supportAnimation: boolean;
  skuId: number;
  updateVersion: (param) => any;
  updateLayersKey: (param) => any;
}) {
  const { type = 'none', timingFunction = 'linear', direction = 'left', duration = 300, delay = 0, opacityOpen = false } = config;
  const whiteList = ['saas_advanced', 'saas_vip', 'saas_personal'];
  const _disabled = useMemo(() => {
    return !(window.appConfig.LOCAL || whiteList.includes(productVersion));
  }, [productVersion]);

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

  const handleChange = (value) => {
    if (!supportAnimation) {
      redirectToUpgrade(skuId);
    } else {
      const values = ids.map((id) => {
        return {
          id,
          key: 'mountAnimation',
          value: {
            ...config,
            ...value
          }
        };
      });
      updateLayersKey({ values });
    }
  };

  return (
    <Collapse header={<Header updateVersion={updateVersion} productVersion={_disabled && productVersion} />}>
      <div>
        <FormItem label="动画类型">
          <EasySelect
            value={type}
            disabled={_disabled}
            options={[
              { name: '无', value: 'none' },
              { name: '移入', value: 'slide' },
              { name: '移入(小)', value: 'slideSmall' },
              { name: '划变', value: 'wipe' }
            ]}
            onChange={(value) => handleChange({ type: value })}
          />
        </FormItem>
      </div>
      {type !== 'none' && (
        <Fragment>
          <FormItem label="渐隐渐现">
            <EasyBoolean value={opacityOpen} onChange={(checked) => handleChange({ opacityOpen: checked })} />
          </FormItem>
          <FormItem label="速率">
            <EasySelect
              options={[
                { name: '匀速', value: 'linear' },
                { name: '慢快慢', value: 'ease' },
                { name: '低速开始', value: 'ease-in' },
                { name: '低速结束', value: 'ease-out' },
                { name: '低速开始和结束', value: 'ease-in-out' }
              ]}
              value={timingFunction}
              onChange={(value) => handleChange({ timingFunction: value })}
            />
          </FormItem>
          <FormItem label="方向">
            <EasySelect
              options={[
                { name: '从左至右', value: 'left' },
                { name: '从右至左', value: 'right' },
                { name: '从上至下', value: 'down' },
                { name: '从下至上', value: 'up' },
                { name: '从左上至右下', value: 'leftDown' },
                { name: '从右上至左下', value: 'rightDown' },
                { name: '从左下至右上', value: 'leftUp' },
                { name: '从右下至左上', value: 'rightUp' }
              ]}
              value={direction}
              className="dark"
              dropdownClassName="dark"
              style={{ width: '100%' }}
              onChange={(value) => handleChange({ direction: value })}
            />
          </FormItem>
          <FormItem label="持续时间(ms)">
            <EasyNumber value={duration} onChange={(value) => handleChange({ duration: value })} />
          </FormItem>
          <FormItem label="延时(ms)">
            <EasyNumber value={delay} onChange={(value) => handleChange({ delay: value })} />
          </FormItem>
        </Fragment>
      )}
    </Collapse>
  );
}

const mapStateToProps = ({ createApp, screensById, user }) => {
  const { id, layersSelected } = createApp;
  const screen = screensById[id];
  const layerId = layersSelected[0];
  const layerIds = layersSelected.filter((id) => isGroup(id));
  const { edition = {} } = user.userInfo;
  const { supportAnimation = true } = edition;
  const productVersion = edition && edition?.id;

  let config;
  if (screen) {
    const { layers } = screen;
    const layer = findLayerById({ id: layerId, layers });
    if (layer) {
      config = layer.mountAnimation;
    }
  }

  return {
    id: layerId,
    ids: layerIds,
    productVersion,
    config,
    skuId: user.userInfo?.skuId,
    supportAnimation: window.appConfig.LOCAL ? true : supportAnimation
  };
};

const mapDispatchToProps = {
  updateLayersKey,
  updateVersion
};

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