/*
 *title:server-user-add
 *@auther  liaoxin
 *date:2018/11/29
*/
layui.extend({
    common: 'js/common'
}).use(['jquery', 'common', 'form', 'laydate', 'upload', 'element'], function () {
    var element = layui.element;
    //  Jquery插件
    var $ = layui.jquery;
    //  引入公共模块
    var common = layui.common;
    //引入表单
    var form = layui.form;
    //时间模块
    var laydate = layui.laydate;
    //  图片上传
    var upload = layui.upload;

    var base64Array = null;

    var result = null;

    //页面元素
    var $node = {
        //卡号
        cardNo: $("#card_no"),
        //
        faceImage: $(".layui-upload-list .layer-photos-content").length,

        rangeDate: $("#rangeDate"),

        faceRangeDate: $("#faceRangeDate"),

        openPermissionType: $('input[name="openPermissionType"]'),
    }


    //监听选项卡切换
    element.on('tab(openPermission)', function (data) {
        //选项卡下标index：    0：人脸门禁     1：门禁卡门禁
        let index = data.index;
        if (index == 0) {

            $node.openPermissionType.val('1')
        } else if (index == 1) {
            
            $node.openPermissionType.val('2')
        }
    });

    // 卡号时间范围
    laydate.render({
        elem: '#rangeDate',
        type: 'date',
        range: true,
        theme: 'molv'
    });

    //人脸时间范围
    laydate.render({
        elem: '#faceRangeDate',
        type: 'date',
        range: true,
        theme: 'molv'
    });

    //监听提交
    form.on('submit(submitButton)', function (data) {
        common.timer($('button[lay-filter="submitButton"]'));
        var cardNo = $node.cardNo.val();
        var faceImage = $node.faceImage;
        var rangeDate = $node.rangeDate.val();
        var faceRangeDate = $node.faceRangeDate.val();
        var openPermissionType = $node.openPermissionType.val();
        if (cardNo) {
            if (!rangeDate) {
                layer.msg("请输入门禁卡有效期！");
                return;
            }
        }
        if (faceImage === 1) {
            if (!faceRangeDate) {
                layer.msg("请输入人脸有效期！")
                return;
            }
        }
        //添加自定义传值参数
        if (rangeDate != null && rangeDate.trim().length > 0) {
            //需要带空格
            var dates = rangeDate.split(" - ");
            if (dates.length > 1) {
                var beginDate = dates[0];
                var endDate = dates[1];
                data.field['beginDate'] = beginDate + ' 00:00:00';
                data.field['endDate'] = endDate + ' 23:59:59';
            }
        }
        if (faceRangeDate != null && faceRangeDate.trim().length > 0) {
            //需要带空格
            var dates = faceRangeDate.split(" - ");
            if (dates.length > 1) {
                var imgBeginDate = dates[0];
                var imgEndDate = dates[1];
                data.field['imgBeginDate'] = imgBeginDate + ' 00:00:00';
                data.field['imgEndDate'] = imgEndDate + ' 23:59:59';
            }
        }

        //1、图片到服务器
        result = savephotoFn();
        if (result != null) {
            data.field.imgUri = result.fullPath;
            data.field.faceCode = result.md5;
        } else {
            //上传图片失败
            if (base64Array != null) {
                return;
            }
        }
        data.field.openPermissionType = openPermissionType
        data.field.deviceAccessType = 10; //下发门禁信息到通用位置的设备上
        common.sendAsyncRequest("/estate/serverUser/addOrEditOpenPermission", 'POST', data.field, callbackFn);
    });
    /*//开启特殊门禁设备下发选择窗口
    form.on('submit(openSpecialButton)', function(data){
        common.openDefaultIframe({
            title   :   '人脸/门禁卡下发设备选择页面',
            content :   '/estate/serverUser/specialOpenPermission/' + data.field.name + '/' + data.field.id
        });
    });*/

    //回调函数
    function callbackFn(result) {
        if (result.data) {
            closeFn();
        } else {//添加失败
            layer.msg("设置失败");
        }
    };

    //关闭事件
    function closeFn() {
        layer.msg("设置成功", {
            time: 500,
            shade: [0.1, '#000', true]
        }, function () {
            //获取当前弹窗出层的名字
            var index = parent.layer.getFrameIndex(window.name);
            //关闭弹窗层
            parent.layer.close(index);
            // 父页面刷新
            parent.location.reload();
        });
    };

    //取消按钮
    $('#cancel_btn').on("click", function () {
        //获取当前弹窗出层的名字
        var index = parent.layer.getFrameIndex(window.name);
        //关闭弹窗层
        parent.layer.close(index);
    });


    //图片到服务器
    var savephotoFn = function () {
        if (base64Array == null) {
            return;
        }
        var data = null;
        $.ajax({
            type: "POST",
            url: "/common/file/uploadBase64",
            contentType: "application/json;charset=utf-8",
            cache: false,
            async: false,
            data: JSON.stringify(base64Array),
            success: function (res) {
                if (res.code == "200") {//上传成功
                    if (res.data) {
                        data = res.data;
                    }
                } else {
                    if (res.code == "500.1") {
                        layer.msg(res.msg);
                    } else {
                        layer.msg("图片上传失败，请联系管理员！");
                    }
                }
            },
            error: function () {
                layer.msg("图片上传失败，请联系管理员！");
            },
            dataFilter: function (data) {
                return data;
            }
        });
        return data;
    };

    //人脸采集
    const width= "320";
    const height= "240";
    let video = document.getElementById('video');
    var canvas =  document.getElementById('canvas');
    var ctx = canvas.getContext("2d");
    var initWebcamFn = function () {
        var pos = 0, saveCB, image = [];
        canvas.setAttribute('width', "320");
        canvas.setAttribute('height', "240");
        //IE8以上及主流浏览器
        if (canvas.toDataURL) {
            //设置画布为2d
            //截图320*240，即整个画布作为有效区
            image = ctx.getImageData(0, 0, width, height);
            saveCB = function (data) {
                //把data切割为数组
                var col = data.split(";");
                var img = image;
                //绘制图像，参数data  只是每行的数据  ，例如320*240 大小的照片，一张完整的照片下来需要240个data，每个data有320个rgb
                for (var i = 0; i < 320; i++) {
                    //转换为十进制
                    var tmp = parseInt(col[i]);
                    img.data[pos + 0] = (tmp >> 16) & 0xff;
                    img.data[pos + 1] = (tmp >> 8) & 0xff;
                    img.data[pos + 2] = tmp & 0xff;
                    img.data[pos + 3] = 0xff;
                    pos += 4;
                }
                //当绘制320*240像素的图片时发给后端php
                if (pos >= 4 * 320 * 240) {
                    //把图像放到画布上,输出为png格式
                    ctx.putImageData(img, 0, 0);
                    imageShowFn(canvas.toDataURL("image/png"));
                    pos = 0;
                }
            };
        } else {
            layer.msg("请升级或者更换浏览器后再操作");
        }

        //调用摄像头
        if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
            //调用用户媒体设备, 访问摄像头
            getUserMedia({video : {width: width, height: height}}, success, error);
        } else {
            alert('不支持访问用户媒体');
        }
        /*$("#webcam").webcam({
            width: 320,
            height: 240,
            mode: "callback",
            swffile: "/js/estate/jscam_canvas_only.swf",
            onSave: saveCB,
            onCapture: function () {
                webcam.save();
            },
            debug: function (type, string) {
                console.log(type + ": " + string);
            }
        });*/
    };

    //图片预览
    var imageShowFn = function (url) {
        var dom = $([" <div class='layer-photos-content'>" +
        "<img class='layui-upload-img' src='" + url + "'>" +
        " <span class='layui-layer-setwin'><a class='layui-layer-ico layui-layer-close layui-layer-close2'></a></span>" +
        " </div>"].join(''));
        //点击删除预览图片
        dom.find('.layui-layer-close').on('click', function () {
            $(this).parents(".layer-photos-content").remove();
            base64Array = null;
        });
        base64Array = url;
        var $imageList = $(".layui-upload-list");
        $imageList.append(dom);
    };

    //点击调用摄像头
    $('#photo_webcam').on("click", function () {
        if ($(this).hasClass("layui-bg-webcam")) {
            //点击拍照
            var length = $(".layui-upload-list .layer-photos-content").length;
            if (base64Array != null || length >= 1) {
                layer.msg("最多设置一张图片，请先删除再操作");
                return;
            }
            ctx.drawImage(video, 0, 0, width, height);
            imageShowFn(canvas.toDataURL("image/png"));
        } else {
            //开启摄像头
            $('#picture-img').hide();
            initWebcamFn();
            $('#photo_graph').show();
            $('#video').show();
            $(this).addClass("layui-bg-webcam");
            $(this).text("点击拍照");
        }
    });

    //上传图片
    $('#photo_upload').on("click", function () {
        var length = $(".layui-upload-list .layer-photos-content").length;
        if (base64Array != null || length >= 1) {
            layer.msg("最多设置一张图片，请先删除再操作");
            return;
        }
        $('#btn_file').click();
        $('#btn_file').change(function () {
            var files = this.files;
            if (files && files.length > 1) {
                document.getElementById("btn_file").outerHTML = document.getElementById("btn_file").outerHTML;
                layer.msg("最多设置一张图片，请先删除后再操作");
                return;
            }
            for (var i = 0; i < files.length; i++) {
                var img = files[i];
                if (!/^(\s|\S)+(jpg|JPG|jpeg|gif|png|PNG|JPEG|GIF|PNG)+$/.test(img.name)) {
                    document.getElementById("btn_file").outerHTML = document.getElementById("btn_file").outerHTML;
                    layer.msg("图片类型必须是png格式");
                    return;
                }
                base64Image({
                    width: 500,                             /*【选填】宽度默认750，如果图片尺寸大于该宽度，图片将被设置为该宽度*/
                    ratio: 0.75,                            /*【选填】压缩率默认0.75 */
                    file: this,                              /*【必填】对应的上传元素 */
                    callback: function (imageUrl) {        /*【必填】处理成功后的回调函数 */
                        /*imageUrl为得到的图片base64数据，这里可以进行上传到服务器或者其他逻辑操作 */
                        imageShowFn(imageUrl);
                    },
                });
            }
        });
        document.getElementById("btn_file").outerHTML = document.getElementById("btn_file").outerHTML;
    });

    //点击删除（清空数据库）
    $(document).on('click', '.layui-layer-close', function () {
        $(this).parents(".layer-photos-content").remove();
        document.getElementById("btn_file").outerHTML = document.getElementById("btn_file").outerHTML;
        base64Array = null;
        $("#face_code").val(null);
        $("#image_uri").val(null);
    });

    //访问用户媒体设备的兼容方法
    function getUserMedia(constraints, success, error) {
        if (navigator.mediaDevices.getUserMedia) {
            //最新的标准API
            navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
            //webkit核心浏览器
            navigator.webkitGetUserMedia(constraints,success, error)
        } else if (navigator.mozGetUserMedia) {
            //firfox浏览器
            navigator.mozGetUserMedia(constraints, success, error);
        } else if (navigator.getUserMedia) {
            //旧版API
            navigator.getUserMedia(constraints, success, error);
        }
    }
    function success(stream) {
        //兼容webkit核心浏览器
        let CompatibleURL = window.URL || window.webkitURL;
        //将视频流设置为video元素的源
        console.log(stream);
        //video.src = CompatibleURL.createObjectURL(stream);
        video.srcObject = stream;
        video.play();
    }
    function error(error) {
        alert('访问用户媒体设备失败');
    }
});
