import { message, ConfigProvider } 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 { 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 } = 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); //时间轴最大时间

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

  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 || '',
      };
      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 || '',
    };
    setHoursRuler(hoursPerRuler);
    setMinTimestamp(moment(stTimes).valueOf());
    setMaxTimestamp(moment(edTimes).valueOf());
    getVideoPlBack(param);
  };

  const getVideoPlBack = (param) => {
    videoPlayback(param).then((res) => {
      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);
      }
    });
  };

  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)}>
      {showId ? (
        <>
          <div className={classNames(`${prefixCls}-video`)}>
            {showId && (
              <TestVideo
                VideoInfo={{ ...VideoInfo, id: showId }}
                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 theme={'dark'} description={''} />
        </div>
      )}
    </div>
  );
};

export default React.forwardRef(RecVideo);
