import { message, ConfigProvider, Progress } from 'antd';
import { useEffect, useState, useContext, useRef, useImperativeHandle } from 'react';
import TestVideo from '../index';
import classNames from 'classnames';
import Empty from '@wisdom-components/empty';
import empty_icon from '../assets/缺省页.png';
import { videoPlayback, newPlayback } from '../apis';
import './index.less';
import moment from 'moment';
import TimeSlider from './TimeSlider';

const RecVideo = (props, ref) => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('rec-video-view');

  const { VideoInfo, JessibucaObj, ProgressBar, EmptyIcon = '', } = props;
  const jessibuca = useRef(null);
  const [hoursRuler, setHoursRuler] = useState(VideoInfo.hoursRuler || 24);
  const [showId, setShowId] = useState(null); //视频ID
  const [peridos, setPeridos] = useState([]); //可播放视频时间段
  const [playTimestamp, setPlayTimestamp] = useState(null); //当前正在播放时间段
  const [minTimestamp, setMinTimestamp] = useState(null); //时间轴最小时间
  const [maxTimestamp, setMaxTimestamp] = useState(null); //时间轴最大时间
  const [loading, setLoading] = useState(true);
  const [percent, setPercent] = useState(0);
  const timeRef = useRef(null);

  useEffect(() => {
    changeReplayCfg();
  }, [props.VideoInfo]);

  useEffect(() => {
    let current = percent;
    if (loading)
      timeRef.current = setInterval(() => {
        current = current + 1;
        setPercent(current > 99 ? 99 : current);
      }, 20);

    return () => {
      if (timeRef.current) {
        clearInterval(timeRef.current);
        timeRef.current = null;
        setPercent(0);
      }
    };
  }, [loading]);

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

  useEffect(() => {
    const { endTime = moment().format('YYYY-MM-DD 23:59:59') } = VideoInfo;
    const edTimes = moment(endTime).format('YYYY-MM-DD HH:mm:ss');
    if (playTimestamp) {
      let momentObj = moment(playTimestamp);
      let formattedTime = momentObj.format('YYYY-MM-DD HH:mm:ss');
      const edDates = moment(edTimes).format('YYYY-MM-DD HH:mm:ss');
      const params = {
        id: VideoInfo.id,
        force: 1,
        startTime: formattedTime,
        endTime: edDates,
        'site-code':
          window?.globalConfig?.userInfo?.LocalSite || window?.globalConfig?.userInfo?.site || '',
      };
      rePaly(params);
    }
  }, [playTimestamp]);

  const changeReplayCfg = () => {
    const {
      beginTime = moment().format('YYYY-MM-DD 00:00:00'),
      endTime = moment().format('YYYY-MM-DD 23:59:59'),
    } = VideoInfo;
    const hoursPerRuler = calculateHours(beginTime, endTime) || 24;
    const stTimes = moment(beginTime).format('YYYY-MM-DD HH:mm:ss');
    const edTimes = moment(endTime).format('YYYY-MM-DD HH:mm:ss');
    const param = {
      id: VideoInfo.id,
      force: 1,
      startTime: stTimes,
      endTime: edTimes,
      'site-code':
        window?.globalConfig?.userInfo?.LocalSite || window?.globalConfig?.userInfo?.site || '',
    };
    setHoursRuler(hoursPerRuler);
    setMinTimestamp(moment(stTimes).valueOf());
    setMaxTimestamp(moment(edTimes).valueOf());
    getVideoPlBack(param);
  };

  const getVideoPlBack = (param) => {
    setLoading(true);
    videoPlayback(param)
      .then((res) => {
        setLoading(false);
        if (res.code === 200) {
          setPeridos(
            res.data.peridos.map((times, i) => {
              let beginTime = moment(times.StartTime.replaceAll('T', ' ').replaceAll('Z', ' '));
              let endTime = moment(times.EndTime.replaceAll('T', ' ').replaceAll('Z', ' '));
              return {
                ...times,
                idx: i,
                beginTime: beginTime.valueOf(),
                endTime: endTime.valueOf(),
                style: { background: '#637DEC' },
              };
            }),
          );
          setShowId(res.data.url);
        } else {
          message.warn(res.msg);
          setShowId(null);
        }
      })
      .catch((error) => {
        setLoading(false);
      });
  };

  const rePaly = (params) => {
    newPlayback(params).then((res) => {
      if (res.code === 200) {
        setShowId(res.data);
      } else {
        message.warn(res.msg);
      }
    });
  };

  const calculateHours = (time1, time2) => {
    const date1 = new Date(time1);
    const date2 = new Date(time2);
    const diff = Math.abs(date1.getTime() - date2.getTime());
    return Math.ceil(diff / (1000 * 60 * 60));
  };

  return (
    <div className={classNames(prefixCls)}>
      {loading ? (
        <>
          <div className={classNames(`${prefixCls}-load`)}>
            <Progress
              className={classNames(`${prefixCls}-progress`)}
              strokeColor={ProgressBar?.strokeColor || ''}
              format={(percent) => {
                return (
                  <span style={{ color: ProgressBar?.textColor || 'unset' }}>{percent + '%'}</span>
                );
              }}
              strokeWidth={14}
              percent={percent}
            />
            <span style={{ color: ProgressBar?.textColor || 'unset' }}>
              视频回放信息获取中,请稍后...
            </span>
          </div>
        </>
      ) : showId ? (
        <>
          <div className={classNames(`${prefixCls}-video`)}>
            {showId && (
              <TestVideo
                VideoInfo={{ ...VideoInfo, id: showId, type: 'rec' }}
                JessibucaObj={{ ...JessibucaObj }}
                key={showId}
                ref={jessibuca}
              />
            )}
          </div>
          {/* 时间轴 */}
          <div className={classNames(`${prefixCls}-time`)}>
            {peridos.length ? (
              <TimeSlider
                minTimestamp={minTimestamp}
                key={JSON.stringify(peridos) + (hoursRuler || 24)}
                maxTimestamp={maxTimestamp}
                hoursPerRuler={hoursRuler || 24}
                playTimestamp={playTimestamp ? playTimestamp : peridos[0].beginTime}
                playTimestampChange={(time, recordInfo, playOffset) => {
                  if (recordInfo && playOffset) {
                    setPlayTimestamp(time);
                  } else {
                    message.warn('当前时间节点没有视频可以播放哦!');
                  }
                }}
                timecell={peridos}
              />
            ) : null}
          </div>
        </>
      ) : (
        <div className={classNames(`${prefixCls}-empty`)}>
          <Empty
            image={EmptyIcon || empty_icon}
            theme={'dark'}
            description={'咦~暂时没有查询到视频回放信息呢~'}
          />
        </div>
      )}
    </div>
  );
};

export default React.forwardRef(RecVideo);