;
(function () {
    var _global;
    //工具函数
    //配置合并
    function extend(def, opt, override) {
        for (var k in opt) {
            if (opt.hasOwnProperty(k) && (!def.hasOwnProperty(k) || override)) {
                def[k] = opt[k]
            }
        }
        return def;
    }

    function FaceIDStart(options) {
        let streaming = false; // 是否开始捕获媒体
        let imageUrl = ''; // 图片base64
        let timerID // 定时器
        let timeSum // 定时次数
        var defaults = {
            //默认各种参数、各种属性
            width: '500px', //  video宽
            height: '500px', //  video高
            timeSum: 10, // 人脸识别次数
            autoPlay: false, // 是否是自动识别验证
            canvasFaceDisplay: true, // 是否暂停
            videoDisplay: true, // 摄像头是否开启
        };
        //options合并到defaults上,defaults继承了options上的各种属性和方法,将所有的赋值给endOptions
        var endOptions = extend(defaults, options, true)
        timeSum = endOptions.timeSum // 定时次数
        var FaceVideodiv = document.createElement('div');
        var FaceVideo =
            '<div  id="FaceModal" class="FaceModal">' +
            '<div class="FaceBox" style="width:' + endOptions.width + ';height:' + endOptions.height + '">' +
            '<div class="close" id="close">关闭</div>' +
            '<video id="videoFace" class="videoFace" width = ' + endOptions.width + ' height =  ' + endOptions.height + ' >  </video>' +
            '<canvas id="canvasFace" class="canvasFace" width=' + endOptions.width + ' height=' + endOptions.height + '></canvas>' +
            '<div  class="FaceFotter"><button id="videoStart" class="floatL FButton bgPrimary" >开启摄像头</button> <button id="videoScreenshot" class="FButton bgAqu">拍照/截图</button> <button  id="videoEnd" class="floatR FButton bgDanger"  >关闭摄像头</button></div>' +
            '</div>' +
            '</div>'
        FaceVideodiv.innerHTML = FaceVideo;
        FaceIDEnd() //删除元素控件
        //把div元素节点添加到body元素节点中成为其子节点，但是放在body的现有子节点的最后
        document.body.appendChild(FaceVideodiv);
        // 生成Dom后添加按钮点击事件 开启摄像头
        document.getElementById('videoStart').addEventListener('click', function (e) {
            e.stopPropagation(); //取消事件冒泡
            document.getElementById('canvasFace').style.display = "none";
            videoStart()
        })

        // 生成Dom后添加按钮点击事件 拍照/截图
        document.getElementById('videoScreenshot').addEventListener('click', function (e) {
            e.stopPropagation(); //取消事件冒泡
            if (!endOptions.videoDisplay) { // 摄像头是否开启
                return false
            }
            endOptions.canvasFaceDisplay = !endOptions.canvasFaceDisplay
            if (endOptions.canvasFaceDisplay) {
                document.getElementById('canvasFace').style.display = "none";
                removeClass(document.getElementById('videoScreenshot'), 'suspend') //移除class
                document.getElementById('videoScreenshot').innerHTML = "拍照/截图";
            } else {
                document.getElementById('canvasFace').style.display = "block";
                videoScreenshot()
                addClass(document.getElementById('videoScreenshot'), 'suspend') //添加class
                document.getElementById('videoScreenshot').innerHTML = "继续";
            }
        })

        // 生成Dom后添加按钮点击事件 关闭摄像头
        document.getElementById('videoEnd').addEventListener('click', function (e) {
            e.stopPropagation(); //取消事件冒泡
            document.getElementById('canvasFace').style.display = "none";
            videoEnd()


        })

        // 生成Dom后添加按钮点击事件 关闭整个DOm
        document.getElementById('close').addEventListener('click', function (e) {
            e.stopPropagation(); //取消事件冒泡
            FaceIDEnd() //删除元素控件
            videoEnd()
        })

        //实现功能的代码
        videoStart()

        //摄像头开启
        function videoStart() {
            try {
                let video = document.querySelector("#videoFace");
                let canvas = document.querySelector("#canvasFace");
                videoEnd() //摄像头关闭
                // 获取用户媒体,包含视频和音频
                navigator.mediaDevices.getUserMedia({
                        video: true
                    })
                    .then(stream => {
                        video.srcObject = stream; // 将捕获的视频流传递给video  放弃window.URL.createObjectURL(stream)的使用
                        video.play(); //  播放视频
                    });

                // 监听视频流就位事件,即视频可以播放了
                video.addEventListener('canplay', function (ev) {
                    if (!streaming) {
                        video.setAttribute('width', endOptions.width);
                        video.setAttribute('height', endOptions.height);
                        canvas.setAttribute('width', endOptions.width);
                        canvas.setAttribute('height', endOptions.height);
                        streaming = true;

                    }
                }, false);
                tackcapture()
            } catch (error) {
                message.error("当前浏览器没有摄像头权限，请先授权。")
            }
        }

        //摄像头开启后执行方法
        function tackcapture() {
            endOptions.videoDisplay = true // 摄像头是否开启
            console.log('摄像头成功开启')

            if (endOptions.autoPlay) {
                // 自动人脸识别 定时器执行人脸扫描 
                autoPlayFaceID()
            }


        }

        //摄像头暂停截图 自动人脸识别 定时器执行人脸扫描 
        function autoPlayFaceID() {
            // 添加定时器
            timerID = setInterval(() => {
                    if (timeSum == 0) {
                        alert('人脸识别超时,关闭摄像头');
                        timeSum = endOptions.timeSum
                        videoEnd()
                    } else {
                        autoPlayAjax() // 自动人脸识别ajax请求
                        timeSum--;
                    }
                },
                2000
            );
        }

        // 手动人脸识别ajax请求
        function playAjax() {
            var img = screenshot()
            var data = {
                "code": "88010021",
                "params": [{
                    "imageBase64": img
                }]
            }
            $Ajax({
                //请求方式
                type: "POST",
                //请求地址
                url: "http:// 172.18.100.86:52774/bdhealth/sysInternalMutiple",
                headers: {
                    'Authorization': 'Basic aGlwOmhpcA==',
                    'Access-Control-Allow-Origin': ' 172.18.100.86',
                },
                contentType: "application/json",
                //数据，json字符串
                dataType: 'json',
                timeout: 10000,
                contentType: "application/json",
                //数据，json字符串
                data: JSON.stringify(data),
                //请求成功
                success: function (result) {
                    var res = JSON.parse(result)
                    if (res.errorCode === 0 && res.result) {
                        var faceValue = res.result.faceValue
                        // 外部获取截图base64方法存在
                        if (endOptions.videoScreenshot) {
                            endOptions.videoScreenshot(faceValue)
                        }
                    }
                },
                //请求失败，包含具体的错误信息
                error: function (e) {
                    console.log(e.status);
                    console.log(e.responseText);
                }
            });

        }

        // 自动人脸识别ajax请求
        function autoPlayAjax() {
            var img = screenshot()
            var data = {
                "code": "88010023",
                "params": [{
                    "imageBase64": img,
                    "faceType": endOptions.faceType
                }]
            }

            $Ajax({
                //请求方式
                type: "POST",
                //请求地址
                url: "http:// 172.18.100.86:52774/bdhealth/sysInternalMutiple",
                contentType: "application/json",
                headers: {
                    'Authorization': 'Basic aGlwOmhpcA==',
                    'Access-Control-Allow-Origin': ' 172.18.100.86',
                },
                dataType: 'json',
                timeout: 10000,
                contentType: "application/json",
                //数据，json字符串
                data: JSON.stringify(data),
                //请求成功
                success: function (result) {
                    var res = JSON.parse(result)
                    console.log(res);
                },
                //请求失败，包含具体的错误信息
                error: function (e) {
                    console.log(e.status);
                    console.log(e.responseText);
                }
            });

        }

        //摄像头暂停截图
        function videoScreenshot() {
            playAjax() // 手动人脸识别ajax请求

        }

        //截图
        function screenshot() {
            let video = document.querySelector("#videoFace");
            let canvas = document.querySelector("#canvasFace");
            let context = canvas.getContext('2d');
            // 需要判断媒体流是否就绪
            if (streaming) {
                context.drawImage(video, 0, 0, 500, 500); // 将视频画面捕捉后绘制到canvas里面
            }
            return canvas.toDataURL('image/png').substring(canvas.toDataURL('image/png').indexOf(",") + 1)
        }


        //摄像头关闭
        function videoEnd() {
            let video = document.querySelector("#videoFace");
            video.srcObject && video.srcObject.getTracks()[0].stop(); //关闭摄像头
            endOptions.videoDisplay = false // 摄像头是否开启
            console.log('摄像头成功关闭')
            clearInterval(timerID); // 移除定时器
        }

    }
    // 人脸识别控件Dom元素整体删除，摄像头关闭
    function FaceIDEnd(options) {
        let FaceModal = document.querySelector("#FaceModal");
        let video = document.querySelector("#videoFace");
        if (FaceModal) {
            if (FaceModal != null) {
                FaceModal.parentNode.removeChild(FaceModal);
            }
            console.log('人脸识别控件成功移除')
        }
        if (video) {
            video.srcObject && video.srcObject.getTracks()[0].stop(); //关闭摄像头
            console.log('摄像头成功关闭')
        }
        // clearInterval(timerID); // 移除定时器
    }

    //添加class
    function addClass(obj, cls) {
        var obj_class = obj.className //获取class的内容；
        var blank = (obj_class != '') ? ' ' : ''; //判断获取的class是否为空，如果不为空，则添加空格；
        var added = obj_class + blank + cls; //组合原来的class和需要添加的class，中间加上空格；
        obj.className = added; //替换原来的class；
    }

    function hasClass(elem, cls) {
        cls = cls || '';
        if (cls.replace(/\s/g, '').length == 0) return false;
        return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' ');
    }

    function removeClass(elem, cls) {
        if (hasClass(elem, cls)) {
            var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, '') + ' ';
            while (newClass.indexOf(' ' + cls + ' ') >= 0) {
                newClass = newClass.replace(' ' + cls + ' ', ' ');
            }
            elem.className = newClass.replace(/^\s+|\s+$/g, '');
        }
    }

    //封装成类似JQuery的形式，供调用
    function $Ajax(options) {
        options = options || {}; //调用函数时如果options没有指定，就给它赋值{},一个空的Object
        options.type = (options.type || "GET").toUpperCase(); /// 请求格式GET、POST，默认为GET
        options.dataType = options.dataType || "json"; //响应数据格式，默认json
        options.headers = options.headers || {}; //header
        var params = options.data; //options.data请求的数据 formatParams(options.data)
        var xhr;

        //考虑兼容性
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else if (window.ActiveObject) { //兼容IE6以下版本
            xhr = new ActiveXobject('Microsoft.XMLHTTP');
        }

        //启动并发送一个请求
        if (options.type == "GET") {
            xhr.open("GET", options.url + "?" + params, true);
            xhr.send(null);
        } else if (options.type == "POST") {
            xhr.open("post", options.url, true);

            //设置表单提交时的内容类型
            //Content-type数据请求的格式
            xhr.setRequestHeader("Content-type", "application/json");
            for (let key in options.headers) {
                let value = options.headers[key]
                xhr.setRequestHeader(key, value)
            }

            xhr.send(params);
        }

        //    设置有效时间
        setTimeout(function () {
            if (xhr.readySate != 4) {
                xhr.abort();
            }
        }, options.timeout)

        //    接收
        //     options.success成功之后的回调函数  options.error失败后的回调函数
        //xhr.responseText,xhr.responseXML  获得字符串形式的响应数据或者XML形式的响应数据
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var status = xhr.status;
                if (status >= 200 && status < 300 || status == 304) {
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                } else {
                    options.error && options.error(status);
                }
            }
        }
    }

    //将插件暴露给全局对象
    _global = (function () {
        return this || (0, eval)('this')
    }());
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = {
            FaceIDStart,
            FaceIDEnd
        };
    } else if (typeof define === "function" && define.amd) {
        define(function () {
            return FaceIDStart;
        })
    } else {
        !('FaceIDStart' in _global) && (_global.FaceIDStart = FaceIDStart);
    }


}());