"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _utils = _interopRequireDefault(require("../../utils"));

var _play = _interopRequireDefault(require("../../img/play.svg"));

var _pause = _interopRequireDefault(require("../../img/pause.svg"));

var _muted = _interopRequireDefault(require("../../img/muted.svg"));

var _notMuted = _interopRequireDefault(require("../../img/not-muted.svg"));

require("./index.css");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var preCls = "titaui-pc-video-box";
var VideoBox = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var videoSrc = props.videoSrc,
      containerWidth = props.containerWidth,
      hasHead = props.hasHead,
      headButton = props.headButton,
      title = props.title,
      extraButton = props.extraButton,
      videoPoster = props.videoPoster,
      _props$time = props.time,
      time = _props$time === void 0 ? "00:00" : _props$time;

  var _useState = (0, _react.useState)(true),
      _useState2 = _slicedToArray(_useState, 2),
      isPlay = _useState2[0],
      setIsPlay = _useState2[1];

  var _useState3 = (0, _react.useState)(true),
      _useState4 = _slicedToArray(_useState3, 2),
      isMuted = _useState4[0],
      setIsMuted = _useState4[1];

  var _useState5 = (0, _react.useState)(false),
      _useState6 = _slicedToArray(_useState5, 2),
      isMouseDown = _useState6[0],
      setIsMouseDown = _useState6[1];

  var _useState7 = (0, _react.useState)(false),
      _useState8 = _slicedToArray(_useState7, 2),
      showDot = _useState8[0],
      setShowDot = _useState8[1];

  var _useState9 = (0, _react.useState)("00:00"),
      _useState10 = _slicedToArray(_useState9, 2),
      totalTime = _useState10[0],
      setTotalTime = _useState10[1];

  var _useState11 = (0, _react.useState)("00:00"),
      _useState12 = _slicedToArray(_useState11, 2),
      currentTime = _useState12[0],
      setCurrentTime = _useState12[1];

  var _useState13 = (0, _react.useState)(false),
      _useState14 = _slicedToArray(_useState13, 2),
      isSmallVideo = _useState14[0],
      setIsSmallVideo = _useState14[1];

  var _useState15 = (0, _react.useState)("0px"),
      _useState16 = _slicedToArray(_useState15, 2),
      progressWidth = _useState16[0],
      setProgressWidth = _useState16[1];

  var _useState17 = (0, _react.useState)("0px"),
      _useState18 = _slicedToArray(_useState17, 2),
      volumeWidth = _useState18[0],
      setVolumeWidth = _useState18[1];

  var videoRef = (0, _react.useRef)(document.createElement("video"));
  var videoBoxRef = (0, _react.useRef)(document.createElement("div"));
  var volumeBoxRef = (0, _react.useRef)(document.createElement("div")); // *---播放/暂停---*

  var handlePlayVideo = function handlePlayVideo() {
    setIsPlay(!isPlay);

    if (isPlay) {
      videoRef.current.pause();
    } else {
      videoRef.current.play();
    }
  }; //* ---进度条---*
  // 鼠标移入进度条区域


  var handleMouseEnterProgress = function handleMouseEnterProgress() {
    setShowDot(true);
  }; // 鼠标移出进度条区域


  var handleMouseLeaveProgress = function handleMouseLeaveProgress() {
    setShowDot(false);
    setIsMouseDown(false);
  }; // 获得点击进度条任意位置 计算实时进度条的宽度


  var getCurrentProgressWidth = function getCurrentProgressWidth(e) {
    var videoContainerLeft = videoBoxRef.current.getBoundingClientRect().left;
    var currentWidth = e.clientX - videoContainerLeft;
    setProgressWidth("".concat(currentWidth, "px"));
    videoRef.current.currentTime = videoRef.current.duration * currentWidth / containerWidth;
  }; // 点击进度条


  var handleClickTotalProgress = function handleClickTotalProgress(e) {
    getCurrentProgressWidth(e);
  }; // 拖动进度条


  var handleMouseDownProgress = function handleMouseDownProgress() {
    setIsMouseDown(true);
  };

  var handleMouseMoveProgress = function handleMouseMoveProgress(e) {
    if (isMouseDown) {
      getCurrentProgressWidth(e);
    }
  };

  var handleMouseUpProgress = function handleMouseUpProgress() {
    setIsMouseDown(false);
  }; // *---音量---*
  // 静音/声音 切换


  var handleChangeVolumeMuted = function handleChangeVolumeMuted() {
    setIsMuted(!isMuted);
    videoRef.current.muted = !videoRef.current.muted;
  }; // 点击音量进度条 计算音量进度条宽度


  var getCurrentVolumeWidth = function getCurrentVolumeWidth(e) {
    var volumeBoxLeft = volumeBoxRef.current.getBoundingClientRect().left;
    var currentWidth = e.clientX - volumeBoxLeft;
    var VolumeTotalProgressWidth = 34;

    if (currentWidth <= 0) {
      setIsMuted(true);
      videoRef.current.muted = true;
    } else if (currentWidth >= VolumeTotalProgressWidth) {
      setVolumeWidth("34px");
      videoRef.current.volume = 1;
    } else {
      setVolumeWidth("".concat(currentWidth, "px"));
      videoRef.current.volume = currentWidth / volumeBoxRef.current.clientWidth;
    }
  }; // 点击音量进度条


  var handleMouseClickVolume = function handleMouseClickVolume(e) {
    getCurrentVolumeWidth(e);
  }; // *---提供父组件调用---*
  // 暂停视频并静音


  var handleCloseAndPauseVideo = function handleCloseAndPauseVideo() {
    videoRef.current.pause();
    videoRef.current.currentTime = 0;
    videoRef.current.muted = true;
    setIsPlay(false);
  };

  var handleGetCurrentTime = function handleGetCurrentTime() {
    return currentTime;
  };

  (0, _react.useImperativeHandle)(ref, function () {
    return {
      closeVideo: handleCloseAndPauseVideo,
      getCurrentTime: handleGetCurrentTime
    };
  }); // *---初始化---*
  // 初始获得总时间

  var getTotalTime = function getTotalTime() {
    if (videoRef.current.duration) {
      setTotalTime(videoRef.current.duration.toString());
      videoRef.current.currentTime = parseFloat(time);
    }
  }; // 获得实时播放时间


  var handleTimeUpdate = function handleTimeUpdate() {
    if (videoRef.current.currentTime) {
      setCurrentTime(videoRef.current.currentTime.toString());
      setProgressWidth("".concat(containerWidth * videoRef.current.currentTime / videoRef.current.duration, "px"));
    }
  }; // 初始获得音量宽度


  (0, _react.useEffect)(function () {
    var VolumeTotalProgressWidth = 34;
    setVolumeWidth("".concat(VolumeTotalProgressWidth * videoRef.current.volume, "px"));
  }, []); // 初始判断是否是小窗口

  (0, _react.useEffect)(function () {
    var FullVideoWidth = 840;

    if (containerWidth < FullVideoWidth) {
      setIsSmallVideo(true);
    }
  }, []); // 按空格键 暂停/播放视频

  var handleKeyDown = function handleKeyDown(e) {
    if (e.keyCode === 32) {
      if (videoRef.current.paused) {
        videoRef.current.play();
        setIsPlay(true);
      } else {
        videoRef.current.pause();
        setIsPlay(false);
      }
    }
  };

  (0, _react.useEffect)(function () {
    document.addEventListener("keydown", handleKeyDown);
    return function () {
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, []);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__box"),
    ref: videoBoxRef
  }, /*#__PURE__*/_react["default"].createElement("video", {
    ref: videoRef,
    src: videoSrc,
    loop: true,
    autoPlay: true,
    muted: true,
    poster: videoPoster,
    style: {
      width: "100%",
      height: "100%"
    },
    onClick: handlePlayVideo,
    onLoadedMetadata: getTotalTime,
    onTimeUpdate: handleTimeUpdate
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(preCls, "__mouseMove"), _defineProperty({}, "".concat(preCls, "__mouseMove--small"), isSmallVideo)),
    onMouseMove: handleMouseMoveProgress,
    onMouseUp: handleMouseUpProgress,
    onMouseEnter: handleMouseEnterProgress,
    onMouseLeave: handleMouseLeaveProgress
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(preCls, "__progress"), _defineProperty({}, "".concat(preCls, "__progress--small"), isSmallVideo)),
    onClick: handleClickTotalProgress,
    onMouseDown: handleMouseDownProgress
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__progress-current"),
    style: {
      width: progressWidth
    }
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])(_defineProperty({}, "".concat(preCls, "__progress-current-dot"), showDot))
  })))), /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(preCls, "__mask1"), _defineProperty({}, "".concat(preCls, "__mask1--small"), isSmallVideo))
  }, hasHead && /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(preCls, "__title"))
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__mask1-title")
  }, title), headButton)), /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(preCls, "__mask2"), _defineProperty({}, "".concat(preCls, "__mask2--small"), isSmallVideo))
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(preCls, "__controls"), _defineProperty({}, "".concat(preCls, "__controls--small"), isSmallVideo))
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__controls-left")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__controls-button"),
    onClick: handlePlayVideo
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: isPlay ? _pause["default"] : _play["default"],
    className: "".concat(preCls, "__controls-play"),
    alt: "\u64AD\u653E/\u6682\u505C"
  })), /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(preCls, "__controls-time")
  }, (0, _utils["default"])(currentTime)), /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(preCls, "__controls-time")
  }, " / ".concat((0, _utils["default"])(totalTime)))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__controls-right")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])(_defineProperty({}, "".concat(preCls, "__controls-button"), isMuted), _defineProperty({}, "".concat(preCls, "__controls-volume"), !isMuted))
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])(_defineProperty({}, "".concat(preCls, "__controls-volume-progress--hidden"), isMuted), "".concat(preCls, "__controls-volume-progress")),
    onClick: handleMouseClickVolume,
    ref: volumeBoxRef
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])(_defineProperty({}, "".concat(preCls, "__controls-volume-current--hidden"), isMuted), "".concat(preCls, "__controls-volume-current")),
    style: {
      width: volumeWidth
    }
  })), /*#__PURE__*/_react["default"].createElement("div", {
    onClick: handleChangeVolumeMuted,
    className: "".concat(preCls, "__controls-play")
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: isMuted ? _muted["default"] : _notMuted["default"],
    alt: "\u97F3\u91CF"
  }))), extraButton))));
});
var _default = VideoBox;
exports["default"] = _default;