import React, { useEffect, useState, useCallback, Fragment } from 'react';
import { connect } from 'react-redux';
import classNames from 'classnames';
import QRCode from 'qrcode.react';
import { Switch, Tooltip } from '@easyv/antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import Title from '../../components/Title';
import Loading from '../../components/Loading';
import { appActions } from '../interaction-detail/models';
import logo from '../../../images/logo.png';
import styles from './index.less';
import message from 'components/message';

const boxWidth = 800;
const boxHeight = 680;
const mobileType = {
  ipad: [768, 1024],
  iphone: [1242, 1080, 750]
};

function getUrl(appId) {
  return `${window.location.origin}${BASENAME}/app/detail/${appId}`;
}

function InteractionPreview({ match, loading, name, config, published, limitNetwork, controlCode, getMobile, updateSetting }) {
  const { params } = match;
  const { appId } = params;
  const [url, setUrl] = useState<string>();
  const [controlCodeOpenStatus, setControlCodeOpenStatus] = useState<boolean>(true);

  useEffect(() => {
    getMobile(appId).then((data) => {
      if (!data) return;
      if (data.published) {
        return setUrl(getUrl(appId) + '?controlCode=' + data.controlCode);
      }
      setUrl(getUrl(appId) + '?checkMode=login');
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [appId]);

  useEffect(() => {
    setControlCodeOpenStatus(controlCode === null ? true : controlCode === '' ? false : true);
  }, [controlCode]);

  const onUpdate = useCallback(
    ({ key, value }) => {
      // 只有当开启控制码才检测控制码是否为6位数字
      if ('controlCode' === key && !/^\d{6}$/g.test(value)) {
        return message.error('请输入6位数字控制码');
      }
      const newKey = key === 'controlCodeStatus' ? 'controlCode' : key;
      const newValue = key === 'controlCodeStatus' ? (value === false ? '' : Math.random().toString().slice(2, 8)) : value;
      updateSetting({ key: newKey, value: newValue }).then((data) => {
        if (~['limitNetwork', 'published', 'controlCode'].indexOf(newKey)) {
          // 关闭发布时
          if ('published' === newKey && !newValue) {
            setUrl(getUrl(appId) + '?checkMode=login');
            return;
          } else {
            // 开启和关闭网络控制时 刷新socket房间
            setUrl(getUrl(appId) + '?controlCode=' + data.controlCode + '&random=' + Date.now());
            return;
          }
        }
      });
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [controlCode, limitNetwork, published]
  );

  const { width = 0, height = 0 } = config;
  if (!width || !height) return null;
  const type = mobileType.ipad.indexOf(width) > -1 ? 'ipad' : mobileType.iphone.indexOf(width) > -1 ? 'iphone' : 'custom';

  let scale;
  if (type === 'custom') {
    const xScale = boxWidth / width;
    const yScale = boxHeight / height;
    const minScale = Math.min(xScale, yScale);
    scale = minScale < 1 ? minScale : 1;
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.keyCode === 13) {
      onUpdate({ key: 'controlCode', value: (e.target as HTMLInputElement).value });
    }
  };

  return (
    <div className={styles.container}>
      <Title title={`${name}-预览`} />
      <div className={styles.content}>
        <div
          className={classNames({
            [styles.content__ipad]: type === 'ipad',
            [styles.content__iphone]: type === 'iphone',
            [styles.content__custom]: type === 'custom'
          })}
          style={type === 'custom' ? { width: width * scale, height: height * scale } : {}}>
          <div>
            <iframe className={styles.iframe} src={url} width="100%" height={'100%'} />
          </div>
        </div>
      </div>
      <div className={styles.panel}>
        <img src={logo} className={styles.logo} />
        <div className={styles.panel__body}>
          <div className={styles.setrow}>
            <label style={{ opacity: !published ? 0.6 : 1 }}>
              <span className={classNames(styles.mark, { [styles['mark--active']]: published })}></span>
              {published ? '已发布' : '未发布'}
            </label>
            <div>
              <Switch size="small" checked={published} onChange={(value) => onUpdate({ key: 'published', value })} />
            </div>
          </div>

          {published ? (
            <Fragment>
              <div className={styles.setrow}>
                <label>控制码</label>
                <Switch
                  size="small"
                  checked={controlCodeOpenStatus}
                  onChange={(value) => {
                    setControlCodeOpenStatus(value);
                    onUpdate({ key: 'controlCodeStatus', value });
                  }}
                />
              </div>
              <div className={styles.setrow} style={{ marginLeft: 100 }}>
                {controlCodeOpenStatus ? (
                  <input
                    className={styles.input}
                    type="text"
                    placeholder="请输入6位数字的控制码"
                    defaultValue={controlCode}
                    onKeyDown={handleKeyDown}
                    onBlur={(e) => onUpdate({ key: 'controlCode', value: e.target.value })}
                  />
                ) : null}
              </div>
              <div className={styles.setrow}>
                <Tooltip
                  className={styles.setrow__icon}
                  title={<div style={{ width: 200 }}>当网络限制开启时，在同一个网络环境下的用户才能使用终端设备进行远程控制</div>}>
                  <QuestionCircleOutlined className="whiteHover" />
                </Tooltip>
                <label>网络限制</label>
                <div>
                  <Switch size="small" checked={limitNetwork} onChange={(value) => onUpdate({ key: 'limitNetwork', value })} />
                </div>
              </div>
              {url && (
                <div className={styles.qrcode_wrap}>
                  <span
                    style={{
                      padding: '5px 5px 0px',
                      display: 'inline-block',
                      background: 'white'
                    }}>
                    <QRCode value={getUrl(appId)} size={190} />
                  </span>
                  <h3 className={styles.name}>{name}</h3>
                  <p className={styles.tip}>通过手机或iPad可直接扫描上方二维码进入控制端界面，输入对应控制码即可远程操控</p>
                </div>
              )}
            </Fragment>
          ) : (
            <p className={styles.unpublish_tip}>发布后通过手机或iPad扫描二维码使用终端控制大屏</p>
          )}
        </div>
      </div>
      {loading && <Loading />}
    </div>
  );
}

function mapStateToProps({ interactionDetail }) {
  const { loading, config, name, mobileURL, published, limitNetwork, controlCode } = interactionDetail;
  return {
    loading,
    config,
    name,
    mobileURL,
    published,
    limitNetwork,
    controlCode
  };
}

const mapDispatchToProps = {
  getMobile: appActions.getApp,
  updateSetting: appActions.updatePublishSetting
};

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