
let that;
let datatable = null;
const app = {
    data() {
        return {
            // 类型筛选选择值
            selecttype: [{ val: "0", text: "全部类型" }, { val: "1", text: "Launcher信息" }, { val: "2", text: "系统信息" }, { val: "3", text: "设备通讯" }, { val: "4", text: "通讯状态" }, { val: "5", text: "定期保存" }, { val: "6", text: "网络处理" }, { val: "7", text: "事件处理" }],
            // 类型筛选选择值
            type: Cookies.get('EVENTLOGGING_type') || 0,
            // 收起
            sq: false,
            // 第一次加载
            isfirst: true,
            // 酒店组值
            selected_hotel_group: Cookies.get('EVENTLOGGING_hotelgroup') || 0,
            // 酒店组
            selecthotelgroup: [{ HotelGroupsId: "0", HotelGroupsName: "全部酒店组" }],
            // 事件id
            mac: Cookies.get('EVENTLOGGING_mac') || "",
            // 房间当前选择
            selected_room: Cookies.get('EVENTLOGGING_room') || 0,
            // 房间选择
            selectroom: [{ val: "0", text: "全部房间" }],
            // 起始时间
            startDate: Cookies.get('EVENTLOGGING_startDate') || moment().startOf("days").format('YYYY-MM-DD HH:mm:ss'),
            // 结束时间
            endDate: Cookies.get('EVENTLOGGING_endDate') || moment().format('YYYY-MM-DD HH:mm:ss'),
            // 表格
            datatable: null,
            // 天数快捷选择值
            selected_day: Cookies.get('EVENTLOGGING_day') || 1,
            // 天数快捷选择
            selectday: [{ val: "1", text: "今天" }, { val: "2", text: "昨天" }, { val: "3", text: "最近7天" }, { val: "4", text: "最近30天" }, { val: "-1", text: "自定义" }],
            // 每页数量选择值
            selected_page: Cookies.get('EVENTLOGGING_page') || 10,
            // 每页数量
            selectpage: [{ val: "10", text: "每页10条" }, { val: "20", text: "每页20条" }, { val: "50", text: "每页30条" }, { val: "100", text: "每页40条" }],
            // 酒店选择
            selecthotel: [{ HotelId: "0", HotelName: "全部酒店" }],
            // 酒店选择值
            selected_hotel: Cookies.get('EVENTLOGGING_hotel') || 0,
            // 高度
            appheight: "",
        }
    },
    mounted() {
        that = this;
        that.init();
    },
    methods: {
        // 数据弹窗
        loc_(el) {
            let data = JSON.parse($(el).attr('data'));
            let STR =
                `<div class="col-12 row text-info card-body shadow-sm" style="padding:0.5rem;  background-color: rgb(255, 250, 240);">
                {{elm}}
                </div>
                `;
            let streml ="";
            for (let i = 1; i < 11; i++) {
                let istr = "type_param_" + i;
                let istr_ = "p" + i;
                streml += `<div  class="col-12 text-left">
                `+ istr_ + ` : <span class='text-gray'>` +  data[istr]  + `</span></div>`;
            }
            STR = STR.replace("{{elm}}", streml);
            let sw =  Swal.fire({
                title: '',
                html: STR,
                confirmButtonText: '确定',
                showCancelButton: false,
            })
        },
        // 收起按钮
        sq_change() {
            that.sq = !that.sq;
            this.loc();
        },
        // 初始化 
        init() {
            this.loc();
            this.selectgroup_init();
            // 带有时间选择的日期范围选择器
            $('#reservationtime').daterangepicker({
                startDate: that.startDate,
                endDate: that.endDate,
                timePicker: true,
                maxDate: new Date(),
                minDate: "2022-3-25 01:01:01",
                timePicker24Hour: true,
                timePickerSeconds: true,
                locale: {
                    cancelLabel: 'Clear',
                    format: 'YYYY-MM-DD HH:mm:ss'
                }
            }).on('apply.daterangepicker', function (ev, picker) {
                that.startDate = picker.startDate.format('YYYY-MM-DD HH:mm:ss');
                that.endDate = picker.endDate.format('YYYY-MM-DD HH:mm:ss');
                that.selected_day = -1;
            }).on('cancel.daterangepicker', function (ev, picker) {
                // 这个 this 指向的是时间输入框
                $(this).val('');
                that.startDate = null;
                that.endDate = null;
                that.selected_day = -1;
            });
        },
        // 酒店组改变事件 更改酒店列表信息
        selectgroup_init() {
            try {
                if (that.isfirst) {
                    MyPost("/Api/HOTELINFO", { isSwal: that.isfirst }, res => {
                        if (res == null) {
                            toastr.error('酒店信息获取失败~');
                            return;
                        }
                        that.selecthotelgroup = that.selecthotelgroup.concat(res || []);
                        let oldok = false;
                        for (let i of that.selecthotelgroup) {
                            if (i.HotelGroupsId == that.selected_hotel_group) {
                                oldok = true;
                                break;
                            }
                        }
                        if (!oldok) {
                            // 历史选择的酒店组不存在
                            that.selected_hotel_group = 0;
                            that.selected_hotel = 0;
                            that.selected_room = 0;
                        }
                        // 初始化 酒店列表
                        that.selecthotel_init();

                    });
                } else {
                    that.selecthotel_init();
                }


            } catch (e) {
                console.log("酒店组选择报错." + e);
            }
        },
        // 获取酒店下拉列表信息
        selecthotel_init() {
            that.selected_hotel_group = Number.parseInt(that.selected_hotel_group + "".replace(/\s*/g, ""));
            // 如果历史酒店组的id 未能在数据找到 就让选择全部酒店组 显示所有酒店
            let alldata = [{ HotelId: "0", HotelName: "全部酒店" }];
            for (let i of that.selecthotelgroup) {
                if (i.Hotels != null) {
                    alldata = alldata.concat(i.Hotels);
                }
                if (i.HotelGroupsId == that.selected_hotel_group && that.selected_hotel_group > 0) {
                    that.selecthotel = [{ HotelId: "0", HotelName: "全部酒店" }];
                    that.selecthotel = that.selecthotel.concat(i.Hotels || []);
                    let isold = false;
                    // 如果是第一次 那就 判断 历史选择的酒店  是否有存在 没有的话就 重置选择
                    if (that.isfirst && that.selected_hotel != 0) {
                        for (let j of that.selecthotel) {
                            if (j.HotelId == that.selected_hotel) {
                                isold = true;
                                break;
                            }
                        }
                    }
                    if (!isold) {
                        that.selected_hotel = 0;
                        that.selected_room = 0;
                    }
                    that.selectroom_init();
                    return;
                }
            }
            // 如果没有找到 就 重置选择
            that.selected_hotel_group = 0;// that.selected_hotel_group > 0  正常操作 是不存在找不到的  酒店组时已经判断过一次了。 
            that.selected_hotel = 0;
            that.selected_room = 0;
            that.selecthotel = alldata;
            that.selectroom_init();
        },
        // 获取房间下拉列表信息
        selectroom_init() {
            that.selectroom = [{ val: "0", text: "全部房间" }];
            MyPost("/Api/ROOMINFO", { isSwal: that.isfirst, data: { HotelId: that.selected_hotel, GroupId: that.selected_hotel_group } }, res => {
                that.selectroom = that.selectroom.concat(res || []);
                let oldok = false;
                if (that.isfirst && that.selected_room != 0) {
                    for (let i of that.selectroom) {
                        if (i.val == that.selected_room) {
                            oldok = true;
                            break;
                        }
                    }
                }
                if (!oldok) {
                    // 历史选择的房间不存在  或者 不是第一次加载
                    that.selected_room = 0;
                }
                //if (that.selected_room == 0 && that.selected_hotel == 0 && !that.isfirst) {
                //    return;
                //}
                that.table_init();
            });
        },
        // 时间快捷选择
        selected_day_change: function () {
            that.selected_day = Number.parseInt(that.selected_day + "".replace(/\s*/g, ""));
            switch (that.selected_day) {
                case 1:
                    that.startDate = moment().startOf("days").format('YYYY-MM-DD HH:mm:ss')
                    that.endDate = moment().format('YYYY-MM-DD HH:mm:ss')
                    break;
                case 2:
                    that.startDate = moment().subtract(1, 'days').startOf("days").format('YYYY-MM-DD HH:mm:ss');
                    that.endDate = moment().subtract(1, 'days').endOf("days").format('YYYY-MM-DD HH:mm:ss');
                    break;
                case 3:
                    that.startDate = moment().subtract(6, 'days').format('YYYY-MM-DD HH:mm:ss');
                    that.endDate = moment().format('YYYY-MM-DD HH:mm:ss');
                    break;
                case 4:
                    that.startDate = moment().subtract(29, 'days').format('YYYY-MM-DD HH:mm:ss');
                    that.endDate = moment().format('YYYY-MM-DD HH:mm:ss');
                    break;
            }
            // that.selected_day 是string 类型 他会自己转成 number 进行比较
            if (that.selected_day > -1) {
                $('#reservationtime').val(that.startDate + ' - ' + that.endDate);
                that.table_init();
            }
        },
        // 计算距离
        loc() {
            setTimeout(() => {
                $('.main-footer').hide();
                that.appheight = "calc(100vh - " + $('.table-responsive').offset().top + "px)";
            }, 10);
        },
        // 点击显示
        showtype(elm, data) {
            let STR =
                `
                <div data='`+ JSON.stringify(data) +`' onclick="javascript:event.stopPropagation();event.preventDefault();that.loc_(this)" class="col-12 row text-info card-body shadow-sm" style="padding:0.5rem;  background-color: rgb(255, 250, 240);">
                {{elm}}
                </div>
                `;
            let streml = "";
            //streml += `<div class="col-12  col-md-6">create: <span class='text-gray'>` + data['createdatetime'] + `</span></div>`;
            streml += `<div class="col-12">log_datetime: <span class='text-gray'>` + data['log_datetime'] + `</span></div>`;
            for (let i = 3; i < 11; i++) {
                let istr = "type_param_" + i;
                let istr_ = "p" + i;
                streml += `<div  class="col-md-4 col-6">
                `+ istr_ + ` : <span class='text-gray'>` + that.ellipsis(data[istr])  + `</span></div>`;
            }
            streml += `<div class="col-12">file: <span class='text-gray'>` + data['logfilename'] + `</span></div>`;
            STR = STR.replace("{{elm}}", streml);
            if (($(elm).find(".card-body").length != 0)) {
                $($(elm).find(".card-body")).toggle();
            } else {
                $(elm).find("td").append(STR);
            }
        },
        // 信息类型判断
        typetext(val_num,type = 0) {
            val_num = Number.parseInt(val_num + "".replace(/\s*/g, ""));
            switch (val_num) {
                case 1:
                    val_num = "Launcher信息";
                    if (type == 1) {
                        val_num = "#00868B"
                    }
                    break;
                case 2:
                    val_num = "系统信息";
                    if (type == 1) {
                        val_num = "#43CD80"
                    }
                    break;
                case 3:
                    val_num = "设备通讯";
                    if (type == 1) {
                        val_num = "#698B22"
                    }
                    break;
                case 4:
                    val_num = "通讯状态";
                    if (type == 1) {
                        val_num = "#8B814C"
                    }
                    break;
                case 5:
                    val_num = "定期保存";
                    if (type == 1) {
                        val_num = "#8B658B"
                    }
                    break;
                case 6:
                    val_num = "网络处理";
                    if (type == 1) {
                        val_num = "#CD6839"
                    }
                    break;
                case 7:
                    val_num = "事件处理";
                    if (type == 1) {
                        val_num = "#D02090"
                    }
                    break;
                default:
                    val_num = "其他处理";
                    if (type == 1) {
                        val_num = "#8A2BE2"
                    }
                    break;
            }
            return val_num;
        },
        // 省略
        ellipsis(value) {
             if ((""+value).length > 8) {
                value =  value.slice(0,8)+"..."
             }
            return value;
        },
        // 表格初始化
        table_init() {
            try {
                if (that.isfirst) {
                    that.isfirst = false;
                }
                if (datatable != null) {
                    datatable.destroy();
                }
                $.fn.dataTable.ext.errMode = 'none';//屏蔽掉报错弹窗
                datatable = $('#dataTable').on('error.dt', function (e, settings, techNote, message) {
                    console.log(e, settings, techNote)
                    console.log('An error has been reported by DataTables: ', message);
                }).DataTable({
                    "data": null,
                    "ordering": true,
                    "paging": true,
                    "serverSide": true,
                    "ajax": function (datas, callback, settings) {
                        datas.hotelid = that.selected_hotel;
                        datas.mac = that.mac;
                        datas.roomid = that.selected_room;
                        datas.startDate = that.startDate;
                        datas.endDate = that.endDate;
                        datas.type = that.type;
                        MyPost("/Server/RcuDataLog_", { isSwal: true, data: datas }, (res) => {
                            that.rcudata = res || [];
                            // 写入数据缓存
                            Cookies.set('EVENTLOGGING_hotelgroup', that.selected_hotel_group, { expires: 7, path: window.location.pathname });
                            if (that.endDate != null) {
                                Cookies.set('EVENTLOGGING_endDate', that.endDate, { expires: 7, path: window.location.pathname });
                            }
                            if (that.startDate != null) {
                                Cookies.set('EVENTLOGGING_startDate', that.startDate, { expires: 7, path: window.location.pathname });
                            }
                            Cookies.set('EVENTLOGGING_day', that.selected_day, { expires: 7, path: window.location.pathname });
                            Cookies.set('EVENTLOGGING_hotel', that.selected_hotel, { expires: 7, path: window.location.pathname });
                            Cookies.set('EVENTLOGGING_page', that.selected_page, { expires: 7, path: window.location.pathname });
                            Cookies.set('EVENTLOGGING_mac', that.mac, { expires: 7, path: window.location.pathname });
                            Cookies.set('EVENTLOGGING_room', that.selected_room, { expires: 7, path: window.location.pathname });
                            if (that.isfirst) { that.isfirst = false; }
                            callback(res);
                        }, (err) => {
                            toastr.error('网络繁忙~')
                        })
                    },
                    'iDisplayLength': that.selected_page,
                    "columns": [{
                        'sTitle': '',/*.substring(6)*/
                        'render': function (data, type, rcu) {
                            try {
                                let STR =
                                    `<div class="text-success col-6 col-md-4">
                                <button type="button" class='btn btn-xs'  style="COLOR:#FFF  !important; background: `+ that.typetext(rcu.log_type,1) +` !important;border: none; ">` + that.typetext(rcu.log_type) + `</button>
                                `+ rcu.mac + `
                                </div>
                                <div class="col-md-4 col-6 text-info">
                                SN:`+ rcu.log_sn + `
                                <span class="text-danger">
                                (`+ rcu.log_timespan + `)</span>
                                </div>
                                <div class="col-md-4 text-danger"></div>
                                <div class="col-md-4 col-6">
                                `+ rcu.createdatetime + `
                                </div>
                                <div class="col-md-4 col-6">
                                `+ rcu.type_param_2 + `
                                </div>
                                `;
                                return STR;
                            } catch (e) {
                                console.log(e);
                            }
                        }
                    }],
                    "fnCreatedRow": function (nRow, aData, iDataIndex) {
                        $(nRow).addClass('bg-white').addClass('shadow')
                        $(nRow).children("td").addClass('row');
                        $(nRow).children("td").click(
                            function () {
                                that.showtype(nRow, aData);
                              }
                        )
                        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)
            }
        }
    }

}

Vue.createApp(app).mount('#app');

$('#app').show();

