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

    var $node = {
        nameInput: $('#name'),
        serialNumberInput: $('#serial_number'),
        onLineStatusSelect: $('#on_line_status'),

        //  小区Id
        residentialId: $('#residential_id')
    };

    //  数据
    var Data = {
        //  当前用户机构Id
        myOrgId: parseInt($('#user_org_id').val()),
        //  表格Id
        tableId: 'data_table',
        //  选中的Id列表
        selectedIdSet: new Set(),
        //  选中的设备项列表
        selectedDeviceMap: new Map(),
        //设备在线状态
        onlineStatus: $('#onlineStatus').val()
    };

    //  初始化表单
    var layuiTable = common.layuiTable.render(layui.table, {
        id: Data.tableId
        , elem: '#data_entity_table'
        , url: '/device/manage/pagingQuery'
        , cellMinWidth: 80 //全局定义常规单元格的最小宽度，
        ,autoSort: false
        , cols: [[
            {type: 'checkbox'}
            , {field: 'alias', title: '设备别名', align: 'center'}
            , {field: 'name', title: '设备名称', align: 'center'}
            , {field: 'serialNumber', title: '设备序列号', align: 'center'}
            // , {field: 'typeNumber', title: '设备类型', align: 'center', templet: '#device_type', width: 100,sort:true}
            , {field: 'typeNumber', title: '设备类型', align: 'center', templet: '#device_type', width: 100,sort:true}
            , {title: '是否支持人脸识别', align: 'center', templet: '#have_face', width: 100}
            , {field: 'xqName', title: '所属小区', align: 'center', width: 100}
            , {field: 'installPath', title: '安装位置', align: 'center', width: 100}
            , {field: 'isOut',title: '朝向', align: 'center',sort: true, templet: '#device_is_out', width: 60}
            , {
                title: '在线状态', align: 'center',  event: 'status', width: 80, templet: function (entity) {
                    if (entity['onlineStatus'] === 1 || entity['deviceFactory'] == "qinlin") {
                        return '<span class="layui-badge layui-bg-green">在线</span>';
                    } else {
                        return '<span class="layui-badge layui-bg-cyan">离线</span>';
                    }
                }
            }
            , {title: '流量卡卡号', align: 'center', templet: '#flowCard', event: 'flowCardBind', style: 'cursor: pointer'}
            , {
                title: '最后通信时间', align: 'center', width: 160, templet: function (entity) {
                    return null == entity['lastHeartbeat'] ? '' : layui.util.toDateString(new Date(parseInt(entity['lastHeartbeat'])), 'yyyy-MM-dd HH:mm:ss');
                }
            }
            , {field: 'versionNumber', title: '版本号', align: 'center',sort: true}
            , {title: '操作', width: 180, align: 'center', toolbar: '#table-operate'}
        ]]
        , page: true
        , done: function (result) {
            var list = result.data;
            for (var i = 0; i < list.length; i++) {
                var entity = list[i];
                Data.selectedIdSet.forEach(function (selectedId) {
                    if (entity.id === selectedId) {
                        $('div[lay-id="' + Data.tableId + '"]').find('.layui-table-box table tr[data-index="' + i + '"]').find('td:first .layui-form-checkbox').eq(0).click();
                    }
                });
            }
        }
    });

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



    //  重新加载表格
    var selectedItem = undefined;
    var reloadTable = function (obj) {
        //  重新加载表格
        layuiTable.reload({
            //  设定异步数据接口的额外参数
            where: {
                name: $node.nameInput.val(),
                serialNumber: $node.serialNumberInput.val(),
                onlineStatus: $node.onLineStatusSelect.val(),
                selectedId: selectedItem ? selectedItem.id : '',
                xqId: $node.residentialId.val(),
                //排序
                sortField   :   obj?obj.field:'',
                sortOrder   :   obj?obj.type:'',
            }
            //  重新从第1页开始
            , page: {
                curr: 1
            },
            initSort: obj,
        });
    };

    //  加载树形列表
    layui.orgTree({
        //  点击路径的回调函数
        pathClickFn: function (item) {
            selectedItem = item;
            residentialSelect.update({data: initResidentialFn()});
            $node.residentialId.val('');
            reloadTable();
        },
        //  点击树的回调函数
        treeClickFn: function (item) {
            selectedItem = item;
            residentialSelect.update({data: initResidentialFn()});
            $node.residentialId.val('');
            reloadTable();
        },
        //  当前用户的机构Id
        orgId: Data.myOrgId,
        //  截至级别（不包含）
        isShowFlag: 2
    });

    //  选中复选框事件
    layui.table.on('checkbox(data_table_event)', function (obj) {
        if (obj.type === 'all') {
            if (obj.checked) {
                //  全选
                var list = layui.table.checkStatus(Data.tableId).data;
                list.forEach(function (entity) {
                    Data.selectedIdSet.add(entity.id);
                    Data.selectedDeviceMap.set(entity.id, entity);
                    selectDeviceIds.add(Number.parseInt(entity.id));
                });
            } else {
                //  全不选
                layui.table.cache[Data.tableId].forEach(function (entity) {
                    Data.selectedIdSet.delete(entity.id);
                    Data.selectedDeviceMap.delete(entity.id);
                    selectDeviceIds.delete(Number.parseInt(entity.id));
                });
            }
        } else {
            var id = obj.data.id;
            var data = obj.data;
            obj.checked ? Data.selectedIdSet.add(id) : Data.selectedIdSet.delete(id);
            obj.checked ? Data.selectedDeviceMap.set(id, data) : Data.selectedDeviceMap.delete(id);
            obj.checked ? selectDeviceIds.add(id) : selectDeviceIds.delete(id);
        }
    });

    var clickBtn = "";
    var canClickBtn = true;
    function canClick(clickBtnId){
        if(clickBtn != clickBtnId){
            clickBtn = clickBtnId;
            clearTimeout();
            canClickBtn = false;
            setTimeout(function () {
                canClickBtn = true;
                clickBtn = "";
            }, 3000);
            return true;
        }else{
            if(canClickBtn){
                return true;
            }else{
                layer.msg("请在3秒后重新点击")
            }
        }
    }

    layui.table.on('tool(data_table_event)', function (obj) {
        switch (obj.event) {
            //  管理设备
            case 'operating':
                common.openDefaultIframe({
                    title: '管理设备',
                    content: '/device/operatingView/' + obj.data.id
                });
                break;
            //  详情
            case 'info':
                common.openDefaultIframe({
                    title: '设备详情',
                    content: '/device/manage/info/' + obj.data.id
                });
                break;
            case 'complete':
                common.openDefaultIframe({
                    title: '设备详情',
                    content: '/device/manage/complete/' + obj.data.id
                });
                break;
            //  关联小区
            case 'relate':
                common.openDefaultIframe({
                    title: '关联小区',
                    content: '/device/manage/relate/' + obj.data.id
                });
                break;
            //  修改
            case 'edit':
                common.openDefaultIframe({
                    title: '修改设备',
                    content: '/device/manage/edit/' + obj.data.id
                });
                break;
             // 检查设备是否在线
            case 'checkOnline':
                if(!canClick("checkOnline")){
                    break;
                }
                $.ajax({
                    url: '/device/manage/check/online',
                    type: 'POST',
                    data: {
                        id: obj.data.id
                    },
                    success: function (result) {
                        if (result.code === '200') {
                            layer.msg("在线检测指令已下发");
                        } else {
                            layer.msg(result.msg);
                        }
                    }
                });
                break;
            //  修改开门密码
            case 'editPwd':
                layer.open({
                    title: '修改开门密码',
                    type: 1,
                    icon: 3,
                    trigger: 'click',
                    area: ['400px', '200px'],
                    content: '' +
                        '   <style type="text/css">' +
                        '       input::-webkit-outer-spin-button,' +
                        '       input::-webkit-inner-spin-button {-webkit-appearance: none;}' +
                        '       input[type="number"] {moz-appearance: textfield}' +
                        '   </style>' +
                        '   <div class="layui-card-body" style="margin-top:17px;margin-left: 20px">' +
                        '       <div class="layui-form">' +
                        '           <div class="layui-form-item">' +
                        '               <label class="layui-form-label"><span class="must">*</span><span>开门密码:</span></label>' +
                        '               <div class="layui-inline">' +
                        '                   <div class="layui-input-inline">' +
                        '                       <input name="openDoorPwd" type="number" autocomplete="off" class="layui-input" oninput="if(value.length>6)value=value.slice(0,6)">' +
                        '                   </div>' +
                        '               </div>' +
                        '           </div>' +
                        '       </div>' +
                        '</div>',
                    btn: ['确定', '取消'],
                    yes: function (index) {
                        var openDoorPwd = $('input[name="openDoorPwd"]').val();
                        if (openDoorPwd.length > 0) {
                            var data = {};
                            data.id = obj.data.id;
                            data.openDoorPwd = openDoorPwd;
                            $.ajax({
                                url: '/device/manage/edit',
                                data: data,
                                type: 'POST',
                                success: function () {
                                    layer.close(index);
                                    layer.msg('修改该设备开门密码成功');
                                }
                            });
                        } else {
                            layer.close(index);
                        }
                    },
                    btn2: function (index) {
                        layer.close(index);
                    }

                });
                break;
            //  重启设备
            case 'reload':
                if(!canClick("reload")){
                    break;
                }
                $.ajax({
                    url: '/device/manage/restart',
                    type: 'POST',
                    data: {
                        id: obj.data.id
                    },
                    success: function (result) {
                        if (result.code === '200') {
                            layer.msg("重启指令已下发，设备即将重启");
                        } else {
                            layer.msg(result.msg);
                        }
                    }
                });
                break;
            //  一键开门
            case 'openDoor':
                if(!canClick("openDoor")){
                    break;
                }
                $.ajax({
                    url: '/device/manage/open/door',
                    type: 'POST',
                    data: {
                        id: obj.data.id,
                        deviceFactory: obj.data.deviceFactory,
                        serialNumber: obj.data.serialNumber
                    },
                    success: function (result) {
                        if (result.code === '200') {
                            layer.msg("开门指令已下发，设备即将开门");
                        } else {
                            layer.msg(result.msg);
                        }
                    }
                });
                break;
            //  删除
            case 'delete':
                layer.confirm('是否确认删除设备？', {icon: 7, title: '提示'}, function (index) {
                    $.ajax({
                        url: '/device/manage/delete',
                        type: 'POST',
                        data: {
                            deviceIds: obj.data.id
                        },
                        success: function (result) {
                            if (result.code === '200') {
                                obj.del();
                                layer.msg("删除成功");
                            } else {
                                layer.alert(result.msg);
                            }
                        }
                    });
                    layer.close(index);
                });
                break;
            //  数据同步
            case 'dataSync':
                if (obj.data.deviceFactory == "dh") {
                    dhDataSyncFn(obj.data.id);
                    break;
                } else {
                    layer.open({
                        title: '数据同步',
                        area: ['500px', '135px'],
                        skin: 'alert_content',
                        btn: ['全部', '人脸广告', '轮播广告', '公告','住户人脸', '服务员人脸','门禁卡','访客授权密码'],
                        btn1: function (index) {
                            dataSyncFn(obj.data.id, 0);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn2: function (index) {
                            dataSyncFn(obj.data.id, 1);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn3: function (index) {
                            dataSyncFn(obj.data.id, 2);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn4: function (index) {
                            dataSyncFn(obj.data.id, 3);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn5: function (index) {
                            dataSyncFn(obj.data.id, 4);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn6: function (index) {
                            dataSyncFn(obj.data.id, 5);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn7: function (index) {
                            dataSyncFn(obj.data.id, 6);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn8: function (index) {
                            dataSyncFn(obj.data.id, 7);
                            layer.msg("操作成功");
                            layer.close(index);
                        }
                    });
                }
                break;
            //格式化
            case 'dataFormat':
                if (obj.data.deviceFactory == "dh") {
                    dhDataFormatFn(obj.data.id);
                    break;
                } else {
                    layer.open({
                        title: '数据格式化',
                        area: ['500px', '135px'],
                        skin: 'alert_content',
                        btn: ['全部', '人脸广告', '轮播广告', '公告','住户人脸','服务员人脸','门禁卡片','访客授权密码'],
                        btn1: function (index) {
                            dataFormatFn(obj.data.id, 0,obj.data.deviceFactory);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn2: function (index) {
                            dataFormatFn(obj.data.id, 1,obj.data.deviceFactory);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn3: function (index) {
                            dataFormatFn(obj.data.id, 2,obj.data.deviceFactory);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn4: function (index) {
                            dataFormatFn(obj.data.id, 3,obj.data.deviceFactory);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn5: function (index) {
                            dataFormatFn(obj.data.id, 4,obj.data.deviceFactory);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn6: function (index) {
                            dataFormatFn(obj.data.id, 5,obj.data.deviceFactory);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn7: function (index) {
                            dataFormatFn(obj.data.id, 6,obj.data.deviceFactory);
                            layer.msg("操作成功");
                            layer.close(index);
                        },
                        btn8: function (index) {
                            dataFormatFn(obj.data.id, 7,obj.data.deviceFactory);
                            layer.msg("操作成功");
                            layer.close(index);
                        }
                    });
                }
                /*layer.confirm('是否确认格式化该设备？', {icon: 7, title: '提示'}, function (index) {
                    $.ajax({
                        url: '/device/manage/format/data',
                        type: 'POST',
                        data: {
                            id: obj.data.id,
                            deviceFactory: obj.data.deviceFactory
                        },
                        success: function (result) {
                            if (result.code === '200') {
                                layer.msg("格式化指令已下发");
                            } else {
                                layer.msg(result.msg);
                            }
                        }
                    });
                    layer.close(index);
                });*/
                break;
            //  指令日志
            case 'log':
                common.openDefaultIframe({
                    title: '日志',
                    content: '/device/instruct/log?serialNumber=' + obj.data['serialNumber']
                });
                break;
            case 'flowCardBind' :
                common.openDefaultIframe({
                    title: '绑定流量卡',
                    content: '/device/flowCard/device/bind/' + obj.data.id
                });
                break;
            case 'status' :
                if(canClick("checkOnline")){
                    $.ajax({
                        url: '/device/manage/check/online',
                        type: 'POST',
                        data: {
                            id: obj.data.id
                        },
                        success: function (result) {
                            if (result.code === '200') {
                                layer.msg("在线检测指令已下发");
                            } else {
                                layer.msg(result.msg);
                            }
                        }
                    });
                }
                break;
            //  远程恢复版本
            case 'restore':
                if(!canClick("restore")){
                    break;
                }
                layer.confirm('是否确认远程恢复设备？', {icon: 7, title: '提示'}, function (index) {
                    $.ajax({
                        url: '/device/manage/restore',
                        type: 'POST',
                        data: {
                            id: obj.data.id
                        },
                        success: function (result) {
                            if (result.code === '200') {
                                layer.msg("远程恢复版本指令已下发，设备即将恢复版本");
                            } else {
                                layer.msg(result.msg);
                            }
                        }
                    });
                    layer.close(index);
                });
                break;
            //  远程恢复版本
            case 'obtainInfo':
                if(!canClick("obtainInfo")){
                    break;
                }
                $.ajax({
                    url: '/device/manage/info/obtain',
                    type: 'POST',
                    data: {
                        id: obj.data.id
                },
                    success: function (result) {
                        if (result.code === '200') {
                            layer.msg("远程获取设备信息指令已下发");
                        } else {
                            layer.msg(result.msg);
                        }
                    }
                });
                break;
                //  更换设备
            case 'replace':
                common.openDefaultIframe({
                    title: '更换设备',
                    content: '/device/manage/replace/' + obj.data.id
                });
                break;
            default:
                break;
        }
    });

    var dataSyncFn = function (deviceId, method) {
        $.ajax({
            url: '/device/manage/sync/data',
            type: 'POST',
            data: {
                id: deviceId,
                syncMethod: method
            },
            success: function (result) {
                if (result.code !== '200') {
                    layer.alert(result.msg);
                }
            }
        });
    };

    var dhDataSyncFn = function (deviceId) {
        $.ajax({
            url: '/device/manage/dh/sync/data',
            type: 'POST',
            data: {
                id: deviceId,
            },
            success: function (result) {
                if (result.code === '200') {
                    layer.msg("数据同步指令已下发");
                } else {
                    layer.msg(result.msg);
                }
            }
        });
    };

    var dataFormatFn = function (deviceId, method, deviceFactory) {
        $.ajax({
            url: '/device/manage/format/data',
            type: 'POST',
            data: {
                id: deviceId,
                deviceFactory: deviceFactory,
                syncMethod: method
            },
            success: function (result) {
                if (result.code !== '200') {
                    layer.alert(result.msg);
                }
            }
        });
    };

    var dhDataFormatFn = function (deviceId, method, deviceFactory) {
        $.ajax({
            url: '/device/manage/format/data',
            type: 'POST',
            data: {
                id: deviceId,
                deviceFactory: deviceFactory,
                syncMethod: method
            },
            success: function (result) {
                if (result.code !== '200') {
                    layer.alert(result.msg);
                }
            }
        });
    };

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

    //监听重置
    form.on('submit(reset)', function () {
        $node.nameInput.val("");
        $node.serialNumberInput.val("");
        $node.onLineStatusSelect.val("");
        $node.residentialId.val('');
        residentialSelect.setValue([]);
        $('#search_text').val('');
        // 刷新select标签
        form.render('select');
        reloadTable();
    });

    //监听设备添加
    form.on('submit(add)', function () {
        common.openDefaultIframe({
            title: '添加设备',
            content: '/device/manage/add'
        });
    });

    //监听设备批量修改
    form.on('submit(batch_update)', function () {
        if (Data.selectedIdSet.size > 0) {
            var parameter = '?1=1';
            Data.selectedIdSet.forEach(function (item) {
                parameter += '&idList=' + item
            });
            layer.open({
                type: 2,
                title: '批量修改',
                content: '/device/manage/batch/edit' + parameter,
                area: ['600px', '450px'],
                maxmin: true
            });
        } else {
            layer.msg("请选中要修改的设备");
        }
    });

    //监听版本升级(可选择升级的版本)
    form.on('submit(select_upgrade)', function () {
        if (Data.selectedIdSet.size === 0) {
            layer.msg("请选中要升级的设备");
            return;
        }
        if (Data.selectedDeviceMap.size === 0) {
            layer.msg("请选中要升级的设备");
            return;
        }
        if (Data.selectedDeviceMap.size === 1) {
            var k;
            for (let key of Data.selectedDeviceMap.keys()) {
                k = key;
            }
            ;
            var deviceFactory = Data.selectedDeviceMap.get(k).deviceFactory;
            var deviceModelNumber = Data.selectedDeviceMap.get(k).deviceModelNumber;
            layer.open({
                type: 2,
                title: '选择需要更新的版本',
                content: '/device/manage/batch/selectUpgrade/' + deviceFactory + "/" + deviceModelNumber,
                area: ['80%', '80%'],
                maxmin: true,
                cancel: function () {
                    reloadTable();
                }
            });
        } else {
            //检查所选的设备是否是同一厂商且同一型号
            var deviceFactory = "tempFactory";
            var deviceModelNumber = "tempTypeCode";
            var flag = true;
            Data.selectedDeviceMap.forEach(function (item) {
                if (deviceFactory === "tempFactory") { //第一条数据
                    deviceFactory = item.deviceFactory;
                    deviceModelNumber = item.deviceModelNumber;
                } else {
                    if (deviceFactory !== item.deviceFactory) {
                        layer.msg("所选设备不属于同一厂商，不能升级");
                        flag = false;
                        return;
                    }
                    deviceFactory = item.deviceFactory;
                    if (deviceModelNumber !== item.deviceModelNumber) {
                        layer.msg("所选设备不属于同一型号，不能升级");
                        flag = false;
                        return;
                    }
                    deviceModelNumber = item.deviceModelNumber;
                }
            });
            //校验通过，直接弹出窗口
            if (flag) {
                layer.open({
                    type: 2,
                    title: '选择需要更新的版本',
                    content: '/device/manage/batch/selectUpgrade/' + deviceFactory + "/" + deviceModelNumber,
                    area: ['80%', '80%'],
                    maxmin: true,
                    cancel: function () {
                        reloadTable();
                    }
                });
            }
        }
    });

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

    $("#name").on("input",function(e){
        //获取input输入的值
        let temp = e.delegateTarget.value;
        if (!/^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(e.delegateTarget.value)){
            return $("#name").val(temp.substring(0, temp.length - 1) + "") ;
        }else{

        }
    });

    function initResidentialFn() {
        var residentialList;
        common.sendSyncRequest("/estate/residential/findListByPosition", 'get', {selectTreeId: selectedItem ? selectedItem.id : ''}, function (result) {
            residentialList = result.list;
        });
        return residentialList;
    }

    if (Data.onlineStatus) {
        $node.onLineStatusSelect.next().find('dl dd[lay-value="' + Data.onlineStatus + '"]').click();
        reloadTable();
    }

});
