import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import PlyrPlayer from '../components/public/PlyrPlayer';
import { useTranslation } from 'react-i18next';
import FPlatformEnum from '../utils/enum';

export default function VideoPlayer() {
  // 解码 base64 化的视频 url:
  // 例如 aHR0cDovL3NmMS1oc2Nkbi10b3MucHN0YXRwLmNvbS9vYmovbWVkaWEtZmUveGdwbGF5ZXJfZG9jX3ZpZGVvL2Zsdi94Z3BsYXllci1kZW1vLTM2MHAuZmx2
  // 解码结果是 http://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/flv/xgplayer-demo-360p.flv
  const decodeFileUrl = (url) => {
    const decodedUrl = atob(url);
    return decodedUrl;
  };
  const { fileUrl, platform, language } = useParams();
  const { t, i18n } = useTranslation();

  const [plyrProps, setPlyrProps] = useState({
    source: {
      type: 'video',
      title: 'Video',
      sources: [
        {
          src: decodeFileUrl(fileUrl),
          type: 'video/mp4',
          size: 720,
        },
      ],
    }, // https://github.com/sampotts/plyr#the-source-setter
    options: {
      playsinline: true,
    }, // https://github.com/sampotts/plyr#options
  });

  useEffect(() => {
    i18n.changeLanguage(language);
  }, [i18n, language]);

  useEffect(() => {
    setPlyrProps({
      source: {
        type: 'video',
        title: 'Video',
        sources: [
          {
            src: decodeFileUrl(fileUrl),
            type: 'video/mp4',
            size: 720,
          },
        ],
        // poster:  '/img/loading.svg',
        poster: decodeFileUrl(fileUrl),
      },
      options: {
        muted: FPlatformEnum.byIndex(platform).isWeb() ? true : false, //  web 平台默认静音，可以自动播放
        autoplay: true,
        hideControls: false,
        controls: [
          'play',
          'progress',
          'current-time',
          FPlatformEnum.byIndex(platform).isWeb() ? 'duration' : '', // 移动端屏幕小，不显示视频总时长
          'mute',
          'settings',
          'fullscreen',
        ],
        i18n: {
          speed: t('播放速度'),
          normal: t('正常'),
        },
        speed: {
          selected: 1,
          options: [2, 1.5, 1.25, 1, 0.5],
        },
        fullscreen: {
          enabled: true,
          iosNative: true,
        },
        playsinline: true,
      }, // https://github.com/sampotts/plyr#options
    });
  }, [fileUrl, platform, t]);

  return (
    <div>
      <div
        className={
          FPlatformEnum.byIndex(platform).isWeb()
            ? 'plyr-wrapper-16-9'
            : 'plyr-wrapper-1-1'
        }>
        <PlyrPlayer plyrProps={plyrProps} />
      </div>
    </div>
  );
}
