import React, { useMemo, useState, useCallback, useEffect, useContext, useRef } from 'react';
import { message } from 'antd';
import VideoTitle from '../components/Title';
import NoVideoTitle from '../components/NoVideoTitle';
import { formatHistoryList, getTimeRang } from '../utils';
import { convertToMp3 } from './utils'
import { inject, observer } from 'mobx-react';
import { useLatest, useDeepCompareEffect, useUpdateEffect } from 'ahooks'
import IconFont from '../ocean-player/iconfont';
import IFont from '../../../themeComponents/IconFont';
import TimePick from '../components/TimePick';
import withNoActivityTimeout, { NoActivityTimeoutContext } from '../components/withNoActivityTimeout';
import ModalComponent from '../../../themeComponents/Modal';
import { LeftExtBar, LeftExtMidBar, RightExtBar } from '../components/Bar';
import NetworkSpeed from '../components/NetworkSpeed';
import CameraControl from '../components/CameraControl';
import FunctionWindow from '../components/FunctionWindow';
import _ from 'lodash';
import { BaseStore, Shared, LMConfig } from '@zenview/micro-basic-library';
import { SocketEmitter, cache, fullScreenHelper, imageMethods } from '@zenview/micro-utils';
import collection from '../collection';
import Service from '../service';
import { Service as baseService } from '@zenview/micro-basic-library';
import PictureView from '../../CaptureImgView';
import Player, { HistoryPlayer } from '../ocean-player';
import AuthComponent from '../../AuthComponent';
import '../style/base.less';
// import 'ocean-player/es/player.css';
import { queryThemeConfig, getVideoHistoryTimes, setVideoHistoryTimes } from './utils';
import WaterMakeDom from '../../WaterMakeDom';
import Recorder from 'js-audio-recorder';
import { useMemoizedFn } from 'ahooks';
const dMenus = {
  captrueSearch: true,
  download: true,
  preset: true,
  hasActive: true,
};
var pc
var mediaDevices
function PlayerComponent({ file, historyList, isLive, startTime, endTime, defaultTime, isLoop, className, cid, title, isFrontEnd, seekPercent, hasLiveBar = true, hasHistory = true, hasFront = true, type, screenNum, menus = {}, playMsgEvent = {}, onIndClick, app, ...props }) {
  const { onClose, switchHistoryVideo, switchLiveVideo, downloadVideo, onFrontEndSeek, openPresetPanel, addPreset, cacheTime, noKeyEvent } = props;
  const [visible, setVisible] = useState(false);
  const [download, setDownload] = useState(false);
  const [timePickType, setTimePickType] = useState('history');
  const [playObj, setPlayObj] = useState(null);
  const [currentTabId, setCurrentTabId] = useState(null);
  const [videoSize, setVideoSize] = useState('contain');
  const [times, setTimes] = useState(() => getTimeRang(startTime, endTime), [startTime, endTime]);
  const [rectModal, setRectModal] = useState({ visible: false });
  const [deviceInfo, setDeviceInfo] = useState({});
  const [deviceSource, setDeviceSource] = useState('');
  const [speed, setSpeed] = useState(1);
  const [uuid, setUuid] = useState('');
  const [playerCutState, setPlayerCutState] = useState(false);//播放断流状态
  const [voiceAbility, setVoiceAbility] = useState(false);
  const [newPtzControl, setNewPtzControl] = useState(false);
  const [streamStatus, setStreamStatus] = useState('');
  const [ptzVisible, setPtzVisible] = useState(false);
  const [volume, setVolume] = useState(0);
  const [volumeShow, setVolumeShow] = useState(false);
  const [talkUrl, setTalkUrl] = useState('')
  const [imgUrl, setImgUrl] = useState('')//截图预览图
  const [videoKey, setVideoKey] = useState(isLive ? file : `${cid}-${startTime}-${endTime}`)
  const playBox = useRef();
  const inputRefs = useRef();
  const domRef = useRef(null);
  let recorder = new Recorder();

  const mouseEventRef = useRef({
    TimeOut: null,
    isPlay: false,
  });

  const volumeRef = useRef({
    TimeOut: null,
  });
  const keydownType = useRef({
    TimeOut: null,//判断是快进还是前进/后退的定时器
    keyDownFlag: false,//是否按下状态
    keepFlag: false//是否持续按下的状态
  })

  const [fragmentList, setFragmentList] = useState(null);
  const [isFullscreen, setFullscreen] = useState(false);
  const [isTalk, setIsTalk] = useState(false)

  // eslint-disable-next-line react-hooks/exhaustive-deps
  useMemo(() => (historyList ? setFragmentList(formatHistoryList(historyList, startTime, endTime, isFrontEnd)) : undefined), [historyList]);
  // const videoKey = useMemo(() => (isLive ? file : `${cid}-${startTime}-${endTime}`), [cid, endTime, file, isLive, startTime,]);

  useUpdateEffect(() => {
    setVideoKey(isLive ? file : `${cid}-${startTime}-${endTime}`)
    if(!file){
      setPlayerCutState(false)
    }
  }, [cid, endTime, file, isLive, startTime])


  // 实时视频使用 player 前端和录像使用 HistoryPlayer
  const PlayView = useMemo(() => (isLive ? Player : HistoryPlayer), [isLive]);

  //设置title功能默认展示项
  const titleMenu = useMemo(() => Object.assign(dMenus, menus), [menus]);
  // 获取缓存时间
  useEffect(() => {
    const fetch = async () => {

      try {
        const times = await getVideoHistoryTimes()
        setTimes(times)
      } catch (error) {

      }
    }
    if (cacheTime) {
      fetch()
    }
  }, [cacheTime])

  useEffect(() => {
    if (startTime && endTime) {
      setTimes(getTimeRang(startTime, endTime))
    }

  }, [startTime, endTime])


  // 获取系统配置
  useEffect(() => {
    Promise.all([queryThemeConfig('server')]).then((res) => {
      const [themeConfig] = res;
      setNewPtzControl(themeConfig.player.newPtzControl);
    });
  }, []);
  // cig 变化时，更新时间
  useEffect(() => {

    if (cid) {
      SocketEmitter.emit('updateLastWatchTime', cid);
    }
  }, [cid]);
  // 根据cid获取设备信息--是否有云台控制权限
  useEffect(() => {
    if (!cid && !isLive) {
      return;
    }
    setSpeed(1);
    const item = BaseStore.device.getDeviceByCId(cid);
    if (!item) {
      return;
    }

    Service.queryDeviceInfo(item.cid).then((result) => {
      const info = result.data || {};
      let deviceSource = '';
      try {
        // const voiceCids = LMConfig?.BSConfig?.player?.voiceCids ||["562888999","562889000","560090462","560090457","560090451","560090429","560090433","562889204","562889205","562889206","562889207"]
        const { type, platform } = info.extJson.cameraInfo;
        const { ability } = info.extJson.extMap || {};
        const { ptz_control, support_voice } = ability
        setVoiceAbility(support_voice)
        info.isPtzControl = (type === 'gb' && +platform === 1) || ptz_control;
        deviceSource = info.accessType.toLowerCase();
      } catch { }
      setDeviceInfo(() => info);
      setDeviceSource(deviceSource);
    });
  }, [cid, isLive]);

  const changeTimes = (value) => {
    setTimes(value)
    const [startTime, endTime] = value;
    if (startTime && endTime) {
      setVideoHistoryTimes([startTime.valueOf(), endTime.valueOf()])
    }
  }
  // 日期面板关闭
  const closeVisible = useCallback(() => {
    // playObj && playObj.cancelFullScreen();
    setVisible(false);
  }, [playObj]);

  // 日期选择面板--确定按钮【云录像】【前端录像】【云录像下载】【前端录像下载】
  const timeOk = () => {
    const [start, end] = times;
    if (!start || !end) {
      return;
    }
    // 暂时屏蔽三天范围
    // const judgeStart = moment().subtract(3, 'days').isBefore(moment(start)) && moment(start).isBefore(moment())
    // const judgeEnd = moment().subtract(3, 'days').isBefore(moment(end)) && moment(end).isBefore(moment())
    // if (!(judgeStart && judgeEnd)) return message.error('只能选近三天时间范围')


    // playObj && playObj.cancelFullScreen();
    const options = { startTime: start.unix(), endTime: end.unix(), cid };

    if (timePickType === 'history') {
      // 切换历史录像
      switchHistoryVideo && switchHistoryVideo(options);
    } else if (timePickType === 'frontEnd') {
      // 切换云录像
      options.isFrontEnd = true;
      switchHistoryVideo && switchHistoryVideo(options);
    } else if (timePickType === 'cloudDownload') {
      // 云录像下载
      options.videoType = 2;
      downloadVideo && downloadVideo(options);
    } else if (timePickType === 'frontDownload') {
      // 前端录像下载
      options.videoType = 1;
      downloadVideo && downloadVideo(options);
    }
    setVisible(false);
  };

  // 全屏触发-样式变化--画中画
  const isVideoFill = useMemo(() => videoSize === 'fill', [videoSize]);

  // 下载
  const openDownloadChoise = useCallback((e) => {
    setDownload(true)
    setVisible(true);
    setTimePickType(e);
  }, []);

  //工具栏- 抓拍
  const snapshot = (e) => {
    let imgUrl = playObj.snapshot();
    playObj && playObj.cancelFullScreen();
    if (imgUrl.length < 10) {
      return message.info('未截取到图片');
    }

    const deviceInfo = BaseStore.device.getDeviceByCId(cid);
    collection
      .addPictureFavorite({
        deviceId: deviceInfo.id || cid,
        deviceName: deviceInfo.deviceName,
        captureTime: Date.now(),
        scenceImageUrl: imgUrl,
        pictureType: '1',
        source: 2,
      })
      .then((res) => {
        setImgUrl(imgUrl)
        message.success('截图成功，请前往我的收藏-视频截图页面查看');
        addAnimation()
      });
  };

  //工具栏- 框选搜图按钮
  const onRectClick = useCallback(async () => {
    if (!playObj) return message.info('视频元素获取失败');
    playObj.cancelFullScreen();
    const imgUrl = playObj.snapshot();
    console.log(imgUrl, "111")
    if (imgUrl.length < 10) {
      return message.info('未截取到图片');
    }
    if (!isLive) {
      playObj.pause();
    }
    let file = imageMethods.base64ToBlob(imgUrl)
    const formData = new FormData();
    formData.append('file', file, 'file.png');
    let urlRes = await Service.faceUploadImg(formData)
    let res = await Service.getAllTargetFeature({ url: urlRes.data?.url })
    const { data } = res || {}
    const { nonvehicles, persons, vehicles } = data

    let rects = []

    const setItem = (v, type) => {
      const { left, top, width, height } = v.rect || {}
      let rect = [left, top, width, height]
      let value = rect.join(',')
      let item = {
        type,
        feature: v.feature,
        value,
        rect,
        needExpand: true
      }
      return item
    }

    nonvehicles?.forEach((v) => {
      let item = setItem(v, 'nonVehicle')
      rects.push(item)
    })
    vehicles?.forEach((v) => {
      let item = setItem(v, 'vehicle')
      rects.push(item)
    })
    persons?.forEach((v) => {
      const { face, body } = v
      if (face) {
        let item = setItem(face, 'face')
        rects.push(item)
      }
      if (body) {
        let item = setItem(body, 'body')
        rects.push(item)
      }
    })
    setRectModal({ visible: true, imgUrl, cid, rects });
  }, [playObj, cid, isLive]);

  // 工具栏- 取消框选弹窗
  const onCancelRect = () => {
    if (playObj && !isLive) {
      playObj.play();
    }
    setRectModal({ visible: false });
  };

  // 工具栏- 跳转框选搜图弹窗
  const frameSelectJumpPage = (params) => {
    onCancelRect();
    const { history } = props;
    if (!history) return console.log('-----History 对象获取失败-----');
    const { defaultUrl, frameUrl, searchData = {}, defaultRect: defaultItem, rects } = params;
    const pageInfo = Shared.resourcePageInfo[params.moduleName];
    const fnName = pageInfo.fnName;
    const { startTime, endTime, imgId, id } = searchData;
    Shared[fnName]({ history, id, imgId, frameUrl, defaultUrl, startTime, endTime, rects, defaultItem });
  };

  //左下角按钮--切换到【实时视频】
  const switchLiveVideoAction = () => {
    if (isLive || isLoop) {
      return;
    }
    switchLiveVideo && switchLiveVideo({ cid });
  };

  // 左下角按钮--切换到【云录像】
  const openHistoryChoise = useCallback(() => {
    if (!isLoop) {
      setDownload(false)
      setVisible(true);
      setTimePickType('history');
    }
  }, [isLoop, playObj]);

  // 左下角按钮--切换到【前端录像】
  const openFrontChoise = useCallback(() => {
    if (!isLoop) {
      setDownload(false)
      setVisible(true);
      setTimePickType('frontEnd');
    }
  }, [isLoop, playObj]);

  // 【前端录像】-重新请求时间段范围
  const seekFrontRangeData = async (currentTime, callback) => {
    // 根据时间范围，查询前端录像
    // 更新 historyList 内容
    const deviceInfo = BaseStore.device.getDeviceByCId(cid);
    deviceInfo.isFrontEnd = isFrontEnd;

    const targetList = await Shared.getVideoRecord({ deviceInfo, startTime: currentTime, endTime });

    if (!targetList || !targetList.length) {
      message.warn('当前时间查询录像失败！');
      // 执行回调进行变更录像片段索引
      callback && callback('error');
      return;
    }

    const mergeList = mergeRangData(historyList, targetList);
    const fragmentList = formatHistoryList(mergeList, startTime, endTime, isFrontEnd);
    setFragmentList(fragmentList);

    // 执行回调进行变更录像片段索引
    callback && callback();
  };

  /**
   * 组合新的数据集合--前端录像
   * @param {*} hList
   * @param {*} nList
   * @returns
   */
  const mergeRangData = (hList, nList) => {
    const cordonDate = nList[0].beginTime;
    let partList = JSON.parse(JSON.stringify(hList)).filter((element) => {
      if (element.beginTime < cordonDate) return element;
    });
    if (partList[partList.length - 1]) {
      partList[partList.length - 1].endTime = cordonDate;
    }

    return [...partList, ...nList];
  };

  //获取预置位截图
  const getImageUrl = async () => {
    playObj && playObj.cancelFullScreen();
    if (!playObj) return message.info('尚未开始播放');
    let imgUrl = playObj.snapshot();
    const oldFile = collection.base64ToBlob(imgUrl);
    const formData = new FormData();
    formData.append('file', oldFile);
    Service.uploadImg(formData).then((res) => {
      addPreset(res.data.url);
    });
  };

  // ---- 播放窗体点击事件-地图模式下预置位转盘聚焦
  const readers = useCallback(() => inputRefs.current.focus(), []);
  const onfullscreenchange = () => {
    setFullscreen(fullScreenHelper.isFullscreen());
  };
  //视频播放区域单机双击事件
  const onPlayerClick = useCallback(
    (e) => {
      onIndClick && onIndClick()
      e.preventDefault();
      e.stopPropagation();
      clearTimeout(mouseEventRef.current.TimeOut); // 清除第一个单击事件
      mouseEventRef.current.TimeOut = setTimeout(() => {
        if (!isLive && playObj && !isLoop) {
          if (mouseEventRef.current.isPlay) {
            playObj.pause();
          } else {
            playObj.play();
          }
        }
      }, 200);
    },
    [playObj, isLive, isLoop]
  );
  const onDouble = useCallback(
    (e) => {
      e.preventDefault();
      e.stopPropagation();
      clearTimeout(mouseEventRef.current.TimeOut); // 清除第二个单击事件
      if (playObj) {
        if (fullScreenHelper.isFullscreen()) {
          playObj.cancelFullScreen();
        } else {
          playObj.requestFullScreen();
        }
      }
    },
    [playObj]
  );
  // 设备信息变化或者播放状态变化时，视频播放，更新设备状态--仅限于实时播放
  useEffect(() => {
    console.log('开流状态==>' + streamStatus);
    if (_.isEmpty(deviceInfo) || !playObj || !isLive || !streamStatus || deviceInfo.deviceStatus !== '0') {
      return;
    }
    console.log('更新设备状态成功！');
    const updateStatus = () => {
      Service.updateDeviceStatus(deviceInfo.id, true);
      BaseStore.device.updateSingleDevice({
        deviceId: deviceInfo.id,
        deviceStatus: '1',
        type: 2,
      });
    };
    playObj.addEventListener && playObj.addEventListener('play', updateStatus);
    return () => { };
  }, [deviceInfo, playObj, streamStatus]);

  // 实时视频-开流状态变化触发
  const onStreamMounted = (obj) => {
    setStreamStatus(obj.streamState);
  };

  // 会话时间检测
  useEffect(() => {
    if (!playObj) {
      return;
    }
    const onPlayer = () => {
      mouseEventRef.current.isPlay = true;
    };
    const onPause = () => {
      mouseEventRef.current.isPlay = false;
    };
    const onProgress = () => {
      cache.setCache('CHECK_TIME', Date.now(), 'session');
    };


    if (playObj.addEventListener) {
      playObj.addEventListener('play', onPlayer);
      playObj.addEventListener('pause', onPause);
      playObj.addEventListener('progress', onProgress);
    }

  }, [playObj]);

  useEffect(() => {
    if (noKeyEvent || !playObj) { return }
    SocketEmitter.on('keydown', keydownHandler);
    SocketEmitter.on('keyup', keyupHandler);
    return () => {
      SocketEmitter.off('keydown', keydownHandler);
      SocketEmitter.off('keyup', keyupHandler);
    }
  }, [noKeyEvent, playObj])

  const keydownHandler = e => {
    if (currentTabId !== cache.getCache('currentTabKey', 'session')) { return }
    const keyCode = e.keyCode
    if (![37, 38, 39, 40].includes(keyCode)) {
      return
    }
    e.stopPropagation()
    if (keydownType.current.keyDownFlag) {
      return
    }
    keydownType.current.keyDownFlag = true
    keydownType.current.TimeOut = setTimeout(() => {
      if (e.keyCode === 39) {
        keydownType.current.keepFlag = true
        setSpeed(8)
      }
    }, 500)
    e.stopPropagation()
  }

  const keyupHandler = e => {
    if (currentTabId !== cache.getCache('currentTabKey', 'session')) { return }
    const keyCode = e.keyCode

    if (![32, 37, 38, 39, 40].includes(keyCode)) {
      return
    }
    if (keyCode === 32) {
      if (mouseEventRef.current.isPlay) {
        playObj.pause();
      } else {
        playObj.play();
      }
      return
    }
    const nowVolume = playObj.__player.volume
    if ([38, 40].includes(keyCode)) {
      let newVolume = (nowVolume * 10 + (keyCode === 38 ? 1 : -1)) / 10
      newVolume = newVolume >= 1 ? 1 : newVolume
      newVolume = newVolume <= 0 ? 0 : newVolume
      setVolume(newVolume)
      playObj.setVolume(newVolume)
      setVolumeShow(true)
      clearTimeout(volumeRef.current.TimeOut)
      volumeRef.current.TimeOut = null
      volumeRef.current.TimeOut = setTimeout(() => {
        setVolumeShow(false)
      }, 1000)
      playObj.unmute()
      // setSpeed(speed => {
      //   let newSpeed = speed * 2
      //   if (newSpeed > 8) {
      //     newSpeed = 8
      //   }
      //   return newSpeed
      // })
    }
    // if (keyCode === 40) {
    //   let newVolume = (nowVolume * 10 - 1) / 10
    //   newVolume = newVolume <= 0 ? 0 : newVolume
    //   playObj.setVolume(newVolume)
    //   playObj.setVolume(newVolume)
    //   playObj.unmute()

    //   // setSpeed(speed => {
    //   //   let newSpeed = speed / 2
    //   //   if (newSpeed < 0.125) {
    //   //     newSpeed = 0.125
    //   //   }
    //   //   return newSpeed
    //   // })
    // }
    if (keydownType.current.keyDownFlag) {
      if (keydownType.current.keepFlag) {
        setSpeed(1)
      } else {
        if (keyCode === 39) {
          playObj.fastForward(5);
        }
        if (keyCode === 37) {
          playObj.backWind(5)
        }
      }
      keydownType.current.keepFlag = false
      keydownType.current.keyDownFlag = false
      clearTimeout(keydownType.current.TimeOut)
      keydownType.current.TimeOut = null
    }
  }
  // 页面销毁
  useEffect(() => {
    setCurrentTabId(cache.getCache('currentTabKey', 'session'))
    document.addEventListener('webkitfullscreenchange', onfullscreenchange, false);

    return () => {
      // 置空播放对象
      setPlayObj(null);
      document.removeEventListener('webkitfullscreenchange', onfullscreenchange, false);
    };
  }, []);

  const closeWindow = useMemoizedFn(() => {
    ptzVisible && setPtzVisible(false)
    setPlayObj(null)
    closeTalk()
    setSpeed(1)
    onClose()
  })

  const recordingMouseDown = async () => {
    const config = {
      sampleBits: 16,
      sampleRate: 16000,
      numChannels: 1,
    }

    if (!recorder) {
      recorder = new Recorder(config);
    } else {
      recorder.stop();
      recorder.destroy()
    }

    recorder.start().then(() => {
      // setTapeStartTime(new Date()*1);
      console.log('开始录音');
    }, (error) => {
      console.log(`异常了,${error.name}:${error.message}`);
    });
  }
  const getImageBase64 = (blob) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onload = () => {
        const base64 = reader.result;
        resolve(base64);
      }
      reader.onerror = error => reject(error);
    });
  }

  const recordingMouseUp = async () => {
    try {
      recorder && recorder.stop();

      if (recorder) {
        const mp3Blob = convertToMp3(recorder.getWAV(), recorder);
        let base64 = await getImageBase64(mp3Blob)
        onBroadcast(base64)
      }
      recorder && recorder.destroy()
    } catch (error) {
      console.log(error);
    }
    recorder && recorder.destroy()
  }
  const onBroadcast = async (base64) => {

    try {
      let res = await Service.voiceInfo(cid)
      const { url } = res?.data || {}
      let broadcastRes = await baseService.$http({
        headers: {
          Authorization: cache.getCache('token', 'session'),
        },
        url,
        method: 'post',
        data: {
          format: 'mp3',
          data: base64.replace('data:audio/mp3;base64,', '')
        }
      })
      if (broadcastRes.code === 200) {
        message.success('语音播报成功！')
      } else {
        message.warn('语音播报失败，请重试！')
      }
    } catch (error) {
      console.log(error);
      message.warn('语音播报失败，请重试！')

    }
  }

  const onIntercom = async () => {
    let palyTalkUrl = talkUrl
    if (!palyTalkUrl) {
      try {
        let res = await baseService.$http({
          headers: {
            Authorization: cache.getCache('token', 'session'),
          },
          url: `/api/device/v1/getVoiceTalk/${cid}`,
          method: 'get',
        })
        if (res.code === 0) {
          palyTalkUrl = res.data?.url
          setTalkUrl(res.data?.url)
        }
      } catch (error) {

      }
    }

    if (palyTalkUrl) {
      pc = new RTCPeerConnection();

      window.navigator.mediaDevices.getUserMedia({ audio: true })
        .then(async res => {
          mediaDevices = res
          const mediaStream = res
          pc.oniceconnectionstatechange = () => {
            console.log('oniceconnectionstatechange', pc.iceConnectionState);
          };
          pc.onicecandidate = (e) => {
            console.log('onicecandidate', e.candidate);
          };
          mediaStream.getTracks().forEach((t) => {
            pc.addTrack(t, mediaStream);
          });

          const offer = await pc.createOffer();
          await pc.setLocalDescription(offer);
          const result = await fetch(palyTalkUrl, { method: 'POST', body: offer.sdp });
          if (result.status != 200) {
            message.warning('该设备不支持语音对讲！')
            mediaDevices.getAudioTracks()[0].stop();
            mediaDevices = null
            pc.close();
            pc = null
            return
          }
          // setTalkBackStatus(talkbackStatus == 'stop' ? 'play' : 'stop')
          const remoteSdp = await result.text();
          await pc.setRemoteDescription(new RTCSessionDescription({ type: 'answer', sdp: remoteSdp }));
        })
        .catch(_ => {
          console.log(_);
          message.warning('不支持语音录制，请检查录音功能是否开启！')
        })
    } else {
      message.warning('该设备不支持语音对讲！')
    }
  }

  const closeTalk = () => {
    setIsTalk(false)
    mediaDevices && mediaDevices?.getAudioTracks()[0].stop();
    mediaDevices = null
    pc && pc.close();
    pc = null
  }


  const hasWatermark = LMConfig?.BSConfig?.player?.hasWatermark

  const volumeIcon = useMemo(() => (volume === 0 ? 'lm-player-volume-close' : volume === 1 ? 'lm-player-volume-max' : 'lm-player-volume-normal-fuben'), [volume])

  const animationNodeRef = useRef(null); // 创建一个ref来引用动画节点
  const timerRef = useRef(null); // 创建一个ref来引用定时器

  const addAnimation = () => {
    console.log(animationNodeRef, "animationNodeRef")
    if (animationNodeRef.current) {
      const element = animationNodeRef.current; // 获取DOM元素
      // 计算元素到窗口上方的距离
      animationNodeRef.current.style = `
      display: block;
      position:fixed;
      width:${playBox.current.offsetWidth}px;
      height:${playBox.current.offsetHeight}px;
      left:${playBox.current.offsetLeft}px;
      top:${playBox.current.offsetTop}px;
      `;  //截图样式
      // 计算元素到窗口右边的距离
      const right = window.innerWidth - (element.offsetLeft + element.offsetWidth) - window.scrollX;
      animationNodeRef.current.style.setProperty('--distance-x', `${right + (element.offsetWidth / 2)}px`);
      animationNodeRef.current.style.setProperty('--distance-y', `-${playBox.current.offsetTop + (element.offsetHeight / 2)}px`);
    }

    // 设置定时器，动画完成后移除节点
    if (!timerRef.current) {
      timerRef.current = setTimeout(() => {
        if (animationNodeRef.current.parentNode) {
          animationNodeRef.current.style = `display: none;position:static`;
          timerRef.current = null;
        }
      }, 1500); // 动画持续时间
    }
  };

// 5分分钟倒计时提示弹窗覆盖
const MAX_INACTIVE_TIME =LMConfig?.BSConfig?.player?.timeOut5G || 5 *60 * 1000; // 5分钟，单位毫秒
const tRef = useRef(null);
  const resetTimer = useMemoizedFn(() => {
    if (tRef.current) {
      clearTimeout(tRef.current);
    }
    tRef.current = setTimeout(() => {
      if (!playerCutState) {
        playObj?.destroy()
        setPlayerCutState(true)
      }
    }, MAX_INACTIVE_TIME);
  });
  const mouseMoveCallback = () => {
    setPlayerCutState(false)
    setVideoKey(Math.random())
  }
  useEffect(() => {
    // 监听鼠标移动事件来重置计时器
    (!!playObj&& deviceInfo.networkType === 5)&&window.addEventListener('mousemove', resetTimer);
    // 组件卸载时清除计时器和事件监听
    return () => {
      if (tRef.current) {
        clearTimeout(tRef.current);
      }
      window.removeEventListener('mousemove', resetTimer);
    };
  }, [playObj]); // 添加依赖项以正确更新
 
  const LoadNoticeHandle = () => {
    if(deviceInfo.networkType === 5){
      resetTimer()
    }
  }
  return (
    <div ref={playBox} onClick={readers} className="playview-box"> 

      <input ref={inputRefs} style={{ width: '0px', height: '0px', position: 'absolute' }} />
      <PlayView
        autoPlay={true}
        isFrontEnd={isFrontEnd}
        isLive={isLive}
        file={file}
        cid={cid}
        type={type}
        className={`lm-c-player-component ${className} ${isVideoFill ? 'video-fill' : 'video-contain'} ${ptzVisible ? 'active playview-box-postion' : ''}`}
        onInitPlayer={(player) => {
          setPlayObj(player);
        }}
        historyList={fragmentList}
        defaultTime={defaultTime}
        key={videoKey}
        onVideoFn={(msg) => {
          setUuid(msg.uuid);
        }}
        speed={speed}
        seekFrontRangeData={seekFrontRangeData}
        loadNoticeHandle={LoadNoticeHandle}
        deviceInfo={{ ...deviceInfo, type }}
        errorReloadTimer={LMConfig?.BSConfig?.player?.reloadTimer}
        screenNum={screenNum}
        onStreamMounted={onStreamMounted}
        leftExtContents={
          titleMenu.hasActive && (
            <LeftExtBar isLive={isLive} isFrontEnd={isFrontEnd} hasLiveBar={hasLiveBar} deviceInfo={deviceInfo} hasHistoryBar={hasHistory} hasFrontEndBar={hasFront} switchLiveVideo={switchLiveVideoAction} openHistoryChoise={openHistoryChoise} frontAction={openFrontChoise} playBox={playBox} />
          )
        }
        leftMidExtContents={<LeftExtMidBar isTalk={isTalk} setIsTalk={setIsTalk} closeTalk={closeTalk} onIntercom={onIntercom} recordingMouseDown={recordingMouseDown} recordingMouseUp={recordingMouseUp} voiceAbility={voiceAbility} isLoop={isLoop} isLive={isLive} />}
        rightExtContents={
          <RightExtBar
            player={playObj}
            isLive={isLive}
            isVideoFill={isVideoFill}
            setVideoSize={setVideoSize}
            setSpeed={setSpeed}
            speed={speed}
            uuid={uuid}
            downloadAction={openDownloadChoise}
            onRectClick={onRectClick}
            snapshot={snapshot}
          />
        }
        errorExtContents={<NoVideoTitle isFile={true} title={title} onClose={closeWindow} />}
      >
        {hasWatermark && <WaterMakeDom imgType={3} />}
        {deviceInfo.isPtzControl && isLive && (
          <AuthComponent actionName="ptzControlAuth">
            {newPtzControl ? (
              <FunctionWindow inputRef={inputRefs} player={playObj} deviceInfo={deviceInfo} isFile={!!file} playBox={playBox} showPTZModule={(visible) => setPtzVisible(visible)} />
            ) : (
              <CameraControl inputRef={inputRefs} player={playObj} deviceInfo={deviceInfo} isFile={!!file} playBox={playBox} />
            )}
          </AuthComponent>
        )}
        <VideoTitle
          {...props}
          menus={titleMenu}
          title={title}
          isFile={file || (historyList && historyList.length)}
          onClose={closeWindow}
          player={playObj}
          downloadAction={openDownloadChoise}
          onRectClick={onRectClick}
          openPresetPanel={openPresetPanel}
          type={type}
          cid={cid}
          deviceInfo={deviceInfo}
          getImageUrl={getImageUrl}
          deviceSource={deviceSource}
        />
        <NetworkSpeed isLive={isLive} playObj={playObj} />
        <NoVideoTitle isFile={historyList && !historyList.length} title={title + '暂无历史录像'} onClose={closeWindow} />
        <div ref={domRef} style={{ zIndex: 200 }}></div>
        <TimePick
          visible={visible}
          onClose={closeVisible}
          onChange={changeTimes}
          download={download}
          onOk={timeOk}
          value={times}
          timePickType={timePickType}
          getContainer={() => {
            return isFullscreen ? domRef.current : document.body;
          }}
        />
        <ModalComponent
          className="collection-page-pic-detail-modal"
          visible={rectModal.visible}
          title={'框选搜图'}
          otherModalFooter={true}
          onCancel={onCancelRect}
          getContainer={() => {
            let dom = document.getElementsByClassName('loop-video-layout')[0] || document.getElementsByClassName('leaflet-wrapper-layout')[0] || document.body;
            return dom;
          }}
          footer={null}
          width={800}
          style={{ height: 544 }}
          destroyOnClose={true}
        >
          <PictureView isShowDefaultRect={false} imagePath={rectModal.imgUrl} showIntelligent={false} rects={rectModal.rects || []} data={{ cid }} disableDownload={true} frameSelectJumpPage={frameSelectJumpPage} height={'calc(100% - 48px)'} minHeight={300} />
        </ModalComponent>
        <div className="play-Box-msg" onDoubleClick={onDouble} onClick={onPlayerClick} {...playMsgEvent}>
          <div className={`${volumeShow ? 'volumeShow' : ''} bpx-player-volume-hint`}>
            <IconFont type={volumeIcon} />
            <span className="bpx-player-volume-hint-text">{volume * 100}%</span>
          </div>

        </div>
      </PlayView>
 
      <div className='bpx-player-animation' ref={animationNodeRef} >
        <img src={imgUrl} ></img>
      </div>
      {/*(isPromptVisible && playObj) && deviceInfo.networkType === 5 {(file&&deviceInfo.networkType===5)&& <NoActivityTimeout onTimeout={handleTimeout}  ref={maskPlayRef} />} */}
     { (playerCutState && playObj && file )  ? <div className='bpx-player-animation-mask'  >
      <p className='bpx-player-animation-mask-text'>
        检测到 5 分钟内未进行任何操作，为防止消耗摄像机流量，系统已自动断流
      </p>
      <p className='bpx-player-animation-mask-text' onClick={mouseMoveCallback}>
        <IFont type='icon-btn_video_play' /> <span>继续观看</span>
      </p>
    </div> : null}
    </div>
  );
}

PlayerComponent.defaultProps = {
  isLive: true,
  isLoop: false,
  className: '',
};
PlayerComponent.getVideoHistoryTimes = getVideoHistoryTimes
PlayerComponent.setVideoHistoryTimes = setVideoHistoryTimes
export default inject('app')(observer(PlayerComponent));
