/*
 * @Author: 634665781 634665781@qq.com
 * @Date: 2023-04-11 13:40:18
 * @LastEditors: yutian 249303761@qq.com
 * @LastEditTime: 2023-08-31 11:34:30
 * @FilePath: \wisdom-components\packages\base-components\VmsVideo\src\index.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @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';
// import * as Jessibuca from './JessibucaVideo/jessibuca';

//  proxy.js配置
// '/jessica/': {
//   target: wsServerPath,
//   changeOrigin: true,
//   ws: true,
//   pathRewrite: {
//     '/jessica': '/jessica',
//   },
// },

const Video = (props, ref) => {
  const _video = useRef(null);
  const Players = useRef(null);
  const refs = useRef(null);
  const [width, setWidth] = useState(0);
  const [height, setHeight] = useState(0);
  let PlayersA = '';
  const { VideoInfo, JessibucaObj, gateway } = props;
  let baseUrl = `ws://${window.location.host}/jessica`;
  let keyID = VideoInfo.id;
  let _VideoInfo = {
    title: '摄像头',
    // dataRate: 1,
    url: `${baseUrl}/live/s8`,
    fullUrl: '',
    key: `摄像头`,
  };
  useLayoutEffect(() => {
    console.log(refs.current.offsetWidth, refs.current.offsetHeight, '宽高');
    setWidth(refs.current.offsetWidth);
    setHeight(refs.current.offsetHeight);
  }, []);
  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;

        PlayersA = new EZUIKit.EZUIKitPlayer({
          id: keyID, // 视频容器ID
          accessToken: accessToken,
          url: `ezopen://open.ys7.com/${VideoInfo.address}/${VideoInfo.channel || 1}.hd.live`,
          templete: 'simple',
          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;
      })

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

  const resizeUpdate = (e) => {
    // 通过事件对象获取浏览器窗口的高度

    //  PlayersA?.stop?.()
    console.log(PlayersA, '视频对象11111111111111111111111111111111111111111111111');
    PlayersA.stop();
    getToken();
  };
  if (VideoInfo.protocol != '萤石EZOPEN') {
    useImperativeHandle(ref, () => {
      // changeVal 就是暴露给父组件的方法, newVal是父组件传递的参数
      return _video.current.jessibuca; // _video&& _video.current&&_video.current.jessibuca
    });
  }
  useEffect(() => {
    if (VideoInfo.protocol != '萤石EZOPEN') {
    } else {
      getToken();
    }
    // 页面刚加载完成后获取浏览器窗口的大小

    // 页面变化时获取浏览器窗口的大小
    window.addEventListener('resize', resizeUpdate);

    return () => {
      // 组件销毁时移除监听事件
      window.removeEventListener('resize', resizeUpdate);
    };
  }, [width, height]);

  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,
    };
  }

  useEffect(() => {
    return () => {
      try {
        PlayersA && PlayersA.stop();
      } catch (e) {}
    };
  }, []);

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

const $Video = forwardRef(Video);

export default $Video;
