/**
 * @title: 实时视频
 */

import React, { useEffect } from 'react';
import { useSetState } from 'ahooks';
import { request, getUrlParam } from '@vtx/utils';
import { message } from 'antd';
import PropTypes from 'prop-types';
function getPreviewUrl(params = {}) {
    return new Promise(resolve => {
        request.get('/cloud/vis/base/np/artemis/previewUrl.smvc', { body: params }).then(res => {
            if (res?.result == 0) {
                resolve(res);
            }
        });
    });
}
function loadJs(path) {
    if (!path || path.length === 0) {
        throw new Error('argument "path" is required !');
    }
    let head = document.getElementsByTagName('head')[0];
    let script = document.createElement('script');
    script.src = path;
    script.type = 'text/javascript';
    head.appendChild(script);
}
function isSupportH5() {
    return getBrowseVersion().indexOf('msie') != -1 ? false : true;
}
function getBrowseVersion() {
    let userAgent = navigator.userAgent.toLowerCase();
    let browser = userAgent.match(/(firefox|chrome|safari|opera|msie)/);
    let browserId = 'msie';
    let browserVersion = '';
    let isIE11 = userAgent.toLowerCase().indexOf('trident') > -1 && userAgent.indexOf('rv') > -1;
    if (isIE11) {
        browserId = 'msie';
        browserVersion = '11.0';
    } else {
        if (browser.length >= 2) {
            browserId = browser[1];
        } else {
            browserId = 'msie';
        }
        browserVersion = (userAgent.match(new RegExp('.+(?:version)[/: ]([\\d.]+)')) ||
            userAgent.match(new RegExp(`(?:${browserId})[/: ]([\\d.]+)`)) || [0, '0'])[1];
    }
    return browserId + browserVersion;
}
let winList = [],
    videoObj = [];

function Monitor(props) {
    const [state, setState] = useSetState({
        winIndex: 0,
        videoId: props.videoId || 'videoPlay',
        winNum: props.winNum || 1,
    });

    props.monitorVideoPlay$ &&
        props.monitorVideoPlay$.useSubscription(data => {
            play(data);
        });
    props.monitorWindowChange$ &&
        props.monitorWindowChange$.useSubscription(data => {
            setState({ winNum: data.winNum });
            initWindow(data.winNum);
        });

    function initWindow(num) {
        let winNum = num || state.winNum;
        let wins = [],
            style = { height: '100%', width: '100%' };
        if (winNum == 4) {
            style = { height: '50%', width: '50%' };
        } else if (winNum == 9) {
            style = { height: '33.33%', width: '33.33%' };
        }
        for (let index = 0; index < winNum; index++) {
            wins.push(
                <div
                    key={`${state.videoId}${index}`}
                    id={`${state.videoId}${index}`}
                    className={`videoItem ${state.winIndex === index ? 'checked' : ''}`}
                    style={style}
                    onClick={() => {
                        setState({
                            winIndex: index,
                        });
                    }}
                ></div>,
            );
        }
        return wins;
    }

    function play(obj) {
        videoObj[state.wndIndex] && videoObj[state.wndIndex].destroy();

        obj &&
            getPreviewUrl({
                channelNum: obj.channelNum,
                deviceId: obj.deviceId,
                linkMode: 'rtsp',
                tenantId: getUrlParam('tenantId'),
            }).then(res => {
                if (!!res && !res.result) {
                    let data = res.data;
                    if (data.url && data.url.length > 0) {
                        winList[state.winIndex] = data;
                        // eslint-disable-next-line no-undef
                        videoObj[state.winIndex] = initPlayer(
                            state.videoId + state.winIndex,
                            data.url,
                            true,
                        );
                        if (state.winIndex === state.winNum - 1) {
                            setState({
                                winIndex: 0,
                            });
                        } else {
                            setState({
                                winIndex: state.winIndex + 1,
                            });
                        }
                    } else {
                        message.warn('未获取到监控点流地址');
                    }
                } else {
                    message.warn('未获取到监控点流地址');
                }
            });
    }

    function initJS() {
        if (isSupportH5()) {
            Promise.all([
                loadJs('./resources/lib/video/h5/flv.min.js'),
                loadJs('./resources/lib/video/h5/DPlayer.min.js'),
                loadJs('./resources/lib/video/h5/vtx-player-h5.js'),
            ]).then(() => {
                play();
            });
        } else {
            Promise.all([
                loadJs('./resources/lib/video/flash/ckplayer.min.js'),
                loadJs('./resources/lib/video/flash/vtx-player-flash.js'),
            ]).then(() => {
                play();
            });
        }
    }

    useEffect(() => {
        initJS();
    }, []);

    return <div className="videoList">{initWindow()}</div>;
}

Monitor.propTypes = {
    videoId: PropTypes.any,
    winNum: PropTypes.any,
    monitorWindowChange$: PropTypes.any,
    monitorVideoPlay$: PropTypes.any,
};

export default Monitor;
