/**
 * 添加bootstrapValidator校验
 */
$(function () {
    $("form[name=cell_edit_form]").bootstrapValidator({
        message: 'This value is not valid',
        excluded: [':disabled'],
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            'communityName': {
                validators: {
                    notEmpty: {
                        message: '小区不能为空'
                    }
                }
            },
            'buildName': {
                validators: {
                    notEmpty: {
                        message: '楼栋不能为空'
                    }
                }
            },
            'num': {
                validators: {
                    notEmpty: {
                        message: '门牌不能为空'
                    }
                },
                regexp: {
                    regexp: /^\d{4}$/i,
                    message: '门牌只能为四位数字'
                }
            },
            'callphone': {
                validators: {
                    regexp: {

                        regexp: /(^(0\d{2,3})?-?[1-9]\d{6,7}$)|(^(\d{2})?1[3-9]\d{9}$)|(^([5|6|8|9])\d{7}$)/,
                        message: '请输入正确的呼叫号码'
                    }
                }
            },
            'address': {
                validators: {
                    notEmpty: {
                        message: '地址不能为空'
                    },
                    regexp: {
                        regexp: getUtfRegexp(),
                        message: '含有非法字符'
                    }
                }
            },
            'name': {
                validators: {
                    notEmpty: {
                        message: '房间名不能为空'
                    },
                    regexp: {
                        regexp: getUtfRegexp(),
                        message: '含有非法字符'
                    }
                }
            }
        }
    });
});

$(function () {

    /*打开楼栋回填列表*/
    // $('#buildName').click(function () {
    //     var communityId = $('#communityId').val();
    //     if (communityId == null || communityId.length <= 0) {
    //         alert("请先选择小区");
    //         return;
    //     }
    //     var data = {"communityId": communityId};
    //     buildList.data = data;
    //     buildList.popBuildList(data);
    //     buildList.backfillFun = function (data) {
    //         $('#buildId').val(data.id);
    //         $('#buildName').val(data.name);
    //         revalidate('buildName');
    //         autocompleteAdr(data.id);
    //     }
    // });
    /**
     * 小区下拉框选中事件,当hidden域name=cell_edit_form的input控件value发生变化时
     */
    $('#communityId').on('change', function () {
        $('#buildId').val("");
        $('#buildName').val("");
        revalidate('buildName');
    });
    /**
     * 点击关闭按钮，关闭当前弹出窗口
     */
    $('#btn_cancel').click(function () {
        closeWin('cell_edit_div');
    });
    /**
     * 点击表单ok按钮
     */
    $('#btn_ok').click(function () {
        if ($("#userListBody").find(".saveUserClass").length > 0) {
            myAlert("请先保存正在编辑中的住户");
            return;
        }
        $("form[name=cell_edit_form]").bootstrapValidator('validate');
        var valid = $("form[name=cell_edit_form]").data('bootstrapValidator').isValid();
        if (!valid) {
            return;
        }
        var data = {};
        data.id = $("#cellId").val();
        data.name = $("#cellName").val();
        data.num = $("#cellNum").val();
        data.address = $("#address").val();
        data.callphone = $("#callPhone").val();
        data.buildId = $("#buildId").val();
        data.buildName = $("#buildName").val();
        doDataPost(data, false, ctx + "/adm/cell/upd", function (json) {
            if (json.code == 0) {
                closeWin('cell_edit_div');
                openTipLayer(json.msg);
            } else {
                myAlert(json.msg);
            }
        });
    });

    /**
     * 根据楼栋ID补全房间地址
     */
    function autocompleteAdr(buildId) {
        if (buildId == null || buildId.length <= 0) {
            return;
        }
        var data = {};
        data.buildId = buildId;
        doDataPost(data, false, ctx + "/adm/build/model/data", function (json) {
            var adr = json.data.address;
            var buildName = json.data.name;
            var cellNum = $("form[name=cell_edit_form] :input[name$=num]").val();
            $('form[name=cell_edit_form] :input[name$=address]').val(adr);
            autocompleteName(buildName, cellNum);
        });
    }

    $("form[name=cell_edit_form] :input[name$=num]").on('keyup', function () {
        var num = $(this).val();
        var buildName = $('#buildName').val();
        autocompleteName(buildName, num);
    });

    /**
     * 根据楼栋名称+房间编号回填房间名
     */
    function autocompleteName(buildName, cellNum) {
        if (buildName == "请选择楼栋") {
            buildName = "";
        }
        var cellName = buildName + "-" + cellNum;
        $('form[name=cell_edit_form] :input[name$=name]').val(cellName);
        revalidate('name');
        revalidate('address');
    }

    /**
     * 需要重新验证数据
     */
    function revalidate(field) {
        //程序回填域需要调用如下函数通知bootstrapValidator校验框架
        $('form[name=cell_edit_form]').data('bootstrapValidator').updateStatus(field, 'NOT_VALIDATED', null).validateField(field);
    }

    /**
     * 判断所选是否是上海智能安防小区
     */
    function checkShanghaiSmartSecurity() {
        var communityId=$('#communityId').val();
        if(communityId==null || communityId.length<=0){
            alert("请先选择小区");
            return;
        }
        var data = {"communityId":communityId};
        $.ajax({
            type:"POST",
            url:ctx +"community/checkShSmartSecurity",
            data:data,
            success:function(json){
                //是否是 上海智能安防小区的标志
                var flag = json.data;
                showShanghaiCellCode(flag);
            }
        });
    }

    /**
     * 上海智能安防房间编号
     */
    function showShanghaiCellCode(flag){
        //显示
        if(flag==1) {
            $("#smark_security_code_div").css("display", "block");
            //添加验证
            $("form[name=cell_add_from]").data('bootstrapValidator').enableFieldValidators('smartCellCode',true);
            revalidate('smartCellCode');
        }
        //隐藏
        else if(flag==0) {
            $("#smark_security_code_div").css("display", "none");
            //取消验证
            $("form[name=cell_add_from]").data('bootstrapValidator').enableFieldValidators('smartCellCode',false);
            // $("form[name=cell_add_from]").bootstrapValidator('removeField','smartCellCode');
            revalidate('smartCellCode');
        }
    }
    var smartCellCode = $("#smarkSecurityCode").val();
    if(smartCellCode!=="")
        $("#smark_security_code_div").css("display", "block");

    /**
     * ----------------住户列表table的相关方法----------------
     */
    resizeTable();
    adjustTableCellWidth('userCellListDiv');

    /**
     * 全选住户
     */
    $('#selectAll').click(function () {
        if (this.checked) {
            $("input[name='userId']:checkbox").each(function () {
                $(this).prop("checked", true);
            })
        } else {
            $("input[name='userId']:checkbox").each(function () {
                $(this).prop("checked", false);
            })
        }
    });

    /**
     * 获取滚动pane
     */
    var pane = $('#scrollDiv');
    pane.jScrollPane(
        {
            animateScroll: true
        }
    );
    var api = pane.data('jsp');

    /**
     * 点击增加按钮
     */
    $('#add_user_btn').click(function () {
        if ($("#userListBody").find(".saveUserClass").length > 0) {
            myAlert("请先保存正在编辑中的住户");
            return;
        }
        var str = '<tr>' +
            '<td>' +
            '<input type="checkbox" name="userId" value="" />' +
            '<input type="hidden" name="types" value="" />' +
            '<input type="hidden" name="cellId" value="" />' +
            '</td>' +
            '<td style="max-width: 200px;">' +
            '<input style="max-width: 70px;" type="text" name="userName" value="" />' +
            '</td>' +
            '<td>' +
            '<select id="userTypeSelect" style="height:22px;width:70px;">' +
            '<option value="MASTER">户主</option>' +
            '<option value="MEMBER" selected="selected">成员</option>' +
            '<option value="TENANT">租客</option>' +
            '</select>' +
            '</td>' +
            '<td>' +
            '<input style="max-width: 85px;" type="text" name="userPhone" value="" />' +
            '</td>' +
            // '<td>' +
            // '<a href="#" class="btn_not_auth" <!--onclick="addAuthThis(this)-->">未认证</a>' +
            // '</td>' +
            '<td>' +
            '<a style="cursor: pointer;" class = "saveUserClass">保存</a>' +
            '</td>' +
            // '<td>' +
            // // '<a style="cursor: pointer;" onclick="updMsgCheckThis(this)">验证短信&nbsp;&nbsp;</a>' +
            // // '<a style="cursor: pointer;" onclick="pswInitThis(this)">还原登录密码&nbsp;&nbsp;</a>' +
            // // '<a style="cursor: pointer;" onclick="openPswInitThis(this)">还原开锁密码</a>' +
            // '</td>' +
            '</tr>';
        var tr = $(str);
        $("#userListBody").append(tr);
        resizeTable();
        adjustTableCellWidth('userCellListDiv');
        api.scrollToBottom();
    });

    /**
     * 点击删除按钮
     */
    $('#remove_user_btn').click(function () {
        if ($("#userListBody").find(".saveUserClass").length > 0) {
            myAlert("请先保存正在编辑中的住户");
            return;
        }
        var x = ($(window).width() - 260 + $('div.viewFramework-sidebar').width()) / 2;
        var y = ($(window).height() / 2 - 73);
        if (!chosenTrs()) {
            layer.alert('请选择数据', {
                icon: 0,
                title: '提示',
                area: ['260px', '146px'],
                offset: [y + 'px', x + 'px']
            });
            return;
        }
        var data = chosenIds();
        layer.confirm('确定要删除？', {
            icon: 3,
            title: '提示',
            btn: ['确定', '取消'],
            area: ['260px', '146px'],
            offset: [y + 'px', x + 'px']
        }, function (index) {
            doDataPost({houseProperty: JSON.stringify(data)}, false, ctx + "/adm/user/cell/del", function (json) {
                if (json.code == 0) {
                    $('form[name=cell_edit_form] table > tbody > tr > td > input[type=checkbox]').each(function () {
                        var input = $(this);
                        if (input.is(':checked')) {
                            input.parent().parent().remove();
                        }
                    });
                    resizeTable();
                    adjustTableCellWidth('userCellListDiv');
                }
                myAlert(json.msg);
            });
            layer.close(index);
        });
    });

    /**
     * 获取选中的数据
     */
    function chosenIds() {
        var result_data = [];
        $('form[name=cell_edit_form] table > tbody > tr > td > input[type=checkbox]').each(function () {
            var input = $(this);
            if (input.is(':checked')) {
                if (input.val() != "") {
                    var userType = $(input).parent().find('input[type=hidden][name=types]').val();
                    var cellId = $(input).parent().find('input[type=hidden][name=cellId]').val();
                    var data_temp = {cellId: cellId, userId: input.val(), userType: userType};
                    result_data.push(data_temp);
                }
            }
        });
        return result_data;
    }

    /**
     * 是否勾选了删除数据
     */
    function chosenTrs() {
        var checkedData = false;
        $('form[name=cell_edit_form] table > tbody > tr > td > input[type=checkbox]').each(function () {
            var input = $(this);
            if (input.is(':checked')) {
                checkedData = true;
            }
        });
        return checkedData;
    }

    /**
     * 编辑行元素
     */
    $("#userListBody").on("click", ".editUserClass", function () {
        if ($("#userListBody").find(".saveUserClass").length > 0) {
            myAlert("请先保存正在编辑中的住户");
            return;
        }
        var tds = $(this).parent("td").siblings();

        var userName = tds.eq(1).html();
        tds.eq(1).html("<input style='max-width: 70px;' type='text' name='userName' value='" + userName + "'/>");

        var userCellType = tds.eq(2).html();
        var str = "<select id='userTypeSelect' style='height:23px;width:70px;' >";
        if (userCellType === "户主") {
            str += "<option value='MASTER' selected='selected'>" + '户主';
        } else {
            str += "<option value='MASTER'>" + '户主';
        }
        if (userCellType === "成员") {
            str += "<option value='MEMBER' selected='selected'>" + '成员';
        } else {
            str += "<option value='MEMBER'>" + '成员';
        }
        if (userCellType === "租客") {
            str += "<option value='TENANT' selected='selected'>" + '租客';
        } else {
            str += "<option value='TENANT'>" + '租客';
        }
        str += "</select>";
        tds.eq(2).html(str);

        var userPhone = tds.eq(3).html();
        tds.eq(3).html("<input style='max-width: 85px;' type='text' name='userPhone' value='" + userPhone + "'/>");
        $(this).parent("td").html("<a style='cursor: pointer;' class='saveUserClass'>保存</a>");
    });

    /**
     * 保存行元素
     */
    $("#userListBody").on("click", ".saveUserClass", function () {
        var td = $(this).parent("td");
        var tds = $(this).parent("td").siblings();
        var cellId = $("#cellId").val();
        var userId = tds.eq(0).find("[name='userId']").val();
        var userName = $("input[name='userName']").val();
        var userCellType = $("#userTypeSelect").val();
        var userPhone = $("input[name='userPhone']").val();
        var data = {
            "cellId": cellId,
            "id": userId,
            "name": userName,
            "userCellType": userCellType,
            "loginphone": userPhone
        };

        var types = 0;
        if (userCellType === "MASTER") {
            userCellType = "户主";
            types = 1;
        } else if (userCellType === "MEMBER") {
            userCellType = "成员";
            types = 2;
        } else if (userCellType === "TENANT") {
            userCellType = "租客";
            types = 3;
        }

        doDataPost(data, false, ctx + "/adm/user/add/upd", function (repJson) {
            myAlert(repJson.msg);
            if (repJson.code == 0) {
                if (userId == "") {
                    userId = repJson.data;
                    tds.eq(0).find("input[name='userId']").val(userId);
                    tds.eq(0).find("input[name='cellId']").val(cellId);
                }
                tds.eq(0).find("input[name='types']").val(types);
                tds.eq(1).html($("input[name='userName']").val());
                tds.eq(2).html(userCellType);
                tds.eq(3).html($("input[name='userPhone']").val());
                td.html("<a style='cursor: pointer;' class='editUserClass'>编辑住户信息</a>");
            }
        });
    });
});

/**
 * 进入实名认证页面
 * @param userId
 */
function addAuth(userId) {
    var data = {'userId': userId,"cellId":$("#cellId").val()};
//    $("div.popup_window").remove();
    $.ajax({
        type: "POST",
        url: ctx + "/adm/auth/add/form_ui",
        data: data,
        success: function (htmlText) {
            $("div.popup_window").remove();
            addForm(htmlText);
            openWin('auth_add_div');
        }
    });
}

function addAuthThis(obj) {
    if(obj==undefined || obj==""){
        return;
    }
    var userId=$(obj).parent().parent().find("input[name='userId']").val();
    if(userId!=""){
        addAuth(userId);
    }

}

function pswInitThis(obj) {
    if(obj==undefined || obj==""){
        return;
    }
    var userId=$(obj).parent().parent().find("input[name='userId']").val();
    if(userId!=""){
        pswInit(userId);
    }
}

function openPswInitThis(obj) {
    if(obj==undefined || obj==""){
        return;
    }
    var userId=$(obj).parent().parent().find("input[name='userId']").val();
    if(userId!=""){
        openPswInit(userId);
    }
}

/**
 * 进入认证信息页面
 * @param userId
 */
function viewAuth(userId) {

    var data = {'userId': userId,"cellId":$("#cellId").val()};
    $.ajax({
        type: "POST",
        url: ctx + "/adm/auth/view/form_ui",
        data: data,
        success: function (htmlText) {
            $("div.popup_window").remove();
            addForm(htmlText);
            openWin('auth_view_div');
        }
    });
}

/**
 * 还原住户登录密码
 * userId [用户的id]
 */
function pswInit(userId) {
    var x = ($(window).width() - 260 + $('div.viewFramework-sidebar').width()) / 2;
    var y = ($(window).height() / 2 - 73);
    layer.confirm('确定要还原登录密码？', {
        icon: 3,
        title: '提示',
        btn: ['确定', '取消'],
        area: ['260px', '146px']
    }, function (index) {
        var data = {"userId": userId};
        doDataPost(data, false, ctx + "/adm/user/pswinit", function (json) {
            //var json=$.parseJSON(repJson);
            layer.alert(json.msg, {
                title: '提示',
                area: ['300px', '170px'],
                offset: [y + 'px', x + 'px']
            });
        });
        layer.close(index);
    })
}

/**
 * 还原住户开锁密码
 * userId [用户的id]
 */
function openPswInit(userId) {
    var x = ($(window).width() - 260 + $('div.viewFramework-sidebar').width()) / 2;
    var y = ($(window).height() / 2 - 73);
    layer.confirm('确定要还原开锁密码？', {
        icon: 3,
        title: '提示',
        btn: ['确定', '取消'],
        area: ['260px', '146px']
    }, function (index) {
        var data = {"userId": userId};
        doDataPost(data, false, ctx + "/adm/user/openpswinit", function (json) {
            //var json=$.parseJSON(repJson);
            layer.alert(json.msg, {
                title: '提示',
                area: ['300px', '170px'],
                offset: [y + 'px', x + 'px']
            });
        });
        layer.close(index);
    })
}

/**
 * 修改短信验证
 * userId [用户的id]
 */
function updMsgCheck(userId) {
    var x = ($(window).width() - 260 + $('div.viewFramework-sidebar').width()) / 2;
    var y = ($(window).height() / 2 - 73);
    layer.confirm('确定要修改短信验证？', {
        icon: 3,
        title: '提示',
        btn: ['确定', '取消'],
        area: ['260px', '146px']
    }, function (index) {
        var data = {"userId": userId};
        doDataPost(data, false, ctx + "/adm/user/updMsgCheck", function (json) {
            //var json=$.parseJSON(repJson);
            layer.alert(json.msg, {
                title: '提示',
                area: ['300px', '170px'],
                offset: [y + 'px', x + 'px']
            });
            if(json.code==0){//验证短信成功
                $(".msgCheck_"+userId).remove();
            }
        });
        layer.close(index);
    })
}
function updMsgCheckThis(obj) {
    if(obj==undefined || obj==""){
        return;
    }
    var userId=$(obj).parent().parent().find("input[name='userId']").val();
    if(userId!=""){
        $(obj).addClass("msgCheck_"+userId);
        updMsgCheck(userId);
    }
}
