/*
 * @Author: 634665781 634665781@qq.com
 * @Date: 2023-04-11 13:40:18
 * @LastEditors: 634665781 634665781@qq.com
 * @LastEditTime: 2023-04-26 09:42:48
 * @FilePath: \wisdom-components\packages\base-components\TestVideo\src\index.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// eslint-disable-next-line no-unused-vars
import EZUIKit, { log } from 'ezuikit-js';

import axios from 'axios';
import React, {
  useState,
  useRef,
  useEffect,
  useImperativeHandle,
  forwardRef,
  useLayoutEffect,
} from 'react';
import App1 from './App';
import style from './index.less';

const Video = (props, ref) => {
  const _video = useRef(null);
  const Players = useRef(null);
  const refs = useRef(null);
  let PlayersA = '';
  const { VideoInfo, JessibucaObj, gateway } = props;
  let baseUrl = `ws://${window.location.host}/jessica`;
  let keyID = 'VIDEO-' + VideoInfo.id;
  let _VideoInfo = {
    title: '摄像头',
    url: `${baseUrl}/live/s8`,
    fullUrl: '',
    key: `摄像头`,
  };

  const getToken = async () => {
    axios
      .post(
        `https://open.ys7.com/api/lapp/token/get?appKey=${VideoInfo.username}&appSecret=${VideoInfo.password}`,
        {},
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
        },
      )
      .then(function (response) {
        let accessToken = response.data.data.accessToken;
        if (!VideoInfo.type || VideoInfo.type !== 'rec') return videoPlayLive(accessToken);
        videoPlayRec(accessToken);
      })

      .catch(function (error) {
        try {
          PlayersA && PlayersA.stop();
        } catch (e) {}
      });
  };

  const videoPlayLive = (accessToken) => {
    PlayersA = new EZUIKit.EZUIKitPlayer({
      id: keyID, // 视频容器ID
      accessToken: accessToken,
      url: `ezopen://open.ys7.com/${VideoInfo.address}/${VideoInfo.channel || 1}.hd.live`,
      template: 'pcLive',
      footer: ['talk', 'broadcast', 'hd', 'fullScreen'],
      width: VideoInfo.width || refs?.current?.offsetWidth || 952,
      height: VideoInfo.height || refs?.current?.offsetHeight || 500,
    });

    PlayersA.pause = PlayersA.stop;
    if (ref) ref.current = PlayersA;
  };

  const videoPlayRec = (accessToken) => {
    let url = `ezopen://open.ys7.com/${VideoInfo.address}/${VideoInfo.channel || 1}.hd.rec`;
    const begin = VideoInfo?.options?.begin || '';
    const end = VideoInfo?.options?.end || '';
    if (begin && end)
      url = `ezopen://open.ys7.com/${VideoInfo.address}/${
        VideoInfo.channel || 1
      }.hd.rec?begin=${begin}&end=${end}`;
    PlayersA = new EZUIKit.EZUIKitPlayer({
      id: keyID, // 视频容器ID
      accessToken: accessToken,
      url: url,
      template: 'pcRec',
      footer: ['talk', 'broadcast', 'hd', 'fullScreen'],
      width: VideoInfo.width || refs?.current?.offsetWidth || 952,
      height: VideoInfo.height || refs?.current?.offsetHeight || 500,
    });

    PlayersA.pause = PlayersA.stop;
    Players.current = PlayersA;
    if (ref) ref.current = PlayersA;
  };

  if (VideoInfo.protocol != '萤石EZOPEN') {
    useImperativeHandle(ref, () => {
      // changeVal 就是暴露给父组件的方法, newVal是父组件传递的参数
      return _video.current.jessibuca; // _video&& _video.current&&_video.current.jessibuca
    });
  }

  useEffect(() => {
    if (VideoInfo.protocol === '萤石EZOPEN' && VideoInfo.type === 'rec') {
      VideoInfo.options && Players && Players.current && Players.current.changePlayUrl(VideoInfo.options);
    }
  }, [VideoInfo.options]);

  useEffect(() => {
    if (VideoInfo.protocol != '萤石EZOPEN') {
    } else {
      getToken();
    }

    const resizeObserver = new ResizeObserver(() => {
      PlayersA &&
        PlayersA.reSize(refs?.current?.offsetWidth || 952, refs?.current?.offsetHeight || 500);
    });

    refs?.current && resizeObserver.observe(refs.current);

    return () => {
      try {
        try {
          // eslint-disable-next-line react-hooks/exhaustive-deps
          refs?.current && resizeObserver.unobserve(refs.current);
        } catch (e) {}
        try {
          PlayersA && PlayersA.destroy();
        } catch (e) {}
        // eslint-disable-next-line react-hooks/exhaustive-deps
        PlayersA = null;
        if (document.getElementById(`${keyID}`)) document.getElementById(`${keyID}`).innerHTML = '';
      } catch (e) {}
    };
  }, []);

  const CommonPath =
    VideoInfo.gateway || window?.globalConfig?.hasGateWay ? 'PandaCore/GateWay/Video/' : ''; // 配置了gateway或者pc端web配置中有gateway

  VideoInfo.url = VideoInfo.useFullUrl
    ? VideoInfo.fullUrl
    : (VideoInfo.pandavmsHost || 'ws://' + location.host + '/') +
      CommonPath +
      'jessica/' +
      VideoInfo.id;

  let operateBtns = {
    fullscreen: true,
    screenshot: true,
    play: true,
    record: true,
    audio: true,
  };

  _VideoInfo = { ..._VideoInfo, ...VideoInfo };

  if (JessibucaObj && JessibucaObj.operateBtns) {
    JessibucaObj.operateBtns = {
      ...operateBtns,
      ...JessibucaObj.operateBtns,
    };
  }

  return (
    <div ref={refs} className={style.app}>
      {VideoInfo.protocol == '萤石EZOPEN' ? (
        <div id={keyID} />
      ) : (
        <App1 {...{ VideoInfo: _VideoInfo, JessibucaObj: JessibucaObj }} ref={_video} />
      )}
    </div>
  );
};

const $Video = forwardRef(Video);

export default $Video;