layui.extend({
    common: 'js/common',
    dropdown: 'layui/lay/modules/dropdown',
    region: 'layui/lay/mymodules/region',
    xmSelect: 'layui/dist/xm-select'
}).use(['table', 'jquery', 'layer', 'common', 'form', 'dropdown', 'region', 'xmSelect'], function () {
    //  弹窗插件
    var layer = layui.layer;
    //  Jquery插件
    var $ = layui.jquery;
    //  引入公共模块
    var common = layui.common;
    //  引入表格
    var table = layui.table;
    //引入表单
    var form = layui.form;

    // 查询框表单
    var $node = {
        //  省市区表单
        provinceInput: $('input[name="regionProvince"]'),

        cityInput: $('input[name="regionCity"]'),

        areaInput: $('input[name="regionArea"]'),

        regionInput: $('#region'),

    };
    //  页面数据
    var pageData = {
        residentialId   :   $('#residentialId').val()
    };

    //选中id集合
    var ids = [];
    //清空选中集合
    var clearCheckbox = function () {
        ids = [];
    }
    //tableId集合
    var table_data = [];

    /**
     * 查询加载
     */
    var queryTableFn = function (obj) {
        var params = {
            name: $("input[name='name']").val(),
            tel: $("input[name='tel']").val(),
            idCard: $("input[name='idCard']").val(),
            type: $("select[name='type']").val(),
            isEnable: $("select[name='isEnable']").val(),
            //卡号
            cardNo: $("input[name='cardNo']").val(),
        };
        //重新加载表格
        layuiTable.reload({
            where: {
                name: params.name,
                tel: params.tel,
                idCard: params.idCard,
                type: params.type,
                isEnable: params.isEnable,
                cardNo: params.cardNo,
                //排序
                sortField: obj ? obj.field : '',
                sortOrder: obj ? obj.type : '',
            }
            //重新从第1页开始
            , page: {
                curr: 1
            },
            initSort: obj
        });
    };

    var layuiTable = common.layuiTable.render(table, {
        elem: '#table-id'
        , url: '/estate/serverUser/showServerUserList?residentialId=' + pageData.residentialId
        , method: 'POST'//  接口http请求类型，默认：get
        , cellMinWidth: 80//全局定义常规单元格的最小宽度，
        , cols: [[
            {type: 'checkbox'}
            , {field: 'name', align: 'center', title: '姓名'}
            , {
                field: 'sex', align: 'center', title: '性别', sort: true, templet: function (d) {
                    var sexName = "";
                    var sex = d.sex;
                    if (sex == 0) {
                        sexName = "未定义";
                    } else if (sex == 1) {
                        sexName = "男";
                    } else if (sex == 2) {
                        sexName = "女";
                    }
                    return sexName;
                }
            }
            , {field: 'residentialName', title: '所属小区', align: 'center'}
            , {
                field: 'type', align: 'center', title: '人员类型', sort: true, templet: function (d) {
                    var typeName = "";
                    var type = d.type;
                    if (type == 0) {
                        typeName = "保安";
                    } else if (type == 1) {
                        typeName = "快递";
                    } else if (type == 2) {
                        typeName = "外卖";
                    } else if (type == 3) {
                        typeName = "清洁";
                    } else if (type == 4) {
                        typeName = "其他";
                    }
                    return typeName;
                }
            }
            , {
                title: '卡号', align: 'center', templet: function (d) {
                    if (d.accessCard) {
                        return d.accessCard.cardNo;
                    }
                    return "";
                }
            }
            , {field: 'serverUserFaceImage.imageUri', title: '人脸图片', templet: '#is_imageUri', align: 'center'}
            , {
                field: 'accessCard.beginDate', width: 82, title: '卡有效期-开始', align: 'center', templet: function (d) {
                    if (d.accessCard) {
                        return d.accessCard.beginDate
                    } else {
                        return ""
                    }
                }
            }
            , {
                field: 'accessCard.endDate', width: 82, title: '卡有效期-结束', align: 'center', templet: function (d) {
                    if (d.accessCard) {
                        return d.accessCard.endDate
                    } else {
                        return ""
                    }
                }
            }
            , {
                field: 'serverUserFaceImage.beginDate',
                width: 90,
                title: '人脸有效期-开始',
                align: 'center',
                templet: function (d) {
                    if (d.serverUserFaceImage) {
                        return d.serverUserFaceImage.beginDate
                    } else {
                        return ""
                    }
                }
            }
            , {
                field: 'serverUserFaceImage.endDate',
                width: 90,
                title: '人脸有效期-结束',
                align: 'center',
                templet: function (d) {
                    if (d.serverUserFaceImage) {
                        return d.serverUserFaceImage.endDate
                    } else {
                        return ""
                    }
                }
            }
            , {field: 'tel', title: '联系方式', align: 'center'}
            , {field: 'idCard', title: '身份证', align: 'center'}
            , {field: 'isEnable', title: '状态', toolbar: '#switch_is_enable', align: 'center', sort: true}
            , {field: 'faceEnable', title: '人脸启用状态', templet: '#is_faceEnable', align: 'center', sort: true}
            , {
                title: '卡启用状态', align: 'center', templet: function (d) {
                    if (d.accessCard) {
                        if (d.accessCard.cardEnable == -1) {
                            return '<span class="layui-badge layui-bg-orange">未设置</span>';
                        } else if (d.accessCard.cardEnable == 0) {
                            return '<span class="layui-badge layui-bg-blue">待启用</span>';
                        } else if (d.accessCard.cardEnable == 1) {
                            return '<span class="layui-badge layui-bg-green">已启用</span>';
                        } else if (d.accessCard.cardEnable == 2) {
                            return '<span class="layui-badge layui-bg-red">已禁用</span>';
                        } else {
                            return "";
                        }
                    } else {
                        return '<span class="layui-badge layui-bg-black">待设置</span>';
                    }
                }
            }
            , {title: '操作', width: 180, align: 'center', toolbar: '#table-useradmin-webuser'}
        ]]
        //  开启分页功能
        , page: true
        , done: function (res, curr, count) {
            // 设置换页勾选之前的
            table_data = res.data;
            for (var i = 0; i < res.data.length; i++) {
                for (var j = 0; j < ids.length; j++) {
                    if (res.data[i].id == ids[j]) {
                        //这里才是真正的有效勾选
                        res.data[i]["LAY_CHECKED"] = 'true';
                        //找到对应数据改变勾选样式，呈现出选中效果
                        var index = res.data[i]['LAY_TABLE_INDEX'];
                        $('.layui-table tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                        $('.layui-table tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                    }
                }
            }
            //设置全选checkbox的选中状态，只有改变LAY_CHECKED的值， table.checkStatus才能抓取到选中的状态
            var checkStatus = table.checkStatus('table-id');
            if (checkStatus.isAll) {
                $(' .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                $('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
            }
            //图片放大
            layer.photos({
                photos: '#layPhotosTbImg',
                shade: .1,
                closeBtn: true
            });
        }
    });

    //排序
    layui.table.on('sort(table-id)', function (obj) {
        queryTableFn(obj);
    });

    //复选框选中监听,将选中的id 设置到缓存数组,或者删除缓存数组
    table.on('checkbox(table-id)', function (obj) {
        if (obj.checked == true) {
            if (obj.type == 'one') {
                ids.push(obj.data.id)
            } else {
                for (var i = 0; i < table_data.length; i++) {
                    ids.push(table_data[i].id);
                }
            }
        } else {
            if (obj.type == 'one') {
                for (var i = 0; i < ids.length; i++) {
                    if (ids[i] == obj.data.id) {
                        ids.splice(i, 1);
                        return;
                    }
                }
            } else {
                for (var i = 0; i < ids.length; i++) {
                    for (var j = 0; j < table_data.length; j++) {
                        if (ids[i] == table_data[j].id) {
                            ids.splice(i, 1);
                            i--;
                            break;
                        }
                    }
                }
            }
        }
    });

    //工具条事件 lay-filter="table-id"
    table.on('tool(table-id)', function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'edit':
                common.openDefaultIframe({
                    title: '修改服务人员',
                    content: '/estate/serverUser/findServerUserById/' + data.id //  打开内容
                });
                break;
            case 'delete':
                layer.confirm("是否确认删除？", {icon: 7, title: '提示'}, function () {
                    common.sendAsyncRequest("/estate/serverUser/deleteServerUser/" + data.id, 'POST', null, function (result) {
                        if (result.code == '200') {
                            if (result.data) {
                                layer.msg("删除成功", {
                                    time: 500
                                }, function () {
                                    // 父页面刷新
                                    location.reload();
                                });
                            } else {//删除失败
                                layer.msg("删除失败");
                            }
                        } else {//删除失败
                            layer.msg("删除失败");
                        }
                    });
                });
                break;
            case "enable":
                layer.confirm("是否确认修改？", function () {
                    //获得当前行 tr 的DOM对象
                    var $tr = obj.tr;
                    var $enable = $tr.find("a[lay-event='enable']");
                    var enabledVal = data.enabled;
                    var changeEnabledVal = enabledVal == 0 ? 1 : 0;
                    common.sendAsyncRequest("/estate/serverUser/updateEnabled", 'POST', {
                        id: data.id,
                        enabled: changeEnabledVal
                    }, function (result) {
                        if (result.code == '200') {
                            if (result.data) {
                                if (enabledVal == "0") {
                                    layer.msg("禁用成功");
                                    $enable.text("禁用");
                                } else {
                                    layer.msg("启用成功");
                                    $enable.text("启用");
                                } //同步更新缓存对应的值
                                obj.update({enabled: changeEnabledVal});
                            } else {//操作失败
                                layer.msg("操作失败");
                            }

                        } else {//删除失败
                            layer.msg("操作失败");
                        }
                    });
                });
                break;
            case "openPermission":
                common.openDefaultIframe({
                    title: '添加开门权限',
                    content: '/estate/serverUser/openPermission/' + data.name + '/' + data.id //  打开内容
                });
                break;
            case "specialOpenPermission":
                if (data.isEnable == 1) {
                    layer.msg("服务人员处于禁用操作状态，不能使用特殊开门权限");
                    break;
                }
                common.openMaxIframe({
                    title: '添加特殊开门权限',
                    content: '/estate/serverUser/specialOpenPermission/' + data.name + '/' + data.id //  打开内容
                });
                break;
            case 'disablePermission':
                layer.confirm('是否确认禁用?', {icon: 7, title: '提示'}, function (index) {
                    var devicesAccessPushVO = {};
                    devicesAccessPushVO.operType = 2;
                    devicesAccessPushVO.userId = data.id;
                    common.sendAsyncRequest('/estate/serverUser/accessDevicesManualPush', 'POST', devicesAccessPushVO, function (result) {
                        //刷新表格
                        layuiTable.reload();
                        layer.msg("禁用成功");
                        layer.close(index);//关闭弹窗提示
                    });
                });
                break;
            case 'faceEnable':
                layer.confirm('是否确认启用人脸?', {icon: 7, title: '提示'}, function (index) {
                    var devicesAccessPushVO = {};
                    devicesAccessPushVO.operType = 3;
                    devicesAccessPushVO.userId = data.id;
                    common.sendAsyncRequest('/estate/serverUser/accessDevicesManualPush', 'POST', devicesAccessPushVO, function (result) {
                        //刷新表格
                        layuiTable.reload();
                        layer.msg("启用成功");
                        layer.close(index);//关闭弹窗提示
                    });
                });
                break;
            case 'faceDisable':
                layer.confirm('是否确认禁用人脸?', {icon: 7, title: '提示'}, function (index) {
                    var devicesAccessPushVO = {};
                    devicesAccessPushVO.operType = 5;
                    devicesAccessPushVO.userId = data.id;
                    common.sendAsyncRequest('/estate/serverUser/accessDevicesManualPush', 'POST', devicesAccessPushVO, function (result) {
                        //刷新表格
                        layuiTable.reload();
                        layer.msg("禁用成功");
                        layer.close(index);//关闭弹窗提示
                    });
                });
                break;
            case 'cardEnable':
                layer.confirm('是否确认启用门禁卡?', {icon: 7, title: '提示'}, function (index) {
                    var devicesAccessPushVO = {};
                    devicesAccessPushVO.operType = 4;
                    devicesAccessPushVO.userId = data.id;
                    common.sendAsyncRequest('/estate/serverUser/accessDevicesManualPush', 'POST', devicesAccessPushVO, function (result) {
                        //刷新表格
                        layuiTable.reload();
                        layer.msg("启用成功");
                        layer.close(index);//关闭弹窗提示
                    });
                });
                break;
            case 'cardDisable':
                layer.confirm('是否确认禁用门禁卡?', {icon: 7, title: '提示'}, function (index) {
                    var devicesAccessPushVO = {};
                    devicesAccessPushVO.operType = 6;
                    devicesAccessPushVO.userId = data.id;
                    common.sendAsyncRequest('/estate/serverUser/accessDevicesManualPush', 'POST', devicesAccessPushVO, function (result) {
                        //刷新表格
                        layuiTable.reload();
                        layer.msg("禁用成功");
                        layer.close(index);//关闭弹窗提示
                    });
                });
                break;
            case 'deleteCard':
                layer.confirm('是否确认禁用门禁卡?', {icon: 7, title: '提示'}, function (index) {
                    common.sendAsyncRequest('/estate/serverUser/deleteCard/' + data.id, 'GET', "", function (result) {
                        //刷新表格
                        layuiTable.reload();
                        layer.msg("禁用成功");
                        layer.close(index);//关闭弹窗提示
                    });
                });
                break;
            case 'deleteFace':
                layer.confirm('是否确认禁用人脸?', {icon: 7, title: '提示'}, function (index) {
                    common.sendAsyncRequest('/estate/serverUser/deleteFace/' + data.id, 'GET', "", function (result) {
                        //刷新表格
                        layuiTable.reload();
                        layer.msg("禁用成功");
                        layer.close(index);//关闭弹窗提示
                    });
                });
                break;
            default:
                break;
        }

    });

    //  监听禁用开启状态
    var switchRollBack = false;
    layui.form.on('switch(switch_is_enable)', function (obj) {
        if (!switchRollBack) {
            //  获取选中行数据
            var id = $(obj.elem).attr("kid");
            var url = "/estate/serverUser/updateIsEnable";
            common.sendAsyncRequest(url, 'POST', {
                id: id,
                isEnable: obj.elem.checked ? 0 : 1
            }, function (result) {
                if (!result.data) {
                    switchRollBack = !switchRollBack;
                    obj.othis.click();
                }
            }, function (result) {
                switchRollBack = !switchRollBack;
                layer.alert(result.msg, function (index) {
                    layer.close(index);
                    //  失败的回调用函数
                    obj.othis.click();
                });
            })
        } else {
            switchRollBack = !switchRollBack;
        }
    });

    //监听搜索
    form.on('submit(query)', function () {
        queryTableFn();
    });

    //监听重置查询
    form.on('submit(reset)', function () {
        $("input[name='name']").val("");
        $("input[name='tel']").val("");
        $("input[name='idCard']").val("");
        $("input[name='cardNo']").val("");
        $("select[name='type']").val("");
        $("select[name='isEnable']").val("");
        form.render('select');
        queryTableFn();
    });

    //监听服务人员添加
    form.on('submit(add)', function () {
        common.openDefaultIframe({
            title: '添加服务人员',
            content: '/estate/serverUser/add' //  打开内容
        });
    });

    //监听批量删除
    form.on('submit(batchdel)', function () {
        if (ids.length == 0) {
            layer.msg("请选择要删除的数据。");
            return;
        }
        layer.confirm('是否确认删除？', {icon: 7, title: '提示'}, function (index) {
            $.ajax({
                url: '/estate/serverUser/deleteServerUserList',
                type: 'POST',
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify(ids),
                success: function (result) {
                    if (result.code == '200') {
                        if (result.data) {
                            //  刷新表格
                            layuiTable.reload();
                            clearCheckbox();
                            layer.msg("删除成功");
                            layer.close(index);
                        } else {
                            layer.msg("删除失败");
                        }
                    } else {
                        layer.msg(result.msg);
                    }
                }
            });
        });
    });

});
