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 laydate = layui.laydate;

    var isCardNoExist = false;

    var $node  = {
        //是否已更新
        isCardUpData : false,
        isDateUpData : false,
        residentialIdInput : $('input[name="residentialId"]'),

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

    //日期时间范围
    laydate.render({
        elem: '#card_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({
        uniquecardNo: function(value, item){
            if(isCardNoExist){
                return "卡号已存在!";
            }
        }
    });

    //监听按钮
    //监听按钮，保存卡设置的同时下发卡到设备上
    form.on('submit(submit_button)', function(data){
        var cardNo = $("#card_no").val();
        if(cardNo != null && cardNo != ''){
           var beginDate  =  $("#begin_date").val();
           var endDate =  $("#end_date").val();
          if(beginDate == null || beginDate ==''|| endDate == null || endDate ==''){
             layer.msg("请输入门禁卡有效期！");
             return;
          }
        }
        common.sendAsyncRequest("/estate/access/addOrUpdateUserCard",'POST',data.field,callbackFn);
    });


    //监听卡设置保存按钮，只保存卡设置
    form.on('submit(save_button)', function(data){
        var cardNo = $("#card_no").val();
        if(cardNo != null && cardNo != ''){
            var beginDate  =  $("#begin_date").val();
            var endDate =  $("#end_date").val();
            if(beginDate == null || beginDate ==''|| endDate == null || endDate ==''){
                layer.msg("请输入门禁卡有效期！");
                return;
            }
        }
        common.sendAsyncRequest("/estate/access/simpleAddOrUpdateUserCard",'POST',data.field,callbackFn);
    });

    //监听按钮
    //监听按钮，保存卡设置的同时下发卡到设备上
    form.on('submit(save_push_button)', function(data){
        common.timer($('button[lay-filter="save_push_button"]'));
        if($('#cardEnable').val() == 2){
            return;
        }
        var cardNo = $("#card_no").val();
        if(cardNo != null && cardNo != ''){
            var beginDate  =  $("#begin_date").val();
            var endDate =  $("#end_date").val();
            if(beginDate == null || beginDate ==''|| endDate == null || endDate ==''){
                layer.msg("请输入门禁卡有效期！");
                return;
            }
        }
        data.field.deviceAccessType = 10; //下发门禁卡到通用位置的设备上
        common.sendAsyncRequest("/estate/access/addOrUpdateUserCard",'POST',data.field,callbackFn);
        // var cardNo = $("#card_no").val();
        // //保存现在的卡号到初始卡号--用于判断是否修改
        // $('#init_card_no').val(cardNo);
        // if(cardNo != null && cardNo != ''){
        //     var beginDate  =  $("#begin_date").val();
        //     var endDate =  $("#end_date").val();
        //     if(beginDate == null || beginDate ==''|| endDate == null || endDate ==''){
        //         layer.msg("请输入门禁卡有效期！");
        //         return;
        //     }
        // }
        // data.field.deviceAccessType = 10; //下发门禁卡到通用位置的设备上
        // common.sendAsyncRequest("/estate/access/addOrUpdateUserCard",'POST',data.field,function (result) {
        //     if(result.data){
        //         layer.msg("保存成功",{
        //             time: 500,
        //             shade : [0.1 , '#000' , true]
        //         });
        //     }else {//添加失败
        //         layer.msg("保存失败");
        //     }
        // });
    });

    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]
                    // value:$node.initialTime,
                }) ;
            },
            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');
                    $('#card_date').val($("#begin_date").val().split(' ')[0] + ' - ' + extensionDate);
                    $('#card_save_btn').click();
                    layer.close(index);
                    layer.msg("有效期-结束日期已设置至" + extensionDate);
                }
            },
            btn2: function(index){
                layer.close(index);
            }

        });
    });

    //监听卡禁用按钮
    form.on('submit(disable_button)', function(data){
        if(data.field.cardEnable == 2){
            layer.msg("门禁卡已被被禁用，请勿重复操作");
        }else{
            layer.confirm('确定要禁用该住户的门禁卡功能吗？',{icon: 7, title:'提示'}, function(index) {
                var cId = data.field.id;
                var body = {};
                body.cardId = cId;
                body.enable = false;
                $.ajax({
                    url : '/estate/access/sendUserCard',
                    type : 'POST',
                    contentType: "application/json;charset=utf-8",
                    data : JSON.stringify(body)
                }).then(function (result) {
                    callbackFn(result)
                });
            });
        }
    });

    //回调函数
    function callbackFn(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("设置失败");
        }
    };

    //卡下发按钮
    form.on('submit(enable_btn)', function(data){
        if ($('#card_no').val() != $('#init_card_no').val()){
            layer.msg("您更换的门禁卡，请先保存后再点击下发");
            return
        }
        var devicesAccessPushVO = {
            operType : 4,
            userId : data.field.userId
        };
        common.sendAsyncRequest('/estate/access/accessDevicesManualPush','POST',devicesAccessPushVO,callbackFn);
    });

    //卡删除按钮
    form.on('submit(delete_btn)', function(data){
        if ($('#card_no').val() != $('#init_card_no').val()){
            layer.msg("只能删除原有的门禁卡");
            return
        }else{
            layer.confirm('确定要删除该住户的门禁卡权限吗？',{icon: 7, title:'提示'}, function(index) {
                var devicesAccessPushVO = {
                    operType : 5,
                    userId : data.field.userId
                };
                common.sendAsyncRequest('/estate/access/accessDevicesManualPush','POST',devicesAccessPushVO,callbackFn);
            });
        }
    });


    var initDateFn = function () {
        var beginDate = $("#begin_date").val();
        var endDate =  $("#end_date").val();
        if(beginDate && endDate){
            $("#card_date").val(beginDate.split(' ')[0] + " - " + endDate.split(' ')[0]);
        }
    };


    //失焦事件提前判断，解决校验异步结果还没返回就执行提交方法的问题
    //失焦事件，根据序列号获取设备信息，来判断设备是否已存在
    $('input[name="cardNo"]').on("blur", function(){
        var value = this.value;
        var id = $('#id').val();
        if (!value){
            return;
        }
        $.ajax({
            url     :   '/estate/accessCard/getAccessCardByCardNo',
            data    :   {cardNo : value,
                        residentialId : $node.residentialIdInput.val()
                        },
            type    :   'GET',
            success :   function (result) {
                if (result.code === '200'){
                    if (result.data && result.data.id != id){
                        // return "卡号已存在!";
                        isCardNoExist = true;
                    }else{
                        isCardNoExist = false;
                    }
                } else {
                    layer.alert(result.msg);
                }
            }
        });
    });

    function intiInput(){
        var cardEable = $('#cardEnable').val();
        if (cardEable && cardEable == 2){
            $('#card_no').attr("disabled",true).addClass("disabled");
            $('#card_date').attr("disabled",true).addClass("disabled");
            $('#card_save_btn').addClass("layui-btn-disabled").attr("disabled",true);
            $('#extension_button').addClass("layui-btn-disabled").attr("disabled",true);
        }
    }
    function intiExtension(){
        let cardDate = $('#card_date').val();
        if (cardDate == null || cardDate == '' || cardDate == undefined){}else {
            $('#card_date').attr("disabled",true).addClass("disabled");
        }
        var cardNo = $('#card_no').val();
        if (cardNo == null || cardNo == '' || cardNo == undefined){
            $('#extension_button').addClass("layui-btn-disabled").attr("disabled",true);
        }
    }

    //  初始化
    (function () {
        //  加载所属房间
        initDateFn();
        intiInput();
        intiExtension();
    })();

});





