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

    var layuiTable = null;

    // 查询框表单
    var $node = {
        //  单元搜索
        unitId  :  $('#unit_id'),
        //  房间搜索
        roomId : $('#room_id'),
        //  住户姓名
        nameInput  :  $('input[name="name"]'),
        //  联系方式
        telInput  :  $('input[name="tel"]'),
        //  身份证
        idCardInput  :  $('input[name="idCard"]'),

        cardNo  :  $('input[name="cardNo"]'),
        //  时间
        faceBeginDate : $('#face_begin_date'),
        faceEndDate : $('#face_end_date'),
        cardBeginDate : $('#card_begin_date'),
        cardEndDate : $('#card_end_date')
    };

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

    //日期时间范围
    laydate.render({
        elem: '#face_date'
        ,type: 'datetime'
        ,range: true
        ,done: function(value, date, endDate){
            var dateArray = value.split(" - ");
            $("#face_begin_date").val(dateArray[0]);
            $("#face_end_date").val(dateArray[1]);
        }
    });
    //日期时间范围
    laydate.render({
        elem: '#card_date'
        ,type: 'datetime'
        ,range: true
        ,done: function(value, date, endDate){
            var dateArray = value.split(" - ");
            $("#card_begin_date").val(dateArray[0]);
            $("#card_end_date").val(dateArray[1]);
        }
    });

    //  重新加载表格
    var reloadTable = function(obj){
        //重新加载表格
        layuiTable.reload({
            where:{
                unitId : $node.unitId.val(),
                roomId : $node.roomId.val(),
                name  :  $node.nameInput.val(),
                tel  :  $node.telInput.val(),
                idCard  :  $node.idCardInput.val(),
                faceBeginDate : $node.faceBeginDate.val(),
                faceEndDate : $node.faceEndDate.val(),
                checkState  :  $('#check_state option:selected').val(),
                cardNo : $node.cardNo.val(),
                cardBeginDate : $node.cardBeginDate.val(),
                cardEndDate : $node.cardEndDate.val(),
                //排序
                sortField   :   obj?obj.field:'',
                sortOrder   :   obj?obj.type:'',
            }
            //重新从第1页开始
            ,page: {
                curr: 1
            },
            initSort:obj
        });
    };
    //  初始化
    (function(){
        //  初始化表格
        layuiTable = common.layuiTable.render(layui.table,{
            elem: '#table_id'
            ,url: '/estate/access/showAccessUserList?residentialId=' + pageData.residentialId
            ,cellMinWidth: 80 //全局定义常规单元格的最小宽度，
            , cols: [[
                { field: 'name', title: '姓名',align:'center'}
                ,{ field: 'tel', title: '联系方式',align:'center' }
                ,{ field: 'idCard', title: '身份证',align:'center' }
                ,{ field: 'roomName', title: '房间名称',align:'center'}
                ,{ field: 'unitName', title: '单元名称',align:'center'}
                ,{ field: 'residentialName', title: '小区名称',align:'center'}
                // ,{ field: 'checkState', title: '人脸审核状态',templet: '#is_checkState' ,align:'center'}
                ,{ title: '卡号',align:'center',templet:function (d) {
                        if(d.accessCard){
                            return d.accessCard.cardNo;
                        }
                        return "";
                    }
                 }
                ,{ field: '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: 'faceBeginDate', width: 90, title: '人脸有效期-开始',sort:true,align:'center' }
                , { field: 'faceEndDate', width: 90, title: '人脸有效期-结束',sort:true,align:'center' }
                ,{ title: '卡状态',align:'center', templet: function(d){
                        if (d.accessCard){
                            if (d.accessCard.cardEnable == 0){
                                return '<span class="layui-badge layui-bg-black">未启用</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 '<span class="layui-badge layui-bg-orange">未设置</span>';
                            }
                        }else{
                            return '<span class="layui-badge layui-bg-orange">未设置</span>';
                        }
                    } }
                ,{ field: 'faceEnable', title: '人脸状态',templet: '#is_faceEnable',sort:true,align:'center' }
                ,{ title: '操作',width:180,align: 'center', toolbar: '#table-useradmin-webuser' }
            ]]
            //  开启分页功能
            , page: true
            ,done:function(res,curr,count){
                layer.photos({
                    photos: '#layPhotosTbImg',
                    shade: .1,
                    closeBtn: true
                });
            }
        });
    })();

    //排序
    layui.table.on('sort(table_event)',function (obj) {
        reloadTable(obj);
    });

    //监听行工具事件 lay-filter="table_event"
    table.on('tool(table_event)', function(obj){
        var data = obj.data; //获得当前行数据
        var userDataStr = data.name + " - " + data.residentialName + " - " + data.unitName;
        switch (obj.event) {
            case 'faceImageSet'://人脸设置
                common.openDefaultIframe({
                    title: '人脸设置',
                    content:  '/estate/access/indexUserFaceSet/'+data.id
                });
                break;
            case 'cardSet'://卡设置
                common.openDefaultIframe({
                    title: '卡设置',
                    content:  '/estate/access/indexUserCardSet/'+data.id
                });
                break;
            case 'log4face':
                common.openDefaultIframe({
                title   :   '人脸日志' + " 【 " + userDataStr + " 】",
                content :   '/estate/user/log4face?userId=' + data.id
            });
                break;
            //  卡日志
            case 'log4card':
                var accessCard = data.accessCard;
                if(!accessCard){
                    layer.alert("暂无卡片信息，请先设置卡号！");
                }else{
                    common.openDefaultIframe({
                        title   :   '卡日志' + " 【 " + userDataStr + " 】",
                        content :   '/estate/user/log4card?cardNo=' + accessCard.cardNo
                    });
                }
                break;
            //  特殊门禁授权
            case 'specialSet':
                common.openMaxIframe({
                    title   :   '特殊门禁授权',
                    content :   '/estate/access/specialOpenPermissionSet/' + data.id + '/' + data.residentialId
                });
                break;
            //  门禁禁用
            case 'accessDisable':
                layer.confirm('是否确认禁用?', {icon: 7, title:'提示'},function(index) {
                    var devicesAccessPushVO = {};
                    devicesAccessPushVO.operType = 2;
                    devicesAccessPushVO.userId = data.id;
                    common.sendAsyncRequest('/estate/access/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/access/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/access/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/access/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/access/accessDevicesManualPush','POST',devicesAccessPushVO,function (result){
                        //刷新表格
                        layuiTable.reload();
                        layer.msg("卡禁用成功");
                        layer.close(index);//关闭弹窗提示
                    });
                });
                break;
            default:
                break;
        }
    });

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

    //监听重置查询
    form.on('submit(reset)', function(){
        unitSelect.update({data : [] , disabled : true});
        roomSelect.update({data : [] , disabled : true});
        $node.unitId.val('');
        $node.roomId.val('');
        $node.nameInput.val('');
        $node.telInput.val('');
        $node.idCardInput.val('');
        $node.faceBeginDate.val('');
        $node.faceEndDate.val('');
        $('#face_date').val('');
        $node.cardNo.val('');
        $node.cardBeginDate.val('');
        $node.cardEndDate.val('');
        $('#card_date').val('');
        // 刷新select标签
        $('#check_state').val("");
        form.render('select');
        reloadTable();
    });

    //单元查询下拉列表
    var unitSelect = xmSelect.render({
        el: '#unit_name',
        prop: {
            name: 'name',
            value: 'id',
        },
        toolbar: {
            show: true,
            list: [{
                name: '清空',
                method(){
                    unitSelect.setValue([]);
                    $node.unitId.val('');
                    roomSelect.update({disabled:true}).setValue([]);
                    $node.roomId.val('');
                }
            }]
        },
        clickClose: true,
        filterable: true,
        remoteSearch: true,
        remoteMethod: function (val, cb, show) {
            $.ajax({
                type: 'GET',
                url: '/estate/unit/getListByLikeName',
                data: {
                    name : val,
                    residentialId : pageData.residentialId,
                    isSelect : true
                },
                success: function (result) {
                    cb(result.list);
                },
                error: function () {
                    cb([]);
                }
            });
        },
        //监听选择
        on: function (data) {
            var change = data.change;
            if (change.length > 0) {
                $node.unitId.val(change[0].id);
                roomSelect.update({data : initRoomFn(change[0].residentialId,change[0].id) , disabled : false});
            }
            if (!data.isAdd) {
                $node.unitId.val('');
                roomSelect.update({data : [] , disabled : true});
            }
            $node.roomId.val('');
        },
        //显示方式
        model: {
            label: {
                type: 'text',
                text: {
                    //左边拼接的字符
                    left: '',
                    //右边拼接的字符
                    right: '',
                    //中间的分隔符
                    separator: ', ',
                },
            }
        },
    });

    //房间查询下拉列表
    var roomSelect = xmSelect.render({
        el: '#room_name',
        disabled: true,
        radio: true,
        prop: {
            name: 'name',
            value: 'id',
        },
        toolbar: {
            show: true,
            list: [{
                name: '清空',
                method(){
                    roomSelect.setValue([]);
                    $node.roomId.val('');
                }
            }]
        },
        clickClose: true,
        filterable: true,
        remoteSearch: true,
        remoteMethod: function (val, cb, show) {
            $.ajax({
                type: 'GET',
                url: '/estate/room/getListByLikeName',
                data: {
                    name : val,
                    residentialId : pageData.residentialId,
                    unitId : $node.unitId.val(),
                    isSelect : true
                },
                success: function (result) {
                    cb(result.list);
                },
                error: function () {
                    cb([]);
                }
            });
        },
        //监听选择
        on: function (data) {
            var change = data.change;
            if (change.length > 0) {
                $node.roomId.val(change[0].id)
            }
            if (!data.isAdd) {
                $node.roomId.val('');
            }
        },
        //显示方式
        model: {
            label: {
                type: 'text',
                text: {
                    //左边拼接的字符
                    left: '',
                    //右边拼接的字符
                    right: '',
                    //中间的分隔符
                    separator: ', ',
                },
            }
        },
    });

    function initRoomFn(residentialId,unitId) {
        var roomList;
        common.sendSyncRequest("/estate/room/getListByLikeName", 'get', {residentialId : residentialId , unitId : unitId,isSelect : true}, function (result) {
            roomList = result.list;
        });
        return roomList;
    }
});
