layui.extend({
    common    :   'js/common'
}).use(['jquery','layer','common','form','laydate'],function () {
    //  Jquery插件
    var $ = layui.jquery;
    //  弹窗插件
    var layer = layui.layer;
    //  引入表单插件
    var form = layui.form;
    //  引入公共模块
    var common = layui.common;

    var base64Array = null;
    var result = null;

    var laydate = layui.laydate;


    var $node  = {
        imageUri : $('#image_uri'),
        faceCode : $('#face_code'),

        //是否已更新
        isFaceUpData : false,
        isDateUpData : false,

        //原始结束时间
        initialTime : $('#end_date').val()
    };

    //日期时间范围
    laydate.render({
        elem: '#face_date'
        ,type: 'date'
        ,range: true
        ,trigger:'click'
        ,min: 0 //最小日期为当天
        ,done: function(value, date, endDate){
            var dateArray = value.split(" - ");
            $("#begin_date").val(dateArray[0] + ' 00:00:00');
            $("#end_date").val(dateArray[1] + ' 23:59:59');
            //时间改变
            $node.isDateUpData = true;
        }
    });
    //  表单校验
    layui.form.verify({
        required4img: function(value, item){
            if (!value){
                return "请采集或上传人脸信息!";
            }
        }
    });

    //监听人脸设置保存按钮，只保存人脸
    form.on('submit(save_button)', function(data){
        //1、图片到服务器
        result = savephotoFn();
        if(result != null){
            data.field.imageUri = result.fullPath;
            data.field.faceCode = result.md5;
        }else{
            //上传图片失败
            if(base64Array!=null){
                return;
            }
        }
        common.sendAsyncRequest("/estate/access/simpleAddOrUpdateUserFaceImage",'POST',data.field,callbackFn);
    });

    //监听人脸设置保存并下发按钮，自动下发到无需另外特殊授权的设备上，即通用下发
    form.on('submit(save_push_button)', function(data){
        common.timer($('button[lay-filter="save_push_button"]'));
        if($('#faceEnable').val() == 2){
            return;
        }
        //1、图片到服务器
        result = savephotoFn();
        if(result != null){
            data.field.imageUri = result.fullPath;
            data.field.faceCode = result.md5;
            //保存数据到页面
            $node.imageUri.val(result.fullPath);
            $node.faceCode.val(result.md5);
            //保存图片成功后更改修改和更新的状态
            $node.isFaceUpData = false;
            $node.isDateUpData = false;
        }else{
            //上传图片失败
            if(base64Array!=null){
                return;
            }
            if(data.field.imageUri == '' && data.field.faceCode == ''){
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
                return;
            }
        }
        data.field.deviceAccessType = 10; //下发人脸到通用位置的设备上
        common.sendAsyncRequest("/estate/access/addOrUpdateUserFaceImage",'POST',data.field,function (result) {
            if(result.data){
                layer.msg("保存成功",{
                    time: 500,
                    shade : [0.1 , '#000' , true]
                }, function () {
                    //获取当前弹窗出层的名字
                    var index = parent.layer.getFrameIndex(window.name);
                    //关闭弹窗层
                    parent.layer.close(index);
                    // 父页面刷新
                    parent.location.reload();
                });
            }else {//添加失败
                layer.msg("保存失败");
            }
        });
    });

    //回调函数
    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();
        });
    };

    //图片到服务器
    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") {//上传成功
                    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;
    };


    //启用按钮
    form.on('submit(enable_btn)', function(data){
        //如果imageUri或者faceCode为空，则提示上传图片再启用。
        if (data.field.imageUri == null || data.field.imageUri == '' || data.field.faceCode == null || data.field.faceCode == ''){
            layer.msg("请先上传图片并保存后再点击启用");
            return
        }
        //如果更新过没有保存则提示保存
        if ($node.isFaceUpData || $node.isDateUpData){
            layer.msg("请先保存后再点击启用");
            return
        }
        var devicesAccessPushVO = {
            operType : 3,
            userId : data.field.id
        };
        common.sendAsyncRequest('/estate/access/accessDevicesManualPush','POST',devicesAccessPushVO,callbackFn);
    });

    //延期按钮
    form.on('submit(extension_button)',function (data) {
        layer.open({
            title: '选择日期',
            type: 1,
            icon: 3,
            offset: '100px',
            trigger: 'click',
            area: ['400px', '270px'],
            content: '' +
                '<div class="layui-inline" style="width: 100%;">' +
                '      <div class="layui-input-inline" style="width: 100%;height: 120px;display: flex;' +
                'align-items: center;justify-content: center;font-size: 15px">' +
                '        <span>请选择结束时间</span>' +
                '        <input type="text" class="layui-input" name="extension" id="extension" ' +
                'style="width: 300px;left: 50px;padding:0px;font-size: 18px;position: absolute;top:80px;text-align: center;">' +
                '      </div>' +
                '    </div>',
            btn:['确定','取消'],
            success:function(layero, index) {
                laydate.render({
                    elem:"#extension",
                    type: 'date',
                    min: $node.initialTime,
                    isInitValue:true,
                    value: $node.initialTime.split(' ')[0]
                }) ;
            },
            yes: function(index) {
                let extensionDate = $("input[name='extension']").val();
                if (extensionDate == "" || extensionDate == "undefined" || extensionDate == null) {
                    layer.close(index);
                } else {
                    $('#end_date').val(extensionDate + ' 23:59:59');
                    $('#face_date').val($("#begin_date").val() + ' - ' + extensionDate);
                    $('#face_save_btn').click();
                    layer.close(index);
                    layer.msg("有效期-结束日期已设置至" + extensionDate);
                }
            },
            btn2: function(index){
                layer.close(index);
            }

        });
    });

    //延期按钮禁用
    function intiExtension(){
        let faceDate = $('#face_date').val();
        if (faceDate == null || faceDate == '' || faceDate == undefined){}else {
            $('#face_date').attr("disabled",true).addClass("disabled");
        }
        var img = $node.imageUri.val();
        if (img == null || img == '' || img == undefined){
            $('#extension_button').addClass("layui-btn-disabled").attr("disabled",true);
        }
    }


    //人脸采集
    var initWebcamFn = function () {
        var pos = 0, ctx = null, saveCB, image = [];
        var canvas =  document.getElementById('canvas');
        canvas.setAttribute('width', 320);
        canvas.setAttribute('height', 240);
        //IE8以上及主流浏览器
        if (canvas.toDataURL) {
            //设置画布为2d
            ctx = canvas.getContext("2d");
            //截图320*240，即整个画布作为有效区
            image = ctx.getImageData(0, 0, 320, 240);
            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("请升级或者更换浏览器后再操作");
        }
        $("#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);
            }
        })
    };

    //上传图片
    $('#photo_upload').on("click",function(){
        var length = $('.picture-img-list').length;
        if(base64Array != null || length >= 1){
            layer.msg("每位住户最多设置1张图片，请先删除再操作");
            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("每位住户最多设置1张图片，请先删除后再操作");
                return;
            }
            for(var i = 0;i<files.length;i++){
                var img = files[i];
                if(!/^(\s|\S)+(jpg|jpeg|gif|png|PNG|JPEG|GIF|PNG)+$/.test(img.name)){
                    document.getElementById("btn_file").outerHTML = document.getElementById("btn_file").outerHTML;
                    layer.msg("图片类型必须是png/gif/jpeg/jpg格式");
                    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;
    });

    //图片预览
    var imageShowFn = function(url){
        var dom = $(['' +
        '<div class="picture-img-list">'+
        '<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>'+
        '</div>'].join(''));

        //点击删除预览图片
        dom.find('.layui-layer-close').on('click',function () {
            $(this).closest('.picture-img-list').remove();
            $('#tips').show();
            base64Array = null;
        });
        base64Array = url;
        $('#tips').hide();
        $('#tips').after(dom);
        //已更新
        $node.isFaceUpData = true;
    };

    //点击调用摄像头
    $('#photo_webcam').on("click",function(){
        $("#default_img").hide();
        $('#photo_webcam').hide();
        initWebcamFn();
        $('#photo_graph').show();
    });

    //点击拍照
    $('#photo_graph').on("click",function(){
        var length = $('.picture-img-list').length;
        if(base64Array != null || length >= 1){
            layer.msg("每位住户最多设置1张图片，请先删除再操作");
            return;
        }
        webcam.capture();
    });

    //删除图片
    $('.layui-layer-close').on('click',function () {
        $(this).closest('.picture-img-list').remove();
        $('#tips').show();
        base64Array = null;
        document.getElementById("btn_file").outerHTML = document.getElementById("btn_file").outerHTML;
        $node.faceCode.val(null);
        $node.imageUri.val(null);
        //已更新
        $node.isUpData = true;
    });

    var initDateFn = function () {
        var beginDate = $("#begin_date").val();
        var endDate =  $("#end_date").val();
        if(beginDate && endDate){
            $("#face_date").val(beginDate.split(' ')[0] + " - " + endDate.split(' ')[0]);
        }
    };
    function intiInputFn(){
        var faceEnable = $('#faceEnable').val();
        if (faceEnable && faceEnable == 2){
            $('#face_date').attr("disabled",true);
            $('#face_date').addClass("disabled");
            $('#face_save_btn').addClass("layui-btn-disabled");
            $('#face_save_btn').addClass("disabled");
        }
    }
    //  初始化
    (function () {
        initDateFn();
        intiInputFn();
        intiExtension();
    })();
});
