import React, { useState, useMemo, useEffect, useRef } from 'react';
import { Button, Popover, Tooltip, message } from 'antd';
import { useInterval } from 'ahooks'
import { LMConfig, Service, BaseStore } from '@zenview/micro-basic-library';
import { cache } from '@zenview/micro-utils';

import IconFont from '../../../themeComponents/IconFont';
import { Bar } from '../ocean-player';

const videoSpeed = [0.125, 0.25, 0.5, 1, 2, 4, 8];
export function LeftExtBar({ deviceInfo, isLive, isFrontEnd, frontAction, hasFrontEndBar, switchLiveVideo, openHistoryChoise, hasLiveBar, hasHistoryBar }) {
  const viewText = useMemo(() => (isLive ? '实时' : !isLive && !isFrontEnd ? '云录像' : !isLive && isFrontEnd ? '前端录像' : ''), [isFrontEnd, isLive]);
  const deviceData = BaseStore.device.getDeviceById(deviceInfo.id) || {};

  // 权限拦截，优先走系统配置
  const hasStorage = LMConfig?.BSConfig?.player?.patternAuth ? deviceData.hasStorage : true;
  const hasFrontEnd = LMConfig?.BSConfig?.player?.patternAuth ? deviceData.hasFrontEnd : true;

  return (
    <Bar className={'play-mode-tooltip'}>
      <span class='play-mode-tooltip-active' onClick={switchLiveVideo}>{viewText}</span>
      <ul class="play-mode-tooltip-downmenu">
        {hasLiveBar && <li class='play-mode-tooltip-downmenu__item' onClick={switchLiveVideo}>实时</li>}
        {hasHistoryBar && hasStorage && <li class='play-mode-tooltip-downmenu__item' onClick={openHistoryChoise}>云录像</li>}
        {hasFrontEndBar && hasFrontEnd && <li class='play-mode-tooltip-downmenu__item' onClick={frontAction}>前端录像</li>}
      </ul>
    </Bar>
  );
}

export const Wave = () => {
  const arr = []
  let len = 40
  let animationLen = 4
  for (let i = 0; i < len; i++) {
    let interval = 200 / len
    let animationIndex = i % animationLen + 1
    let animationClass = `animation${animationIndex}`
    const width = Math.floor(3 * Math.random())


    arr.push({ width, left: interval * i, animationClass })
  }
  return <div className="wave-box">
    <div className="wave-middle-line">
    </div>
    {
      arr.map((v, k) => {
        const { width, left, animationClass } = v
        return <div key={k} style={{ width, left }} className={`wave-item ${animationClass}`}></div>
      })
    }
  </div>
}

const CountdownView = ({ stop }) => {
  const [count, setCount] = useState(0);

  const clear = useInterval(() => {
    setCount(count + 1);
  }, 1000);

  useEffect(() => {
    if (count > 60) {
      clear()
      stop()
    }
  }, [clear, count, stop])
  return <Bar className='count-down-view'>
    {count >= 60 ? 60 : count}s / 60s
  </Bar>
}


export function LeftExtMidBar({ isLoop, closeTalk, recordingMouseDown, recordingMouseUp, voiceAbility, isLive, onIntercom,isTalk, setIsTalk }) {
  const ref = useRef();
  const dargRef = useRef();
  const [startFlag, setStartFlag] = useState(false)

  const getParentElements = (node) => {
    let arr = []
    const getParentElement = (node) => {
      arr.push(node)
      if (node.parentElement) {
        getParentElement(node.parentElement)
      }
    }
    getParentElement(node)
    return arr
  }

  const onMouseDown = (e) => {
    const parentElements = getParentElements(e.target)
    let item = parentElements.find(v => v.draggable)
    if (item) {
      dargRef.current = item
      dargRef.current.draggable = false
    }
    setStartFlag(true)
    recordingMouseDown()
  }

  const onMouseUp = (e) => {
    if (dargRef.current) {
      dargRef.current.draggable = true
    }
    if (startFlag) {
      setStartFlag(false)
      recordingMouseUp()
    }
  }



  return isLoop ? <Bar key="loop" className="video-loop-active">正在轮巡视频</Bar>
    : isLive ? (
      <>
        {
          <Tooltip visible={isTalk} getPopupContainer={node =>node} overlayClassName='voice-intercom-tip' placement='top' title={<div className='voice-intercom-content'>
            <div className="voice-intercom-top">
              <IconFont type='icon-fast_nav_category' />
              正在对讲
            </div>
            <Button onClick={() => {
              closeTalk()
              setIsTalk(false)
            }} type='primary'>关闭</Button>
          </div>} trigger='click'>
            <Bar
              onClick={
                () => {
                  setIsTalk(true)
                  !isTalk&&onIntercom()
                }
              }
              className="sound-recording" title='点击开启对讲'><IconFont type='icon-hanhua' /></Bar>
          </Tooltip>
        }
        {voiceAbility ? <>
          <Bar className="sound-recording" barRef={ref} title='长按进行录音' onMouseDown={onMouseDown} onMouseUp={onMouseUp}><IconFont type='icon-luyin1' />
          </Bar>
          {startFlag ? <> <CountdownView stop={onMouseUp} /><Wave />  </> : null}
        </> : null}
      </>
    ) : null
}

export function RightExtBar({ player, speed, setSpeed, isLive, isFrontEnd, isVideoFill, setVideoSize, snapshot, uuid }) {
  // const [speed, setSpeed] = useState(1);
  const [visible, setVisible] = useState(false);
  const [resSpeed, setResSpeed] = useState({ name: '', status: '' });
  // 免责工具 -- 设备相应记录按钮展示状态
  const { showExemptionDeviceButton = false } = LMConfig.BSConfig.funcConfig || {};

  const [deviceStatus, setDeviceStatus] = useState({
    AckTime: '',
    DeviceCode: '',
    DeviceName: '',
    ErrorInfo: '',
    FirstFrameTime: '',
    InviteRespTime: '',
    InviteTime: '',
    LastFrameTime: '',
    NetworkDelay: '',
    Platform: '',
    PlatformCode: '',
    ResponseSpeed: '',
    VideoArriveTime: '',
  });

  const onVideoSizeChange = () => {
    setVideoSize(!isVideoFill ? 'fill' : 'contain');
  };

  // useEffect(() => {
  //   console.log(21321321312321);
  //   console.log(player?.__player?.playbackRate );
  //   setSpeed && setSpeed(player?.__player?.playbackRate || 1)
  // }, [])

  const onSpeedChange = (e, v) => {
    setSpeed(v);
    player.setPlaybackRate(v);
  };

  const onDeviceStatus = (e, v) => {
    setVisible(true);
    console.log('获取Request-Id======================', uuid);
    return Service.$http({
      headers: {
        Authorization: cache.getCache('token', 'session'),
      },
      url: `/exemption/raven/v1/diagnoses/requestids`,
      method: 'post',
      data: { request_ids: [uuid] },
    })
      .then((res) => {
        if (!res.data || !res.data.length) {
          message.warn('正在提取响应记录，请稍等...');
          return;
        }
        setDeviceStatus(res.data[0]);
        // 设置响应速度状态
        const timeSpeed = res.data[0].ResponseSpeed / 1000;
        if (timeSpeed <= 2) {
          setResSpeed({
            name: '良好',
            status: 'success',
          });
        } else if (timeSpeed > 2 && timeSpeed <= 5) {
          setResSpeed({
            name: '延迟',
            status: 'warning',
          });
        } else if (timeSpeed > 5) {
          setResSpeed({
            name: '故障',
            status: 'error',
          });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const handleVisibleChange = (visible) => {
    setVisible(visible);
  };

  return (
    <>
      {isLive && showExemptionDeviceButton && (
        <Popover
          placement="top"
          overlayClassName={'video-device-popover'}
          trigger="click"
          visible={visible}
          onVisibleChange={handleVisibleChange}
          content={
            <div className="device-popup">
              <div className="device-popup-header">
                <span className="fl title">设备响应记录</span>
                <a className="fr close" href title="关闭" onClick={(e) => setVisible(false)}>
                  X
                </a>
              </div>
              <div className="device-popup-content">
                <div className="device-popup-group">
                  <ul>
                    <li>下级平台：{deviceStatus.DeviceName}</li>
                    <li>国标编号：{deviceStatus.DeviceCode}</li>
                  </ul>
                </div>
                <div className="device-popup-group">
                  <div className="device-popup-title">
                    <span>信令交互</span> <span className="device-popup-title__td">详细信息参数</span>
                  </div>
                  <ul className="sub-item">
                    <li>
                      <span>开流请求</span>
                      <span> {deviceStatus.InviteTime}</span>
                    </li>
                    <li>
                      <span>开流响应</span> <span>{deviceStatus.InviteRespTime}</span>
                    </li>
                    <li>
                      <span>开流应答</span> <span>{deviceStatus.AckTime}</span>
                    </li>
                  </ul>
                </div>
                <div className="device-popup-group">
                  <div className="device-popup-title">获取关键帧</div>
                  {deviceStatus.LastFrameTime ? (
                    <ul className="sub-item">
                      <li>
                        <span>数据到来时间</span> <span>{deviceStatus.VideoArriveTime}</span>
                      </li>
                      <li>
                        <span>第一个关键帧</span> <span>{deviceStatus.FirstFrameTime}</span>
                      </li>
                      <li>
                        <span>最后一个关键帧</span> <span>{deviceStatus.LastFrameTime}</span>
                      </li>
                      <li>
                        <span>响应速度</span>
                        <span className="tc">{resSpeed.name}</span>
                        <span>{deviceStatus.ResponseSpeed}</span>
                        <span className={`dot dot-` + resSpeed.status}></span>
                      </li>
                    </ul>
                  ) : (
                    <ul className="sub-item">
                      <li>
                        <span>正在提取...</span>
                      </li>
                    </ul>
                  )}
                </div>
              </div>
            </div>
          }
        >
          <Bar className="controller-item snap-shot">
            <IconFont
              className="lm-player-iconfont"
              type={'icon-S_Plase_Disclaimer'}
              onClick={() => {
                onDeviceStatus();
              }}
              title={'设备响应记录'}
            />
          </Bar>
        </Popover>
      )}
      <Bar onClick={snapshot} className="controller-item snap-shot">
        <IconFont className="lm-player-iconfont" type={'icon-M_Bar_Camera1'} title={'截图'} />
      </Bar>
      <Bar onClick={onVideoSizeChange} className="controller-item fill">
        <IconFont className="lm-player-iconfont" type={!isVideoFill ? 'icon-S_View_ScreenSizeFull' : 'icon-S_View_ScreenSizeDefault'} title={!isVideoFill ? '画面填充' : '画面自适应'} />
      </Bar>

      {!isLive && !isFrontEnd && (
        <Bar className={'fl-menu'}>
          <span class='fl-menu-main'>{speed}x</span>
          <ul class="fl-menu-level">
            {
              videoSpeed.map((v) => (
                <li class="fl-menu-level-1" key={v} onClick={(e) => onSpeedChange(e, v)}>{v}x</li>
              ))
            }
          </ul>
        </Bar>
      )}
    </>
  );
}
