<template>
    <div class="playerContainer" ref="playerContainer">
        <div id="playWnd" class="playWnd" v-if="!showSetting" ref="playWnd">
            {{ text }}
        </div>
        <div id="tipsWindow" v-else>
            <img
                :src="require('@/assets/img/empty.png')"
                alt="控件未安装"
                class="empty-img"
            />
            <h1>控件未安装或加载失败</h1>

            <div v-if="!simpleTips">
                <h3>支持谷歌浏览器、360浏览器、搜狗浏览器、火狐浏览器</h3>
                <el-button type="text" @click="openModel"
                    >谷歌浏览器设置指南</el-button
                >
                <h3>
                    若已安装控件，请尝试重启浏览器重试当前操作。若问题任然存在，请检查网络或重新安装控件。
                </h3>
                <a
                    class="download-btn"
                    download="VideoWebPlugin.exe"
                    :href="downloadUrl"
                >
                    <i class="el-icon-download"></i>
                    下载浏览器控件
                </a>
            </div>
            <div v-else>
                <h3>请参考视频监控页提示，下载安装控件。</h3>
            </div>
        </div>
        <video-plugin-browser-setting
            ref="BrowserSetting"
        ></video-plugin-browser-setting>
    </div>
</template>

<script>
import utils from '@/hotent-ui-util'
import videoPluginBrowserSetting from '@/components/dialog/VideoPluginBrowserSetting.vue'
export default {
    components: {
        videoPluginBrowserSetting,
    },
    props: {
        options: {
            type: Object,
            default: () => {
                return {
                    layout: '2x2',
                    showToolbar: 1,
                    simpleTips: false,
                    mountedInit: true
                }
            },
        },
    },
    data() {
        return {
            text: '',
            downloadUrl: './../static/plugin/VideoWebPlugin.exe',
            showSetting: false,
            simpleTips: this.options.simpleTips,
            width: 0,
            height: 0,
            // 插件对象实例，初始化为null，需要创建多个插件窗口时，需要定义多个插件对象实例变量，各个变量唯一标志对应的插件实例
            oWebControl: null,
            bIE: !!window.ActiveXObject || 'ActiveXObject' in window, // 是否为IE浏览器
            pubKey: '', // demo中未使用加密，可根据需求参照开发指南自行使用加密功能
            initCount: 0,
            playMode: 0, // 播放类型，0-预览，1-回放
            showDivInstruction: false, // 标志是否显示使用说明弹框
            endTime: '',
            startTime: '',
            playTime: '',
            param: {
                argument: {
                    appkey: window.context.videoAppkey,
                    ip: window.context.videoIp,
                    port: window.context.videoPort,
                    secret: window.context.videoSecret,
                    enableHTTPS: 1,
                    language: 'zh_CN',
                    layout: this.options.layout,
                    playMode: 0,
                    reconnectDuration: 5,
                    reconnectTimes: 5,
                    showSmart: 0,
                    showToolbar: this.options.showToolbar,
                    toolBarButtonIDs:
                        '2048,2049,2050,2304,2306,2305,2307,2308,2309,4096,4608,4097,4099,4098,4609,4100',
                    snapDir: 'D:/snap',
                    videoDir: 'D:/video',
                },
                funcName: 'init',
            },
            paramPlay: {
                argument: {
                    authUuid: '',
                    cameraIndexCode: '',
                    ezvizDirect: 0,
                    gpuMode: 0,
                    streamMode: 0,
                    transMode: 1,
                    wndId: -1,
                    cascade: 1,
                },
                funcName: 'startPreview',
            },
        }
    },
    created() {},
    mounted() {
        this.$nextTick(() => {
            this.getWindowSize()
        })
        if(this.options.mountedInit){
            this.open()
        }
        this.$root.$on('resize', () => {
            this.$nextTick(() => {
                this.getWindowSize()
                if (this.oWebControl) {
                    this.oWebControl.JS_Resize(this.width, this.height)
                }
            })
        })
    },
    beforeDestroy() {
        this.disconnect()
    },
    methods: {
        resize(width, height) {
            if(!this.oWebControl)return
            let iwidth = width ? width : this.width
            let iheight = height ? height : this.height
            this.oWebControl.JS_Resize(iwidth, iheight)
        },
        cutWindow(left = 0, top = 0, width = 0, height = 0) {
            if(!this.oWebControl)return
            this.oWebControl.JS_CuttingPartWindow(left, top, width, height)
        },
        repairWindow() {
            if(!this.oWebControl)return
            this.oWebControl.JS_RepairPartWindow(0, 0, this.width, this.height)
        },
        open() {
            this.initTime()
            this.initPlugin()
            this.getWindowSize()
        },
        destroy() {
            if(!this.oWebControl)return
            this.oWebControl.JS_DestroyWnd();
        },
        HideWnd() {
            if(!this.oWebControl)return
            this.oWebControl.JS_HideWnd();
        },
        ShowWnd() {
            if(!this.oWebControl)return
            this.oWebControl.JS_ShowWnd();
        },
        disconnect() {
            if(!this.oWebControl)return
            this.oWebControl.JS_HideWnd();
            this.oWebControl.JS_Disconnect().then(
                ()=>{
                    console.log('销毁成功')
                    this.oWebControl = null
                }
            )
        },
        play(code) {
            if (!code) return
            this.paramPlay.argument.cameraIndexCode = code
            let params = utils.deepClone(this.paramPlay)
            this.requestInterface(params)
        },
        requestInterface(param) {
            let JsonParam = param
            let JsonArgument = JsonParam.argument
            JsonParam.argument = JSON.stringify(JsonArgument)

            this.oWebControl.JS_RequestInterface(JsonParam).then((oData) => {
                console.log(oData)
                this.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''))
            })
        },
        autoInit() {
            let params = utils.deepClone(this.param)
            let JsonParam = params

            if (JsonParam.argument.hasOwnProperty('playMode')) {
                this.playMode = JsonParam.argument.playMode
            }
            //隐藏/显示轮巡功能模块
            // document.getElementById('TourPreview').style.display =
            //     0 == playMode && JsonParam.argument.hasOwnProperty('appkey')
            //         ? ''
            //         : 'none'

            //如果包含加密处理，处理加密字段
            if (JsonParam.argument.hasOwnProperty('encryptedFields')) {
                var enFields = JsonParam.argument.encryptedFields
                var strArray = new Array()
                strArray = enFields.split(',')
                for (var i = 0, len = strArray.length; i < len; i++) {
                    if ('appkey' == strArray[i]) {
                        if (JsonParam.argument.hasOwnProperty('appkey')) {
                            var appkey = JsonParam.argument.appkey
                            appkey = setEncrypt(appkey)
                            JsonParam.argument.appkey = appkey
                        }
                    }

                    if ('secret' == strArray[i]) {
                        if (JsonParam.argument.hasOwnProperty('secret')) {
                            var secret = JsonParam.argument.secret
                            secret = setEncrypt(secret)
                            JsonParam.argument.secret = secret
                        }
                    }

                    if ('ip' == strArray[i]) {
                        if (JsonParam.argument.hasOwnProperty('ip')) {
                            var ip = JsonParam.argument.ip
                            ip = setEncrypt(ip)
                            JsonParam.argument.ip = ip
                        }
                    }

                    if ('snapDir' == strArray[i]) {
                        if (JsonParam.argument.hasOwnProperty('snapDir')) {
                            var snapDir = JsonParam.argument.snapDir
                            snapDir = setEncrypt(snapDir)
                            JsonParam.argument.snapDir = snapDir
                        }
                    }

                    if ('layout' == strArray[i]) {
                        if (JsonParam.argument.hasOwnProperty('layout')) {
                            var layout = JsonParam.argument.layout
                            layout = setEncrypt(layout)
                            JsonParam.argument.layout = layout
                        }
                    }

                    if ('videoDir' == strArray[i]) {
                        if (JsonParam.argument.hasOwnProperty('videoDir')) {
                            var videoDir = JsonParam.argument.videoDir
                            videoDir = setEncrypt(videoDir)
                            JsonParam.argument.videoDir = videoDir
                        }
                    }
                }
            }

            //1.4.1及以上版本支持argument字段为json，以下版本argument必须为string
            let JsonArgument = JsonParam.argument
            JsonParam.argument = JSON.stringify(JsonArgument)

            //param = {
            //    "argument": '{"appkey": "21216099","ip": "172.7.13.242","port": 443,"secret": "dX5Gt0C0hmKbQ9ucHnWY","enableHTTPS": 1,"language": "zh_CN","layout": "2x2","playMode": 0,"reconnectDuration": 5,"reconnectTimes": 5,"showSmart": 0,"showToolbar": 1,"snapDir": "D:/snap","videoDir": "D:/video"}',
            //    "funcName": "init"
            //}

            this.oWebControl.JS_RequestInterface(JsonParam).then((oData) => {
                console.log(oData)
                this.$emit('ready')
                this.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''))
                // UpdatePlayParamValue()
                this.oWebControl.JS_Resize(this.width, this.height)
            })
        },
        // 初始化插件
        initPlugin() {
            if(this.oWebControl!==null) return
            console.log("初始化插件")
            // 创建插件实例，并启动本地服务建立websocket连接，创建插件窗口
            this.oWebControl = new WebControl({
                szPluginContainer: 'playWnd',
                iServicePortStart: 15900,
                iServicePortEnd: 15909,
                szClassId: '23BF3B0A-2C56-4D97-9C03-0CB103AA8F11', // 用于IE10使用ActiveX的clsid
                cbConnectSuccess: () => {
                    this.initCount = 0
                    this.setCallbacks()
                    this.oWebControl
                        .JS_StartService('window', {
                            dllPath: './VideoPluginConnect.dll',
                        })
                        .then(
                            () => {
                                this.oWebControl
                                    .JS_CreateWnd(
                                        'playWnd',
                                        this.width,
                                        this.height
                                    )
                                    .then(() => {
                                        console.log('JS_CreateWnd success')
                                        this.autoInit()
                                        this.oWebControl
                                            .JS_RequestInterface({
                                                funcName: 'getRSAPubKey',
                                                argument: JSON.stringify({
                                                    keyLength: 1024,
                                                }),
                                            })
                                            .then((oData) => {
                                                console.log(oData)
                                                if (oData.responseMsg.data) {
                                                    this.pubKey =
                                                        oData.responseMsg.data
                                                }
                                            })
                                    })
                            },
                            () => {}
                        )
                },
                cbConnectError: () => {
                    console.log('cbConnectError')
                    this.oWebControl = null
                    this.text = '插件未启动，正在尝试启动，请稍候...'
                    // $('#playWnd').html('插件未启动，正在尝试启动，请稍候...')
                    WebControl.JS_WakeUp('VideoWebPlugin://')
                    this.initCount++
                    if (this.initCount < 3) {
                        setTimeout(() => {
                            this.initPlugin()
                        }, 3000)
                    } else {
                        this.showSetting = true
                        this.text = ''
                    }
                },
                cbConnectClose: (bNormalClose) => {
                    // 异常断开：bNormalClose = false
                    // JS_Disconnect正常断开：bNormalClose = true
                    console.log('cbConnectClose')
                    this.oWebControl = null
                },
            })
        },
        // 获取窗口宽高
        getWindowSize() {
            this.width = this.$refs.playerContainer.clientWidth
            this.height = this.$refs.playerContainer.clientHeight
        },
        // 初始化时间变量
        initTime() {
            this.endTime = Math.floor(
                new Date(
                    this.dateFormat(new Date(), 'yyyy-MM-dd 23:59:59')
                        .replace('-', '/')
                        .replace('-', '/')
                ).getTime() / 1000
            ).toString()
            this.startTime = Math.floor(
                new Date(
                    this.dateFormat(new Date(), 'yyyy-MM-dd 00:00:00')
                        .replace('-', '/')
                        .replace('-', '/')
                ).getTime() / 1000
            ).toString()
            this.playTime = Math.floor(
                new Date(
                    this.dateFormat(new Date(), 'yyyy-MM-dd 00:00:00')
                        .replace('-', '/')
                        .replace('-', '/')
                ).getTime() / 1000
            ).toString()
        },
        // 设置窗口控制回调
        setCallbacks() {
            this.oWebControl.JS_SetWindowControlCallback({
                cbIntegrationCallBack: this.cbIntegrationCallBack,
            })
        },

        // 推送消息
        cbIntegrationCallBack(oData) {
            this.showCBInfo(JSON.stringify(oData.responseMsg))
        },
        // 显示接口返回的消息及插件回调信息
        showCBInfo(szInfo, type) {
            console.log('接口返回的消息及插件回调信息:' + type + szInfo)
        },

        // 格式化时间
        dateFormat(oDate, fmt) {
            var o = {
                'M+': oDate.getMonth() + 1, //月份
                'd+': oDate.getDate(), //日
                'h+': oDate.getHours(), //小时
                'm+': oDate.getMinutes(), //分
                's+': oDate.getSeconds(), //秒
                'q+': Math.floor((oDate.getMonth() + 3) / 3), //季度
                S: oDate.getMilliseconds(), //毫秒
            }
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(
                    RegExp.$1,
                    (oDate.getFullYear() + '').substr(4 - RegExp.$1.length)
                )
            }
            for (var k in o) {
                if (new RegExp('(' + k + ')').test(fmt)) {
                    fmt = fmt.replace(
                        RegExp.$1,
                        RegExp.$1.length == 1
                            ? o[k]
                            : ('00' + o[k]).substr(('' + o[k]).length)
                    )
                }
            }
            return fmt
        },

        textbox(obj, min, max) {
            obj.value = obj.value.replace(/[^\d]/g, '')
            if (
                parseInt(obj.value) == obj.value &&
                parseInt(obj.value) >= min &&
                parseInt(obj.value) <= max
            ) {
            } else {
                if (parseInt(obj.value) < min) {
                    obj.value = min
                }
                if (parseInt(obj.value) > max) {
                    obj.value = max
                }
            }
        },
        openModel() {
            this.$refs.BrowserSetting.open()
        },
    },
}
</script>

<style lang="scss" scoped>
$border-color: #566a7e;
$active-color: #409eff;
$high-light-color: #ff7c40;
$text-color:#b7c6d8;
$text-color-dark:#8993a0;
$dark-bg:#0b1926;
$dark-bg-lighter: #1d3b57;
.playerContainer {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
}
#playWnd{
    width: 100%;
    height: 100%;
}
#tipsWindow{
    width: 100%;
    height: 100%;
    background-color: rgba($dark-bg, 0.6);
    text-align: center;
    .empty-img{
        display: inline-block;
        width: 26%;
        margin:0 auto;
    }
    h1{
        font-size: 24px;
    }
    h3{
        font-size: 14px;
    }
}

.download-btn{
    color: $active-color;
    text-decoration: none;
    cursor: pointer;
    font-size: 18px;
    font-weight: 700;
    i{
        font-size: 18px;
    }
}
</style>