import _regeneratorRuntime from 'babel-runtime/regenerator';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

import React, { forwardRef, useRef, useImperativeHandle, useEffect, useState, useContext } from 'react';
import { createPortal } from 'react-dom';
import Context from './../Context/instance.js';

var VideoFull = forwardRef(function (_ref, ref) {
  // 实例化
  var initInstance = function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      var _extends2;

      var e, data;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (src) {
                _context.next = 4;
                break;
              }

              console.error(locale('请传入视频源', 'hint_video_src'));
              if (onError) onError(e, { errMsg: locale('请传入视频源', 'hint_video_src') });
              return _context.abrupt('return');

            case 4:
              _context.next = 6;
              return loadSdk();

            case 6:
              if (_context.sent) {
                _context.next = 10;
                break;
              }

              console.error(locale('加载播放器库出错, 请稍后再试', 'hint_video_sdk_load_failed'));
              if (onError) onError(e, { errMsg: locale('加载播放器库出错, 请稍后再试', 'hint_video_sdk_load_failed') });
              return _context.abrupt('return');

            case 10:
              if (window.Aliplayer) {
                _context.next = 13;
                break;
              }

              setTimeout(function () {
                initInstance();
              }, 1000);
              return _context.abrupt('return');

            case 13:
              e = { target: refEl.current
                // const width = refEl.current.clientWidth;
                // const height = refEl.current.clientHeight;
                // 构建参数
              };
              data = _extends((_extends2 = {
                id: idSdkPlayer,
                source: src,
                // 样式设置
                width: '100%',
                height: '100%',
                videoWidth: '100%',
                videoHeight: '100%',
                skinLayout: getSkinLayout(),
                // 控件设置
                autoplay: autoPlay,
                controlBarVisibility: 'click',
                showBarTime: 3000,
                // 播放设置
                isLive: isLive,
                preload: true,
                playsinline: navigator.userAgent.toLowerCase().match(/cpu iphone os (.*?) like mac os/) ? true : false,
                showBuffer: true,
                defaultDefinition: 'FD'
              }, _extends2['source'] = src, _extends2.useH5Prism = true, _extends2.useFlashPrism = false, _extends2.cover = poster, _extends2.x5_type = 'h5', _extends2.x5_fullscreen = false, _extends2), params);

              instance.current = new Aliplayer(data, function (player) {
                if (bar) {
                  attachBar(player);
                }
                if (autoPlay) {
                  player.play();
                }
              });
              refEl.current.instance = instance;
              if (onLoad) onLoad(e, instance.current);

            case 18:
            case 'end':
              return _context.stop();
          }
        }
      }, _callee, this);
    }));

    return function initInstance() {
      return _ref2.apply(this, arguments);
    };
  }();

  var portal = _ref.portal,
      _ref$scriptSDK = _ref.scriptSDK,
      scriptSDK = _ref$scriptSDK === undefined ? '//g.alicdn.com/de/prismplayer/2.8.8/aliplayer-min.js' : _ref$scriptSDK,
      _ref$cssSDK = _ref.cssSDK,
      cssSDK = _ref$cssSDK === undefined ? '//g.alicdn.com/de/prismplayer/2.8.8/skins/default/aliplayer-min.css' : _ref$cssSDK,
      _ref$poster = _ref.poster,
      poster = _ref$poster === undefined ? '' : _ref$poster,
      src = _ref.src,
      _ref$autoPlay = _ref.autoPlay,
      autoPlay = _ref$autoPlay === undefined ? true : _ref$autoPlay,
      pause = _ref.pause,
      isLive = _ref.isLive,
      params = _ref.params,
      onError = _ref.onError,
      onLoad = _ref.onLoad,
      bar = _ref.bar,
      children = _ref.children,
      others = _objectWithoutProperties(_ref, ['portal', 'scriptSDK', 'cssSDK', 'poster', 'src', 'autoPlay', 'pause', 'isLive', 'params', 'onError', 'onLoad', 'bar', 'children']);

  // context
  var context = useContext(Context) || {};
  var locale = context.locale || function (key) {
    return key || '';
  };

  var refEl = useRef(null);
  useImperativeHandle(ref, function () {
    return refEl.current;
  });
  var instance = useRef(null);

  var _useState = useState(''),
      idSdkPlayer = _useState[0],
      setIdSdkPlayer = _useState[1];

  var idSdkCss = '_seedsui_videofull_css_';
  var idSdkScript = '_seedsui_videofull_script_';

  function loadSdk() {
    return new Promise(function (resolve) {
      var css = document.getElementById(idSdkCss);
      if (!css) {
        var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.id = idSdkCss;
        link.href = cssSDK;
        link.setAttribute('rel', 'stylesheet');
        link.setAttribute('type', 'text/css');
        head.appendChild(link);
      }
      var script = document.getElementById(idSdkScript);
      if (!script) {
        script = document.createElement('script');
        script.id = idSdkScript;
        script.type = 'text/javascript';
        script.charset = 'utf-8';
        script.src = scriptSDK;
        document.body.appendChild(script);
        script.onload = function () {
          resolve(true);
        };
        script.onerror = function () {
          resolve(false);
        };
      } else {
        resolve(true);
      }
    });
  }

  // 视频控件样式修改
  function getSkinLayout() {
    if (isLive) {
      return [{
        name: 'bigPlayButton', align: 'cc'
      }, {
        name: 'controlBar', align: 'blabs', x: 0, y: 0,
        children: [{ name: 'progress', align: 'tlabs', x: 0, y: 0 }, { name: 'playButton', align: 'tl', x: 15, y: 26 }, { name: 'nextButton', align: 'tl', x: 10, y: 26 }, { name: 'timeDisplay', align: 'tl', x: 10, y: 24 }, { name: 'fullScreenButton', align: 'tr', x: 10, y: 25 }, { name: 'streamButton', align: 'tr', x: 10, y: 23 }, { name: 'volume', align: 'tr', x: 10, y: 25 }]
      }, {
        name: 'fullControlBar', align: 'tlabs', x: 0, y: 0,
        children: [{ name: 'fullTitle', align: 'tl', x: 25, y: 6 }, { name: 'fullNormalScreenButton', align: 'tr', x: 24, y: 13 }, { name: 'fullTimeDisplay', align: 'tr', x: 10, y: 12 }, { name: 'fullZoom', align: 'cc' }]
      }];
    }
    return [{
      name: 'bigPlayButton', align: 'cc'
    }, {
      name: 'H5Loading', align: 'cc'
    }, {
      name: 'errorDisplay', align: 'tlabs', x: 0, y: 0
    }, {
      name: 'infoDisplay'
    }, {
      name: 'tooltip', align: 'blabs', x: 0, y: 56
    }, {
      name: 'thumbnail'
    }, {
      name: 'controlBar', align: 'blabs', x: 0, y: 0,
      children: [{ name: 'progress', align: 'blabs', x: 0, y: 44 }, { name: 'playButton', align: 'tl', x: 15, y: 12 }, { name: 'timeDisplay', align: 'tl', x: 10, y: 7 }, { name: 'fullScreenButton', align: 'tr', x: 10, y: 12 }, { name: 'subtitle', align: 'tr', x: 15, y: 12 }, { name: 'setting', align: 'tr', x: 15, y: 12 }, { name: 'volume', align: 'tr', x: 5, y: 10 }]
    }];
  }

  // 绑定显隐事件

  var _useState2 = useState(false),
      showBar = _useState2[0],
      setShowBar = _useState2[1];

  function attachBar(player) {
    if (!player) return;
    player.on('hideBar', function () {
      setShowBar(false);
    });
    player.on('showBar', function () {
      setShowBar(true);
    });
  }

  useEffect(function () {
    window._seedsui_videofull_player_ = window._seedsui_videofull_player_ ? window._seedsui_videofull_player_ + 1 : 1;
    idSdkPlayer = '_seedsui_videofull_player_' + window._seedsui_videofull_player_;
    setIdSdkPlayer(idSdkPlayer);
    if (instance.current) return;
    initInstance();

    return function () {
      if (instance.current) instance.current.dispose();
    };
  }, []); // eslint-disable-line

  useEffect(function () {
    if (instance.current && pause === true) {
      instance.current.pause();
    }
  }, [pause]);

  var DOM = React.createElement(
    'div',
    _extends({ className: 'videofull-page' + (others.className ? ' ' + others.className : '') }, others, { ref: refEl }),
    React.createElement('div', { 'x5-video-player-type': 'h5', className: 'prism-player', 'webkit-playsinline': 'true', playsInline: true, id: idSdkPlayer, style: { width: '100%', height: '100%' } }),
    showBar && bar ? bar : null,
    children
  );
  if (portal) {
    return createPortal(DOM, portal);
  }
  return DOM;
});

export default VideoFull;