<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
    <title>@ViewData["Title"] - UniversalApi_WebConsole_App</title>
    <link rel="stylesheet" href="~/WebConsole/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/WebConsole/css/site.css" />
    <link rel="stylesheet" href="~/WebConsole/css/commonlayout.css"/>
    <link rel="stylesheet" href="~/WebConsole/css/hint.css" />
    <link rel="stylesheet" href="~/WebConsole/css/index.css"/>
    <style type="text/css">
        .mydiv {
            position: absolute;
            bottom:0%;
            left: 0.8%;
            width: 83%;
            z-index: 9999;
            visibility: hidden;
        }
        .mydivNumber {
            position: absolute;
            z-index: 9999;
            visibility: hidden;
            top: 50%;
            left: 40%;
            width: 30%;
        }
    </style>
</head>

<body id="mainscreen_body">
    <header>
        <div id="common_header" class="commonheader" onclick="AlarmBarClicked(this.id)">
            <img id="common_header_left_normal" v-show="currentAlarmBarItem === undefined ||currentAlarmBarItem.Severity==='Information'"
                 src="~/WebConsole/images/shared/headblueLeft.png" />
            <img id="common_header_left_warning" src="~/WebConsole/images/shared/headYellowLeft.png"
                 v-show="currentAlarmBarItem !== undefined&&currentAlarmBarItem.Severity==='Warning'" />
            <img id="common_header_left_alarm" src="~/WebConsole/images/shared/headRedLeft.png"
                 v-show="currentAlarmBarItem !== undefined&&(currentAlarmBarItem.Severity==='Error'||
                 currentAlarmBarItem.Severity==='Fatal')" />
            <div id="common_header_informations">
                <span id="common_header_left_text" v-if="currentAlarmBarItem !== undefined" style="left: 0%; width: 100%;visibility:hidden;">
                    {{currentAlarmBarItem.Title}}
                </span>
            </div>

            <img id="common_header_right_date_img" src="~/WebConsole/images/shared/headRight.png" />
            <span id="common_header_right_text">
                @DateTime.Now.ToShortDateString()
            </span>
        </div>
    </header>

    <div id="smartfuel_main_view">
        @RenderBody()
        <div id="alarm_information" @*v-show="showAlarmHistoryForm"*@ style="visibility:hidden;">
            <div id="alarm_table">
                <table id="alarm_table_infos" class="alarmTable">
                    <thead class="tableRow">
                        <tr>
                            <th v-for="(h,i) in headers" :key="i" :class="h.class" style="text-align:center;">{{h.text}}</th>
                        </tr>
                    </thead>
                    <tbody class="alarmTableBody">
                        <tr class="tableRow" v-for="(alarm,i) in genericAlarmList" :key="i">
                            @*<td class="tableData2">{{alarm.Severity}}</td>*@
                            <td class="tableDataSeverity">
                                <i :class="(alarm.Severity==='Fatal'||alarm.Severity==='Error')?'redCircle':
                                   (alarm.Severity==='Warning'?'yellowCircle':'blueCircle')"></i>
                            </td>
                            <td class="tableData2Hide" onclick="showDetails(this)">{{alarm.Title}}</td>
                            <td class="tableData2Hide" onclick="showDetails(this)">{{alarm.OriginatorDisplayName}}</td>
                            <td class="tableData2" v-if="alarm.ClosedTimestamp===null">{{formatTime(alarm.OpeningTimestamp)}}</td>
                            <td class="tableData2" v-else>{{formatTime(alarm.OpeningTimestamp)}}({{formatTime(alarm.ClosedTimestamp)}}<a @@click="showCloseReason(alarm)" style="color: #1cd4f8; font-size: 1.2rem; text-decoration: underline; text-decoration-color: #0094ff;">关结</a>)</td>
                            <td class="tableData3" onclick="showDetails(this)">{{alarm.Detail}}</td>
                            <td class="tableData1">
                                <img v-show="alarm.AckedTimestamp === null" class="muteImg" @@click="AckGenericAlarm(alarm)" />
                                <img v-show="alarm.AckedTimestamp !== null" class="alarmImg" @@click="AckGenericAlarm(alarm)" />
                                <img v-show="alarm.ClosedTimestamp===null" class="closeImg" @@click="closeAlarm(alarm)" />
                                <img v-show="alarm.ClosedTimestamp !==null" class="closedImg" />
                            </td>
                        </tr>
                    </tbody>
                </table>
                <div id="details" style="position:absolute;visibility:hidden;background-color: rgba(0, 0, 0, .4)">
                    <div id="detail_button" class="messageButtonDiv">
                        <input type="button" class="messageButton" value="關閉" onclick="hidenTheDetailsForm()" />
                    </div>

                    <div id="detail_message" class="messageDiv">{{detailMessage}}</div>
                </div>
            </div>
            <div id="alarm_pageInfo">
                <div class="pageStepDiv" onclick="previous()"><img class="pageStepImg" src="~/WebConsole/images/smartFuel/prePage.png"/></div>
                <div class="pageStepDiv" onclick="next()"><img class="pageStepImg" src="~/WebConsole/images/smartFuel/nextPage.png" /></div>
            </div>
            <img id="alarm_closeButton" src="/WebConsole/images/shared/closeButton.png" class="closeAlarmFormButton" onclick="AlarmBarClicked(this.id)" />
            <img id="alarm_query" src="/WebConsole/images/device/filter.png" class="alarmFilter" onclick="showAlarmQuery()" />
            <div id="alarm_query_form" v-show="showFilterForm" class="alarmQueryForm">
                <div id="alarm_query_option1" class="option1Div">
                    <p>篩選條件:</p>
                    <select v-model="option1" @@change="option1Change">
                        <option v-for="(item, i) in options1" :key="i" :value="item.value">{{ item.text }}</option>
                    </select>
                </div>

                <div v-show="option1!==0" id="alarm_query_option2" class="option2Div">
                    @*<p>详细信息:</p>*@
                    <ul class="queryUl">
                        <li v-for="(item, i) in selectedList" :key="i">
                            <p><input type="checkbox" v-model="item.checked" value="item.value" />{{item.value}}</p>
                        </li>
                    </ul>
                </div>
                <div id="alarm_query_search" class="searchDiv">
                    <img id="alarm_query_search_img" src="~/WebConsole/images/onlineMonitor/chartView/table.png" class="searchImg" onclick="showQueryReslut()" />
                </div>
            </div>
        </div>
        <div class="alarmInfoWrap hide">
            <div class="wrap-dialog hide">
                <div class="dialog">
                    <div class="dialog-header">
                        <span class="dialog-title"></span>
                    </div>
                    <div class="dialog-body">
                        <span class="dialog-message"></span>
                    </div>
                    <div class="dialog-footer">
                        <input type="button" class="btn" id="confirm" value="確認" />
                        <input type="button" class="btn ml50" id="cancel" value="取消" />
                    </div>
                </div>
            </div>
        </div>      
    </div>

    <div class="fullScrrenWrap hide">
        <div class="input-dialog" id="input_dialog_wrap">
            <div class="dialog">
                <div class="dialog-header">
                    <span class="input-dialog-title"></span>
                </div>
                <div class="dialog-body">
                    <input class="input-box" id="input_value" type="password"/>
                </div>
                <div class="dialog-footer">
                    <input type="button" class="btn" id="input_confirm" value="確認" />
                    <input type="button" class="btn ml50" id="input_cancel" value="取消" />
                </div>
            </div>
        </div>
    </div>
    <div id="mydiv" class="mydiv"><div id="mydivheader" class="simple-keyboard"></div></div>
    <div id="common_popupMenu">
        <div class="popupMenuItem" v-for="(menuItem, i) in bottomPopupMenuItems " :key="i" @@click="menuItemClicked(menuItem)">
            {{menuItem.dispalyText}}
        </div>
    </div>
    <footer>
        @*<div id="mydiv"><div id="mydivheader" class="simple-keyboard"></div></div>*@
        <div id="common_footer">
            <img id="common_footer_img" draggable="false" src="~/WebConsole/images/shared/smartFuelFooter.png" />
            <div class="menuItemDiv">
                <a class="menuItem" draggable="false" v-for="(item, i) in bottonMenuItems" :key="i" @@click="menuItemClicked(item)" @*:href="item.LinkUrl"*@>
                    <img draggable="false" class="menuItemImg" :src="item.IconUrl" />
                </a>
            </div>


            <!--<a id="common_footer_smartfuel" draggable="false" asp-controller="SmartFuel" asp-action="Index" style="left:40.625%;">
                        <img draggable="false" src="/WebConsole/images/shared/nozzle.png">
                    </a>
                    <a id="common_footer_tank" draggable="false" asp-controller="TankDetails" asp-action="Index" style="left:50.234%;">
                        <img draggable="false" src="/WebConsole/images/shared/tank.png">
                    </a>
                    <a id="common_footer_fairbanks" draggable="false" asp-controller="FairBanks" asp-action="Index" style="left:59.844%;">
                        <img draggable="false" src="/WebConsole/images/shared/fairBanks.png">
                    </a>
                    <a id="common_footer_settings" draggable="false" asp-controller="Config" asp-action="Index" style="left:69.453%;">
                        <img draggable="false" src="/WebConsole/images/shared/settings.png">
                    </a>
                    <a id="common_footer_restart" draggable="false"-->
            @*asp-controller="" asp-action=""*@
            <!--style="left:79.063%;">
                <img draggable="false" src="/WebConsole/images/shared/restart.png">
            </a>
            <a id="common_footer_exist" draggable="false"-->
            @*asp-controller="" asp-action=""*@
            <!--style="left:88.672%;">
                <img draggable="false" src="/WebConsole/images/shared/exit.png">
            </a>-->
        </div>
    </footer>
    <script src="~/WebConsole/js/index.js"></script>
    <script src="~/WebConsole/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/WebConsole/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/WebConsole/js/site.js" asp-append-version="true"></script>
    @*<script src="~/WebConsole/js/signalr/dist/browser/signalr.js"></script>*@
    @*<script src="~/WebConsole/js/alarmBar.js"></script>*@
    <script src="~/WebConsole/js/mqtt.min.js"></script>
    @*<script src="~/WebConsole/js/AlarmBarClient.js"></script>*@
    <script type="text/javascript" src="~/WebConsole/js/vue.min.js"></script>
    <script src="~/WebConsole/js/alarms.js"></script>
    @RenderSection("Scripts", required: false)
    <script>
        // Make the DIV element draggable:
        dragElement(document.getElementById("mydiv"));

        function dragElement(elmnt) {
            var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
            if (document.getElementById(elmnt.id + "header")) {
                // if present, the header is where you move the DIV from:
                document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
            } else {
                // otherwise, move the DIV from anywhere inside the DIV:
                elmnt.onmousedown = dragMouseDown;
            }

            function dragMouseDown(e) {
                e = e || window.event;
                e.preventDefault();
                // get the mouse cursor position at startup:
                pos3 = e.clientX;
                pos4 = e.clientY;
                document.onmouseup = closeDragElement;
                // call a function whenever the cursor moves:
                document.onmousemove = elementDrag;
            }

            function elementDrag(e) {
                e = e || window.event;
                e.preventDefault();
                // calculate the new cursor position:
                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;
                // set the element's new position:
                elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
                elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
            }

            function closeDragElement() {
                // stop moving when mouse button is released:
                document.onmouseup = null;
                document.onmousemove = null;
            }
        }
    </script>
    <script>
        var alarmsCategoryMap = new Map();
        var alarmsOriginalMap = new Map();
        var layoutvm = new Vue({
            el: '#alarm_information',
            data: {
                page: 1,
                pageCount: 10,
                genericAlarmList: [],
                showAlarmHistoryForm: false,
                showFilterForm: false,
                alarmCount: 0,
                warningCount: 0,
                alarmBarItem: null,
                option1: 0,
                categoryList: [],
                orignialList: [],
                selectedList: [],
                tableDataSource: [],
                detailMessage: "",
                options1: [{ text: "所有", value: 0 }, { text: "來源", value: 1 }, { text: "分類", value: 2 }],
                headers: [{ text: "級別", class: "tableData0" }, { text: "標題", class: "tableData2" }, { text: "來源", class: "tableData2" },
                { text: "發生時間", class: "tableData2" }, { text: "詳情", class: "tableData3" }, { text: "操作", class: "tableData1" }]
            },
            methods: {

            },
            mounted: function () {
                console.log("layout mouted");
            }
        });
        var alarmBarVm = new Vue({
            el: '#common_header',
            data: {
                currentAlarmBarItem: { Title: "", Severity: "Information", PersistId: -1 },
            },
        }
        );//Information Fatal,Error,Warning,

        var hrefTemp = window.location.href;
        var pathTemp = window.location.pathname;
        let basicUrlTemp = href.slice(0, href.indexOf(path));
        var defaultBottomMenu = [{ "IconUrl": "/WebConsole/images/shared/nozzle.png", "LinkUrl": basicUrlTemp + "/SmartFuel", "Action": "" },
        { "IconUrl": "/WebConsole/images/shared/tank.png", "LinkUrl": basicUrlTemp + "/TankDetails", "Action": "" },
        { "IconUrl": "/WebConsole/images/shared/fairBanks.png", "LinkUrl": basicUrlTemp + "/FairBanks", "Action": "" },
        { "IconUrl": "/WebConsole/images/shared/settings.png", "LinkUrl": basicUrlTemp + "/Config", "Action": "" },
        { "IconUrl": "/WebConsole/images/shared/restart.png", "LinkUrl": "", "Action": "" },
        { "IconUrl": "/WebConsole/images/shared/exit.png", "LinkUrl": "", "Action": "" }
        ];
        var bottomMenuVm = new Vue({
            el: '#common_footer',
            data: {
                bottonMenuItems: []
            }
        });
        var bottomPopupMenuVm = new Vue({
            el: '#common_popupMenu',
            data: {
                bottomPopupMenuItems: []
            }
        });

        function getGenericAlarmHistory(initialget, severity, category, originator) {
            var href = window.location.href;
            var path = window.location.pathname;
            let basicUrl = href.slice(0, href.indexOf(path));
            let clientAcceptLanguage = navigator.language;
            let serviceUrl = basicUrl + "/u/?apitype=service&an=GetGenericAlarmHistoryAsync&pn=ProcessorsDispatcher&en=Edge.Core.Processor.Dispatcher.DefaultDispatcher";
            let parameter = [null, null, severity, originator, category, true, false, layoutvm.page - 1, layoutvm.pageCount, clientAcceptLanguage];
            //[null, null, null, severity,null, true, false, 0, 9999, ""];

            $.ajax({
                url: serviceUrl,
                datatype: "application/json",
                type: 'post',
                contentType: "application/json;charset=utf-8;",
                data: JSON.stringify(parameter),
                beforeSend: function () {
                },
                success: function (data) {
                    console.log(data);
                    layoutvm.genericAlarmList = Array.isArray(data) ? data : [];
                    if (initialget) {
                        if (data.length > 0 && alarmBarVm.currentAlarmBarItem.PersistId === -1)
                            alarmBarVm.currentAlarmBarItem = data[0];
                        var alarmTextSpan = document.getElementById("common_header_left_text");
                        if (alarmTextSpan && alarmTextSpan.style.visibility === 'hidden') {
                            alarmTextSpan.style.visibility = 'visible';
                        }
                    }
                    toAddAlarmAudio();
                },
                error: function (err) {
                    layoutvm.genericAlarmList = [];
                }
            });
        }
        //如果当前页或者顶部栏有报警,需要响警报
        function toAddAlarmAudio() {
            var hasFatalAlarm = false;
            var topBarAlarmInList = false;
            if (layoutvm.genericAlarmList && Array.isArray(layoutvm.genericAlarmList) && layoutvm.genericAlarmList.length > 0) {
                layoutvm.genericAlarmList.forEach(function (alarm) {
                    if ((alarm.Severity === 'Error' || alarm.Severity === "Fatal") &&
                        alarm.AckedTimestamp === null && alarm.ClosedTimestamp === null) {
                        hasFatalAlarm = true;
                    }
                    if (alarmBarVm.currentAlarmBarItem !== undefined &&
                        (alarm.Id === alarmBarVm.currentAlarmBarItem.PersistId ||
                        alarmBarVm.currentAlarmBarItem.Id === alarm.Id)) {
                        topBarAlarmInList = true;
                    }
                });
            }
            if (hasFatalAlarm)
            {
                addAlarmAudio();
            } else if (topBarAlarmInList) {
                removeAlarmAudio();
            }
        
        }

        function getGenericAlarmsSummaryAsync() {
            var href = window.location.href;
            var path = window.location.pathname;
            let basicUrl = href.slice(0, href.indexOf(path));
            let clientAcceptLanguage = navigator.language;
            let serviceUrl = basicUrl + "/u/?apitype=service&an=GetGenericAlarmsSummaryAsync&pn=ProcessorsDispatcher&en=Edge.Core.Processor.Dispatcher.DefaultDispatcher";
            let parameter = [clientAcceptLanguage];

            $.ajax({
                url: serviceUrl,
                datatype: "application/json",
                type: 'post',
                contentType: "application/json;charset=utf-8;",
                data: JSON.stringify(parameter),
                beforeSend: function () {
                },
                success: function (data) {
                    console.log(data);
                    layoutvm.categoryList = [];
                    layoutvm.orignialList = [];
                    if (data !== null && Array.isArray(data.Categories)) {
                        data.Categories.forEach(function (category, i) {
                            if (category !== null) {
                                layoutvm.categoryList.push({ checked: false, value: category });
                            }
                        });
                    }
                    if (data && Array.isArray(data.Originators)) {
                        data.Originators.forEach(function (originator, i) {
                            if (originator !== null) {
                                layoutvm.orignialList.push({ checked: false, value: originator });
                            }
                        });
                    }
                },
                error: function (err) {
                    layoutvm.categoryList = [];
                    layoutvm.orignialList = [];
                }
            });
        }

        $(document).ready(function () {
            //console.log("Joy layout ready");
            getGenericAlarmHistory(true, null, null, null);

            getWebConsoleAPI(["webapi", ["WebConsole"]], function (apiPath) {
                if (apiPath === null || apiPath === undefined || apiPath === "") {
                    bottomMenuVm.bottonMenuItems = defaultBottomMenu.reverse();
                    return;
                }
                var href = window.location.href;
                var path = window.location.pathname;
                let basicUrl = href.slice(0, href.indexOf(path));
                var serviceUrl = basicUrl + apiPath;

                $.ajax({
                    url: serviceUrl,
                    datatype: "application/json",
                    type: 'post',
                    contentType: "application/json;charset=utf-8;",
                    beforeSend: function () {
                    },
                    success: function (data) {
                        console.log(data);
                        if (data !== null && data.LayoutConfig !== null && data.LayoutConfig !== undefined &&
                            data.LayoutConfig.NaviMenuConfig && data.LayoutConfig.NaviMenuConfig.MenuItemConfigs !== undefined &&
                            Array.isArray(data.LayoutConfig.NaviMenuConfig.MenuItemConfigs) &&
                            data.LayoutConfig.NaviMenuConfig.MenuItemConfigs.length > 0) {
                            var tempItems = [];
                            data.LayoutConfig.NaviMenuConfig.MenuItemConfigs.forEach(function (item, i) {
                                if (item !== null) {
                                    tempItems.push(item);
                                }
                            });
                            bottomMenuVm.bottonMenuItems = tempItems.length > 0 ? tempItems.reverse() : defaultBottomMenu.reverse();
                        } else {
                            bottomMenuVm.bottonMenuItems = defaultBottomMenu.reverse();
                        }
                    },
                    error: function (err) {
                        console.log(err);
                        bottomMenuVm.bottonMenuItems = defaultBottomMenu.reverse();
                    }
                });
            });
        });

        function showDetails(obj) {
            if (obj.offsetWidth < obj.scrollWidth) {
                //var that = this;
                layoutvm.detailMessage = obj.textContent;
                var messageDiv = document.getElementById("details");
                if (messageDiv === null) return;
                messageDiv.style = "position:absolute;width:" + obj.offsetWidth + "px;height:" + 3 * obj.offsetHeight + "px;left:" +
                    obj.offsetLeft + "px;top:" + obj.offsetTop + "px;visibility:visible;border:none;background-color: rgba(0, 0, 0, .4);" +
                    "box-shadow:gainsboro 2px 2px 3px 2px;";
            }
        };
        function showCloseReason(alarm) {
            layoutvm.detailMessage = alarm.ClosedReason;
            //alert(alarm.ClosedReason);
            var messageDiv = document.getElementById("details");
            if (messageDiv === null) return;
            messageDiv.style = "position:absolute;width:20%;height:20%;left:40%;top:30%;visibility:visible;background-image:url('/WebConsole/images/onlineMonitor/chartView/background_query.png');background-repeat:no-repeat;background-size:100% 100%; border:none;" +
                "box-shadow:gainsboro 2px 2px 3px 2px;";
        }
        function hidenTheDetailsForm() {
            layoutvm.detailMessage = "";
            var messageDiv = document.getElementById("details");
            if (messageDiv === null) return;
            messageDiv.style.visibility = "hidden";
        }
        function option1Change() {
            //console.log("Joy option1Change");
            //选择所有时不需要展示其他选项
            layoutvm.selectedList = layoutvm.option1 === 1 ? layoutvm.orignialList :
                (layoutvm.option1 === 2 ? layoutvm.categoryList : []);
        }
        function previous() {
            if (layoutvm.page === 1) { dialogBox("提示信息", "已經是第一頁", null, null); return; }
            layoutvm.page = layoutvm.page - 1;
            if (layoutvm.option1 === 0) {
                getGenericAlarmHistory(true, null, null, null);
                return;
            }
            var temp = [];
            if (layoutvm.selectedList !== null && Array.isArray(layoutvm.selectedList)) {
                layoutvm.selectedList.forEach(function (item, i) {
                    if (item.checked)
                        temp.push(item.value);
                });
            }
            if (layoutvm.option1 === 1) {
                getGenericAlarmHistory(true, null, null, temp);
                return;
            }
            if (layoutvm.option1 === 2) {
                getGenericAlarmHistory(true, null, temp, null);
                return;
            }
            //if (layoutvm.tableDataSource.length === 0) {
            //    layoutvm.genericAlarmList = [];
            //    return;
            //}
            //let dataLength = layoutvm.tableDataSource.length;
            //let startIndex = (layoutvm.page - 1) * layoutvm.pageCount;
            //var count =
            //    (dataLength - layoutvm.pageCount * (layoutvm.page - 1)) > layoutvm.pageCount
            //        ? layoutvm.pageCount
            //        : (dataLength - layoutvm.pageCount * (layoutvm.page - 1));
            //layoutvm.genericAlarmList = layoutvm.tableDataSource.slice(startIndex, startIndex + count);
        }
        function next() {
            //if (layoutvm.option1 !== 0 &&
            //    !(layoutvm.tableDataSource.length > layoutvm.page * layoutvm.pageCount)) {
            //    alert("已是最后一页");
            //    return;
            //}
            if (layoutvm.genericAlarmList.length < layoutvm.pageCount) {
                //alertDialog("已經是最後一頁");
                dialogBox("提示信息", "已經是最後一頁", null, null)
                return;
            }
            layoutvm.page = layoutvm.page + 1;
            if (layoutvm.option1 === 0) {
                getGenericAlarmHistory(true, null, null, null);
                return;
            }

            var temp = [];
            if (layoutvm.selectedList !== null && Array.isArray(layoutvm.selectedList)) {
                layoutvm.selectedList.forEach(function (item, i) {
                    if (item.checked)
                        temp.push(item.value);
                });
            }
            if (layoutvm.option1 === 1) {
                getGenericAlarmHistory(true, null, null, temp);
                return;
            }
            if (layoutvm.option1 === 2) {
                getGenericAlarmHistory(true, null, temp, null);
                return;
            }
            //if (layoutvm.tableDataSource.length === 0) {
            //    layoutvm.genericAlarmList = [];
            //    return;
            //}
            //let dataLength = layoutvm.tableDataSource.length;
            //let startIndex = (layoutvm.page - 1) * layoutvm.pageCount;
            //var count =
            //    (dataLength - layoutvm.pageCount * (layoutvm.page - 1)) > layoutvm.pageCount
            //        ? layoutvm.pageCount
            //        : (dataLength - layoutvm.pageCount * (layoutvm.page - 1));
            //layoutvm.genericAlarmList = layoutvm.tableDataSource.slice(startIndex, startIndex + count);
        }
        function formatTime(timeString) {
            if (timeString === null) {
                return "";
            }
            var currentYear = new Date().getFullYear();

            return (currentYear === new Date(timeString).getFullYear() ? "" : (new Date(timeString).getFullYear() + "-")) + Pad1(new Date(timeString).getMonth()
                + 1, 2) + "-" + Pad1(new Date(timeString).getDate(), 2) + " " + Pad1(new Date(timeString).getHours(), 2) +
                ":" + Pad1(new Date(timeString).getMinutes(), 2);
        }
        function Pad1(num, n) {
            var len = num.toString().length;
            while (len < n) {
                num = "0" + num;
                len++;
            }
            return num;
        }
        function AlarmBarClicked(id) {
            var alarmForm = document.getElementById("alarm_information");
            if (alarmForm === null || alarmForm === undefined) return;
            layoutvm.showAlarmHistoryForm = id === "common_header" ? true : false;
            if (layoutvm.showAlarmHistoryForm) {
                layoutvm.page = 1;
                layoutvm.option1 = 0;
                layoutvm.showFilterForm = false;
                alarmForm.style.visibility = "visible";
                getGenericAlarmHistory(true, null);
            } else {
                alarmForm.style.visibility = "hidden";
            }
        }

        function AckGenericAlarm(alarm) {
            if (alarm === undefined || alarm === null) return;
            var href = window.location.href;
            var path = window.location.pathname;
            let basicUrl = href.slice(0, href.indexOf(path));
            var preAlertMsg = alarm.AckedTimestamp === null ? "靜音" : "解除靜音";

            let serviceUrl = basicUrl + "/u/?apitype=service&an=AckGenericAlarmAsync&pn=ProcessorsDispatcher&en=Edge.Core.Processor.Dispatcher.DefaultDispatcher";
            let parameter = [alarm.Id, preAlertMsg + "from webconsole", alarm.AckedTimestamp === null ? false : true];
            $.ajax({
                url: serviceUrl,
                datatype: "application/json",
                type: 'post',
                contentType: "application/json;charset=utf-8;",
                data: JSON.stringify(parameter),
                beforeSend: function () {
                },
                success: function (data) {
                    console.log(data);
                    if (data === true) {
                        alarm.AckedTimestamp = alarm.AckedTimestamp === null ? " " : null;

                        toAddAlarmAudio();
                        //alertDialog(preAlertMsg + "成功");
                        dialogBox("提示信息", preAlertMsg + "成功", null, null);
                    }
                },
                error: function (err) {
                    //alertDialog(preAlertMsg + "失敗");
                    dialogBox("提示信息", preAlertMsg + "失敗", null, null);
                }
            });
        }

        function closeAlarm(alarm) {
            if (alarm === undefined || alarm === null) return;
            dialogBox("確定問題已解決?", "標記此问题为已经解决,系统不再追踪此问题( 但如果系统再次检测到问题,则仍会发出通知)", function () {
                var href = window.location.href;
                var path = window.location.pathname;
                let basicUrl = href.slice(0, href.indexOf(path));
                let serviceUrl = basicUrl + "/u/?apitype=service&an=CloseGenericAlarmAsync&pn=ProcessorsDispatcher&en=Edge.Core.Processor.Dispatcher.DefaultDispatcher";
                let parameter = [alarm.Id, "從webconsole關結"];
                $.ajax({
                    url: serviceUrl,
                    datatype: "application/json",
                    type: 'post',
                    contentType: "application/json;charset=utf-8;",
                    data: JSON.stringify(parameter),
                    beforeSend: function () {
                    },
                    success: function (data) {
                        console.log(data);
                        if (data === true) {
                            alarm.ClosedTimestamp = new Date();
                            alarm.ClosedReason = "页面手动关闭";
                            toAddAlarmAudio();
                                //removeAlarmAudio();
                            
                            dialogBox("提示信息", "關閉成功", null, null);
                        }
                    },
                    error: function (err) {
                        dialogBox("提示信息", "關閉失敗", null, null);
                    }
                });
            }, null, true);
        }

        function dialogBox(title, message, yesCallback, noCallback) {
            if (message) {
                $('.dialog-title').html(title);
                $('.dialog-message').html(message);
            }
            // 显示遮罩和对话框
            $('.wrap-dialog').removeClass("hide");
            $('.alarmInfoWrap').removeClass("hide");
            // 确定按钮
            $('#confirm').click(function () {
                $('.wrap-dialog').addClass("hide");
                $('.alarmInfoWrap').addClass("hide");
                noCallback = null;
                if (yesCallback !== null && yesCallback !== undefined) {
                    yesCallback();
                    yesCallback = null;
                }
            });
            // 取消按钮
            $('#cancel').click(function () {
                yesCallback = null;
                $('.wrap-dialog').addClass("hide");
                $('.alarmInfoWrap').addClass("hide");
                if (noCallback !== null && noCallback !== undefined) {
                    noCallback();
                    noCallback = null;
                }

            });
        }
        function inputDialog(title, value, yesCallback, noCallback) {
            if (title) {
                $('.input-dialog-title').html(title);
            }
            // 显示遮罩和对话框
            $('.fullScrrenWrap').removeClass("hide");

            $('#input_value').click(function (e) {
                showKeyboard('number', e.currentTarget);
            });
            // 确定按钮
            $('#input_confirm').click(function () {
                $('.fullScrrenWrap').addClass("hide");
                noCallback = null;
                hideKeyboard();
                if (yesCallback !== null && yesCallback !== undefined) {
                    yesCallback($('#input_value')[0].value);
                    $('#input_value')[0].value = "";
                    //var inputValueItem = document.getElementById("input_value");
                    //inputValueItem.value = "";
                    yesCallback = null;
                }
            });
            // 取消按钮
            $('#input_cancel').click(function () {
                yesCallback = null;
                $('.fullScrrenWrap').addClass("hide");
                $('#input_value')[0].value = "";
                hideKeyboard();
                //var inputValueItem = document.getElementById("input_value");
                //inputValueItem.value = "";
                if (noCallback !== null && noCallback !== undefined) {
                    noCallback();
                    noCallback = null;
                }

            });
        }
        function menuItemClicked(menuItem) {
            var displayPopupMenu = false;
            var action = null;
            if (typeof (menuItem.Action) === "object") {
                action = menuItem.Action;
            } else {
                action = menuItem.Action === undefined || menuItem.Action === null ? null : parsJsonStr(menuItem.Action);
            }
            let popUpMenu = null;
            if (action !== null && action.type === "menu" && action.items) {
                if (!bottomPopupMenuVm) return;
                popUpMenu = document.getElementById("common_popupMenu");
                if (popUpMenu && popUpMenu.style.visibility === "visible") {
                    popUpMenu.style.visibility = "hidden";
                    return;
                }
                bottomPopupMenuVm.bottomPopupMenuItems = action.items;
                displayPopupMenu = true;
            }else if (action !== null && action.type === "input") {
                inputDialog(action.prompt, action.value, function (inputText) {
                    if (inputText !== action.value) {
                        dialogBox("提示信息", "輸入信息錯誤!", null, null);
                        return;
                    }
                    window.location = menuItem.LinkUrl;
                }, null);
            } else {
                window.location = menuItem.LinkUrl;
            }
            
            if (popUpMenu) {
                popUpMenu.style.visibility = displayPopupMenu ? "visible" : "hidden";
            }
        }
        function parsJsonStr(jsonStr) {
            var reslut = null
            try {
                reslut = JSON.parse(jsonStr);
            } catch (e) {
                reslut = null;
            }
            return reslut;
        }
        function showAlarmQuery() {
            //alarmsCategoryMap.clear();
            //alarmsOriginalMap.clear();
            layoutvm.orignialList = [];
            layoutvm.categoryList = [];
            getGenericAlarmsSummaryAsync();
            //if (!layoutvm.showFilterForm)
            //    getGenericAlarmHistory(false, null);
            layoutvm.showFilterForm = !layoutvm.showFilterForm;
        }

        function processAlarms(alarmsList) {
            if (alarmsList === null) {
                layoutvm.categoryList = [];
                layoutvm.orignialList = [];
                return;
            }
            alarmsList.forEach(function (alarm, index) {
                if (alarmsCategoryMap.size > 0 && !alarmsCategoryMap.has(alarm.Category) ||
                    alarmsCategoryMap.size === 0) {
                    if (alarm.Category !== null) {
                        let tempArray = new Array();
                        tempArray.push(alarm);
                        alarmsCategoryMap.set(alarm.Category, tempArray);
                        layoutvm.categoryList.push({ checked: false, value: alarm.Category });
                    }
                } else if (alarmsCategoryMap.has(alarm.Category)) {
                    alarmsCategoryMap.get(alarm.Category).push(alarm);
                }
                if (alarmsOriginalMap.size > 0 && !alarmsOriginalMap.has(alarm.OriginatorDisplayName) ||
                    alarmsOriginalMap.size === 0) {
                    if (alarm.OriginatorDisplayName !== null) {
                        let tempArray = new Array();
                        tempArray.push(alarm);
                        alarmsOriginalMap.set(alarm.OriginatorDisplayName, tempArray);
                        layoutvm.orignialList.push({ checked: true, value: alarm.OriginatorDisplayName });
                    }
                } else if (alarmsOriginalMap.has(alarm.OriginatorDisplayName)) {
                    alarmsOriginalMap.get(alarm.OriginatorDisplayName).push(alarm);
                }
            });
        }

        function showQueryReslut() {
            layoutvm.tableDataSource = [];
            layoutvm.page = 1;
            layoutvm.showFilterForm = false;
            //所有
            if (layoutvm.option1 === 0) {
                getGenericAlarmHistory(true, null, null, null);
                return;
            }
            var temp = [];
            if (layoutvm.selectedList !== null && Array.isArray(layoutvm.selectedList)) {
                layoutvm.selectedList.forEach(function (item, i) {
                    if (item.checked)
                        temp.push(item.value);
                });
            }
            if (layoutvm.option1 === 1) {
                getGenericAlarmHistory(true, null, null, temp);
                return;
            }
            if (layoutvm.option1 === 2) {
                getGenericAlarmHistory(true, null, temp, null);
                return;
            }
            ////来源
            //if (layoutvm.option1 === 1) {
            //    layoutvm.selectedList.forEach(function (item, index) {
            //        if (item.checked && alarmsOriginalMap.has(item.value)) {

            //            layoutvm.tableDataSource = layoutvm.tableDataSource.concat(alarmsOriginalMap.get(item.value));
            //        }
            //    });
            //} else if (layoutvm.option1 === 2) {
            //    layoutvm.selectedList.forEach(function (item, index) {
            //        if (item.checked && alarmsCategoryMap.has(item.value)) {

            //            layoutvm.tableDataSource = layoutvm.tableDataSource.concat(alarmsCategoryMap.get(item.value));
            //        }
            //    });
            //}
            //if (layoutvm.tableDataSource.length > 0) {
            //    let count = layoutvm.tableDataSource.length < layoutvm.pageCount ? layoutvm.tableDataSource.length : layoutvm.pageCount;
            //    layoutvm.genericAlarmList = layoutvm.tableDataSource.slice(0, count);
            //} else
            //    layoutvm.genericAlarmList = [];
        }
        const Keyboard = window.SimpleKeyboard.default;
        var currentElement = null;

        const myKeyboard = new Keyboard({
            onChange: input => onChange(input),
            onKeyPress: button => onKeyPress(button),
            layout: {
                'number': [
                    '1 2 3 {bksp}',
                    '4 5 6 {close}',
                    '7 8 9 0'
                ],
                'default': [
                    '{close} 1 2 3 4 5 6 7 8 9 0 - = {bksp}',
                    '{tab} q w e r t y u i o p [ ] \\',
                    '{lock} a s d f g h j k l ; \' {enter}',
                    '{shift} z x c v b n m , . / `',
                    '.com @@ {space}'
                ],
                'shift': [
                    '{close} ! @@ # $ % ^ & * ( ) _ + {bksp}',
                    '{tab} Q W E R T Y U I O P { } |',
                    '{lock} A S D F G H J K L : " {enter}',
                    '{shift} Z X C V B N M < > ? ~',
                    '.com  {space}'
                ]
            },
            display: {
                '{bksp}': 'Backspace',
                '{tab}': 'Tab',
                '{lock}': 'CapsLock',
                '{enter}': 'Enter',
                '{shift}': 'Shift',
                '{close}': 'Close',
                '{space}': 'Space'
            }
        });

        function onChange(input) {
            if (input === "") return;
            var temp = document.querySelector(".input");
            var keyBoardInput = myKeyboard.input;
            var tmp = myKeyboard.getOptions("theme");
            //document.querySelector(".input").value = input;

            if (currentElement !== null) {
                var currentElementValue = currentElement.value;
                if (currentElementValue !== null && currentElementValue !== "") {
                    var selectStart = currentElement.selectionStart;
                    var startValue = currentElementValue.slice(0, selectStart);
                    var endValue = currentElementValue.slice(selectStart);
                    currentElement.value = startValue + input + endValue;
                    currentElement.selectionEnd = currentElement.selectionStart = selectStart + 1;
                } else {
                    currentElement.value = input;
                }
                currentElement.dispatchEvent(new Event('input'))
            }
            myKeyboard.input.default = "";
            //selectionEnd: 5
            //selectionStart: 5
            console.log("Input changed", input);
        }

        function showKeyboard(layout, element) {
            var mydivel = document.getElementById("mydiv");
            if (mydivel === null || mydivel === undefined) return;

            mydivel.className = layout === "number" ? "mydivNumber" : "mydiv";
            if (layout === "number") {
                myKeyboard.setOptions({ theme: "hg-theme-default hg-layout-numeric numeric-theme" });
            } else {
                myKeyboard.setOptions({ theme: "hg-theme-default"});
            }
            currentElement = element;
            myKeyboard.setOptions({ layoutName: layout });
            mydivel.style.visibility = 'visible'
        }
        function hideKeyboard() {
            var keyboardEl = document.getElementById("mydiv");
            if (keyboardEl && keyboardEl.style.visibility === 'visible') {
                keyboardEl.style.visibility = 'hidden';
            }
        }
        function onKeyPress(button) {
            if (button === "{close}") {
                currentElement = null;
                hideKeyboard();
            }
            else if (button === "{shift}") {
                handleShift();
            } else if (button === "{bksp}") {
                if (currentElement === null || currentElement.selectionStart === 0) {
                    return;
                }
                var tempValue = currentElement.value;
                if (myKeyboard.input.default === "" && tempValue !== null && tempValue !== "") {
                    var selectionStart = currentElement.selectionStart;
                    var startValue = tempValue.slice(0, selectionStart-1);
                    var endValue = tempValue.slice(selectionStart);
                    currentElement.value = startValue + endValue;
                    currentElement.dispatchEvent(new Event('input'));
                    currentElement.selectionEnd = currentElement.selectionStart = selectionStart - 1;
                    //currentElement.value = tempValue.slice(0, tempValue.length - 1);
                }
            }
            else
                console.log("Button pressed", button);
        }

        function handleShift() {
            let currentLayout = myKeyboard.options.layoutName;
            let shiftToggle = currentLayout === "default" ? "shift" : "default";
            myKeyboard.setOptions({ layoutName: shiftToggle });
        }

        setInterval(function () {
            var textspan = document.getElementById("common_header_right_text");
            if (textspan != null) {
                var currentDate = new Date();
                var month = (currentDate.getMonth() + 1).toString().length < 2
                    ? "0" + (currentDate.getMonth() + 1).toString()
                    : (currentDate.getMonth() + 1).toString();
                var date = currentDate.getDate() < 10
                    ? "0" + currentDate.getDate().toString()
                    : currentDate.getDate().toString();
                textspan.innerHTML = currentDate.getFullYear() + "/" + month + "/" + date;
            }

        }, 10 * 60 * 1000);
    </script>
</body>
</html>