let that;
const app = {
    data() {
        return {
            // 定时请求,下发进度
            timer_send:null,
            // 正在发送的MAC
            mac_send:[],
            // 防抖 输入停止后才搜索
            fd: null,
            // datatable 实例
            datatable: null,
            // 每页长度
            page_length: Cookies.get('page_length') || 21,
            // 数据
            rcudata: [],
            // 内容高度
            appheight: "",
            // 房号
            roomnumber: "",
            // 房间状态
            room_type: Cookies.get('room_type') || 0,
            // 下发多选
            moresel: false,
            // tool展开
            tool: false,
            // 多选的rcu
            sel_rcu: [],
            // 下发类型  1 固件  2 配置
            send_type: Cookies.get('send_type') || 1,
            // 全选
            moresel_all: false,
            // 房间在线 -1 全部 1 在线  0 不在线
            room_online_satatus: Cookies.get('room_online_satatus') || -1,
        }
    },
    mounted() {
        that = this;
        that.init();
    },
    methods: {
        //  一些隐藏显示 
        moresel_(type = 1) {
            switch (type) {
                case 1:
                    that.moresel = !that.moresel; 
                    that.show_rcu_chek();
                    break;
                case 2:
                    that.tool = !that.tool;
                    break;
            }
        },
        // 房间前面显示多选按钮
        show_rcu_chek: function () {
            if (that.moresel) {
                $('.rcu_chek').show();
            }
            else {
                $('.rcu_chek').hide();
                // 房间 复选框消失   同时清空之前勾选的数据
                that.sel_rcu = [];
                // 全选标记取消
                that.moresel_all = false;
                $('.rcu_chek').prop('checked', false);//取消勾选
            }
        },
        // 加入或者取消选择    type = 1 表示    单个下发    会直接下发
        sel_rcu_chek: function (elm, type = 0) {
            let data = JSON.parse($(elm).attr('data-text'));
            if (type == 1) {
                let data_ = new Object();
                data_.type = that.send_type;
                data_.MAC = new Array();
                data_.MAC.push(data.MAC);
                that.SendCmd(data_);
                // 开始单个下发
                return;
            }
            if ($(elm).prop('checked')) {
                // 判断是否有
                let ok = false;
                try {
                    that.sel_rcu.forEach(function (val) {
                        if (val.MAC == data.MAC) {
                            ok = true;
                            console.log(val.MAC);
                            console.log(data.MAC);
                        throw "存在跳出...";
                    }
                    });
                }
                catch (err) {
                    console.log(err);
                }
                if (!ok) {
                    that.sel_rcu.push(data);
                }
            } else {
                // 取消全选
                that.moresel_all = false;
                // 移除
                that.sel_rcu = that.sel_rcu.filter(function (val) {
                    return val.MAC != data.MAC;
                })
            }
        },
        // 下发确认弹窗  暂时不做
        Send_ok: function (data = null, back = null) {
            if (back == null || data == null) {
                console.log("Send_ok  参数不对.....");
                return;
            }
        }, 
        // 批量下发
        more_send: function () {
            that.SendCmd();
        },
        // 初始化函数
        init: function () {
            that.loc();
            that.table_init();
        },
        // 请求数据
        getdata: function (data, back = null) {
            MyPost("/Api/GetRCU", { isSwal: that.fd == null, data }, (res) => {
                if (back != null) {
                    back(res);
                }
            }, (err) => {
                toastr.error('网络繁忙~')
                console.log(err);
            })
        },
        // 下发
        SendCmd: function (data = null, back = null) {
            // 单个下发时 会自动传入参数 data
            if (data == null) {
                data = new Object();
                data.type = that.send_type;
                data.MAC = new Array();
                that.sel_rcu.forEach((x) => {
                    data.MAC.push(x.MAC);
                    $('.' + x.MAC).find('div').css('width','0');// 点击下发 进度条为0  无作用
                });
            }
            // 记录勾选的 下发文件类型
            Cookies.set('send_type', that.send_type, { expires: 7, path: window.location.pathname });
            MyPost("/Api/SendCmd", { isSwal: true, title: "下发中...", data }, (res) => {
                if (res == null) {
                    toastr.error('网络繁忙~');
                    return;
                }
                that.sel_rcu = []; // 清空记录
                $('.rcu_chek').prop('checked', false);//取消勾选
                that.moresel_all = false; // 全选标记取消 

                // 正在下发的MAC
                that.mac_send = [];
                for (let i = 0; i < res.length; i++) {
                    let str = data.MAC[i] + '下发' + (data.type == 1 ? '固件命令' :'配置命令')+ (res[i] ? '成功~' : '下发失败~');
                    if (res[i]) {
                        // 添加到正在下发的数据
                        that.mac_send.push(data.MAC[i]);

                        // 下发成功的开始显示进度条 
                        $('.' + data.MAC[i]).show();


                    } else {
                        toastr.error(str);
                    }
                }
            },(err) => {
                toastr.error('网络繁忙~')
                console.log(err);
            })
        },
        // 高度
        loc: function () {
            // 采用的局部 vue 所以这里 有些许 jquery
            let footloc = $('.main-footer').offset().top;
            $('.main-footer').hide();
            this.appheight = "calc(100vh - " + $("#app").offset().top + "px)";
        },
        // 防抖 输入停止后才搜索
        fd_: function () {
            if(that.fd != null) {
                clearTimeout(that.fd);
                that.fd = null;
            }
            that.fd = setTimeout(function () { that.table_init(); },500);
        },
         // 数据初始化
        table_init() {
            try {
                if (that.datatable != null) {
                    that.datatable.destroy();
                }
                $.fn.dataTable.ext.errMode = 'none';//屏蔽掉报错弹窗
                that.datatable = $('#dataTable').on('draw', function (e, settings, techNote, message) {
                    console.log(e, settings, techNote)
                    console.log('An error has been reported by DataTables: ', message);
                }).on('xhr.dt', function (e, settings, json, xhr) {
                    // 每次请求数据之后根据勾选显示每个房间 的勾选框
                    setTimeout(() => { 
                        that.show_rcu_chek();
                    }, 10);
                    })
                    .DataTable({
                    "data": null,
                    "ordering": true,
                    "paging": true,
                    "serverSide": true,
                    "ajax": function (datas, callback, settings) {
                        datas.roomnumber = that.roomnumber;
                        datas.room_type = that.room_type;
                        datas.room_online_satatus = that.room_online_satatus;
                        that.getdata(datas, res => {
                            Cookies.set('room_online_satatus', that.room_online_satatus, { expires: 7, path: window.location.pathname });
                            Cookies.set('page_length', that.page_length, { expires: 7, path: window.location.pathname });
                            Cookies.set('room_type', that.room_type, { expires: 7, path: window.location.pathname });
                            callback(res)
                        });
                    },
                    'iDisplayLength': that.page_length,
                    "columns": [{
                        'sTitle': '',/* .substring(6) */
                        'render': function (data, type, rcu) { 
                            try {
                                let STR =
                                    `<div class= "` + (rcu.ONLINE_SATATUS == 0 ? 'mb' : '') + `">
                                <input type="checkbox" data-text='`+ JSON.stringify(rcu) +`' onchange="that.sel_rcu_chek(this)" class="rcu_chek" >
                                <button type="button" data-text='`+ JSON.stringify(rcu) +`' onclick="that.sel_rcu_chek(this,1)"  class= " btn btn-xs btn-success ">下发</button>
                                <button type="button" class= "`+ (rcu.ONLINE_SATATUS == 1 ? 'btn btn-xs btn-success' : 'btn btn-xs btn-danger') + `">` + (rcu.ONLINE_SATATUS == 1 ? '在线' : '离线') + `</button>
                                <button type="button" class= " btn btn-xs `+
                                (rcu.RoomStatusID == 16 ? 'btn-info' : (rcu.RoomStatusID == 2 ? 'btn-success' : (rcu.RoomStatusID == 8 ? 'btn-warning' : (rcu.RoomStatusID == 4 ? 'btn-secondary' : 'btn-danger'))))
                                 + `">` +
                                (rcu.RoomStatusID == 16 ? '空房' : (rcu.RoomStatusID == 2 ? '出租中' : (rcu.RoomStatusID == 8 ? '退房中' : (rcu.RoomStatusID == 4 ? '待租' : '未知'))))
                                + `</button> <lable class="">` + (("" + rcu.COMM_TIMEMARK) == 'null' ? " - " : rcu.COMM_TIMEMARK) + ` </lable>
                                ` + rcu.MAC +`  
                                `+ rcu.ROOM_NUMBER + `
                                </div>
                                <div title='已完成0%' class="`+ rcu.MAC +`  progress mt-1 mb-1" style="display:none;">
                                <div class="progress-bar bg-success progress-bar-striped" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%;">
                                </div>
                                <!--  @* style的效果是父元素绝对居中  *@ -->
                                <span class="  text-white" style='position:absolute;line-height:16px;width: 200px;text-align: center;left: calc(50% - 100px);'>完成0%</span></div>`;
                                return STR;
                            } catch (e) {
                                console.log(e);
                            }
                        }
                    }],
                    "fnCreatedRow": function (nRow, aData, iDataIndex) {
                        $(nRow).addClass('p-1').addClass('m-0 row col-md-4 col-12');
                        $(nRow).children("td").addClass('col-12 p-2 bg-white');
                            // .addClass('shadow');
                        return;
                    },
                    "searching": false,
                    "autoWidth": false,
                    "bDeferRender ": true,
                    "bLengthChange": false,
                    "language":
                    {
                        "sProcessing": "处理中...",
                        "sLengthMenu": "显示 _MENU_ 项结果",
                        "sZeroRecords": "没有匹配结果",
                        "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                        "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                        "sInfoPostFix": "",
                        "sSearch": "搜索:",
                        "sUrl": "",
                        "sEmptyTable": "表中数据为空",
                        "sLoadingRecords": "载入中...",
                        "sInfoThousands": ",",
                        "oPaginate": {
                            "sFirst": "首页",
                            "sPrevious": "上页",
                            "sNext": "下页",
                            "sLast": "末页"
                        },
                        "oAria": {
                            "sSortAscending": ": 以升序排列此列",
                            "sSortDescending": ": 以降序排列此列"
                        }
                    }
                });
            } catch (e) {
                console.log(e)
            }
        },
        //全选按钮文字 点击事件
        moresel_all_: function () {
            // 没有开启多选无法点击
            if (!that.moresel) { return; }
            that.moresel_all = !that.moresel_all;
            that.moresel_all_sel();
        },
        // 取消全选
        moresel_all_sel: function () {
            // 没有开启多选无法点击
            if (!that.moresel) { return; }
            $('.rcu_chek').prop('checked',that.moresel_all);//房间前面的按钮全勾选、取消勾选
            $('.rcu_chek').change();//调用事件添加、移除到选定的数组中
        },
        // 请求进度
        send_schedule: function () {
            let data = new Object();
            data.mac = that.mac_send;
            data.type = that.send_type;
            MyPost("/Api/send_schedule", { isSwal: false, data }, (res) =>
            {
                    if (res == null) {
                        toastr.error('网络繁忙~');
                        return;
                }
                
                that.mac_send =  that.mac_send.filter(key => {
                    if (res[key] != null) {
                        $('.' + key).find('div').css('width', res[key]);
                        $('.' + key).parent().find('span').html(res[key]);
                    }
                    return res[key] != "100.00%";
                });

            }, (err) => {
                toastr.error('网络繁忙~')
                console.log(err);
            })
        }
    },
    watch: {
        mac_send: function (val) {
            that.mac_send = val;
            if (that.timer_send != null) {
                clearInterval(that.timer_send);
            }
            if (that.mac_send.length>0) {
                that.timer_send = setInterval(() => {
                    // 定时请求 发送进度接口 
                    that.send_schedule();
                }, 500);
            }
        },
    }
}
Vue.createApp(app).mount('#app');
$('#app').show();


