<div id="alNozzlesPage" style="position: relative; width:100%; height:100%;">
    <div id="alNozzles" style="position: absolute;top:2.4%; width:100%; height:88.516%;">
        <div v-for="n in Nozzles" class="NozzleDiv">
            <div class="ALDatas" style="height:55%">
                <div class="NozzleId">{{n.SiteLevelNozzleId}}</div>
                @*<img v-show="n.FuelingState ==='IDLE'" src="/WebConsole/images/smartFuel/idleStatic.png" class="FuelingState" />*@
                @*<img v-show="n.FuelingState ==='FUELING'" src="/WebConsole/images/smartFuel/fuelling.gif" class="FuelingState"/>*@
                <img :src="n.imgsource" class="FuelingState" />

                <img v-show="n.HealthState === 'NORMAL' && n.FuelingState !=='FUELING'" src="~/WebConsole/images/onlineMonitor/nozzleView/NozzleALNormal.png" class="HealthState" />
                <img v-show="n.HealthState === 'WARNING'  && n.FuelingState !=='FUELING'" src="~/WebConsole/images/onlineMonitor/nozzleView/NozzleALWarning.png" class="HealthState" />
                <img v-show="(n.HealthState === 'DISCONNETED'||n.HealthState === 'NOT_SET'||n.HealthState === 'NO_VR') && n.FuelingState !=='FUELING'" src="~/WebConsole/images/onlineMonitor/nozzleView/NozzleALDisconnect.png" class="HealthState" />
                <img v-show="n.HealthState === 'ALARM' && n.FuelingState !=='FUELING'" src="~/WebConsole/images/onlineMonitor/nozzleView/NozzleALAlarm.png" class="HealthState" />
            </div>
            <div class="ALDatas">
                <div class="ALLable">氣</div>
                <div class="ALLableData">{{n.VaporVolumeWithDecimal}}</div>
            </div>
            <div class="ALDatas">
                <div class="ALLable">油</div>
                <div class="ALLableData">{{n.LiquidVolumeWithDecimal}}</div>
            </div>
            <div class="ALDatas">
                <div class="ALLable" style="width:33%;">氣液比</div>
                <div v-if="n.ALIsNormal === true" class="ALLableData" style="width:35%;">{{n.VaporLiquidRatio}}</div>
                <div v-else class="ALLableData" style="width: 35%;color: deeppink;">{{n.VaporLiquidRatio}}</div>
            </div>
        </div>
    </div>
    <div class="tank_filter_div" v-show="smartFuelEnabled" id="toggleSmartFuel" onclick="ToggleSmartFuel()" style="top:0%;bottom:90%;left:95%;background-image: url(/WebConsole/images/onlineMonitor/nozzleView/SmartFuel.png)">
    </div>
</div>
<script>
    var currentPage = 1;
    var oldPage = currentPage;
    var totalPage = 1;
    var maxNozzleNumberInOnePage = 12;
    var alIntervalId = -1;

    //切换至气液比油枪界面
    function ToggleSmartFuel() {
        RenderDiv("/OnlineMonitor/Nozzles", contentDiv, null, null);
    }
    var vm = new Vue({
        el: '#alNozzlesPage',
        data: {
            totalPage: 1,
            Nozzles: [/*{ "SiteLevelNozzleId": 1, "HealthState": "NORMAL", "LatestTrxFlowData": null, "FuelingState": "IDLE" }*/],
            smartFuelEnabled: false,
        },
        methods: {

        },
        mouted() {
        }
    });
    $(document).ready(function () {
        if (vm === undefined) {
            return;
        }

        if (apis.has("GetPumpsLayout")) {
            vm.smartFuelEnabled = true;
        }
        alIntervalId = setInterval(function () {
            console.log("time interval");
            
            if (vm && vm.Nozzles.length === 0) {
                ALNozzlesSubscribeEvents();
            }
        }, 5000);

        if (apis.size > 0 && apis.has("GetVRBoardNozzles")) {
            ALNozzlesSubscribeEvents();
            return;
        }
        
        //var requestData = ["localMqtt", ["在线监测"]];
        ShowMeAPIS(["localMqtt", ["OnlineWatch"]], function () {
            ALNozzlesSubscribeEvents();
        });
        //var serviceUrl = basicUrl + "/u/?apitype=service&an=ShowMeApi&pn=ProcessorsDispatcher&en=Edge.Core.Processor.Dispatcher.DefaultDispatcher";
        //$.ajax({
        //    url: serviceUrl,
        //    datatype: "application/json",
        //    type: 'post',
        //    contentType: "application/json;charset=utf-8;",
        //    data: JSON.stringify(requestData),
        //    beforeSend: function () {
        //    },
        //    success: function (data) {
        //        console.log(data);
        //        data.forEach(function (d) {
        //            if (apis.has(d.ApiName)) {
        //                apis.delete(d.ApiName);
        //            }
        //            apis.set(d.ApiName, d.Path.slice(d.Path.length - 1) === "+" ? d.Path.slice(0, d.Path.length - 1) : d.Path);
        //        });
        //        ALNozzlesSubscribeEvents();
        //    },
        //    error: function (err) {
        //        console.log(err);
        //    }
        //});
    }
    );
    mqttclient.on('connect', function () {
        ALNozzlesSubscribeEvents();
    });
    //mqttclient.on('message', function (topic, message) {
    //    if (apis.size > 0 && apis.has("GetVRBoardNozzles_Reply") && topic === apis.get("GetVRBoardNozzles_Reply")) {
    //        vm.Nozzles = JSON.parse(message.toString());
    //    }
    //});
    function OnReply(apis, topic, jsonObj) {
        if (apis.size > 0 && apis.has("GetVRBoardNozzles_Reply") && topic === apis.get("GetVRBoardNozzles_Reply")) {
            //vm.Nozzles = jsonObj;
            if (!Array.isArray(jsonObj)) {
                console.log("Invalid response GetVRBoardNozzles_Reply");
                return;
            }
            //stop the interval if can receive message from mqtt
            if (alIntervalId !== -1) {
                console.log("stop the interval:" + alIntervalId);
                clearInterval(alIntervalId);
            }
            jsonObj.forEach(function (d) {
                console.log("GetVRBoardNozzles_Reply:" + d.SiteLevelNozzleId + "-" + d.FuelingState);
                d.VaporVolumeWithDecimal = d.LatestTrxFlowData === null ? "" : d.LatestTrxFlowData.VaporVolumeWithDecimal;
                d.LiquidVolumeWithDecimal = d.LatestTrxFlowData === null ? "" : d.LatestTrxFlowData.LiquidVolumeWithDecimal;
                d.VaporLiquidRatio = d.LatestTrxFlowData === null ? "" : d.LatestTrxFlowData.VaporLiquidRatio;
                d.ALIsNormal = d.LatestTrxFlowData === null ? "" : d.LatestTrxFlowData.气液比值是否正常;
                d.imgsource = d.FuelingState === "FUELING" ? "/WebConsole/images/smartFuel/fuelling.gif?a=" + d.SiteLevelNozzleId : (d.FuelingState === "IDLE" ? "/WebConsole/images/smartFuel/idleStatic.png" :"/WebConsole/images/smartFuel/disconnect.png");
            })
            totalPage = Math.ceil(jsonObj.length / maxNozzleNumberInOnePage);
            var dataLength =
                (jsonObj.length - maxNozzleNumberInOnePage * (currentPage - 1)) > maxNozzleNumberInOnePage
                    ? maxNozzleNumberInOnePage
                    : (jsonObj.length - maxNozzleNumberInOnePage * (currentPage - 1));

            vm.Nozzles = jsonObj.sort(sortBySiteLevelNozzleId).slice((currentPage - 1) * maxNozzleNumberInOnePage, (currentPage - 1) * maxNozzleNumberInOnePage + dataLength)
            if (currentPage > totalPage) {
                currentPage = totalPage;
            }
            UpdateFooterPage();
        } else if (apis.size > 0 && apis.has("OnVaporRecoveryDataCollectorBoardNozzleFlowDataRead") && topic === apis.get("OnVaporRecoveryDataCollectorBoardNozzleFlowDataRead")) {
            if (vm.Nozzles.length > 0) {
                vm.Nozzles.forEach(function (n) {
                    if (n.SiteLevelNozzleId === jsonObj.SiteLevelNozzleId) {
                        n.VaporVolumeWithDecimal = jsonObj.VaporVolumeWithDecimal;
                        n.LiquidVolumeWithDecimal = jsonObj.LiquidVolumeWithDecimal;
                        n.VaporLiquidRatio = jsonObj.VaporLiquidRatio;
                        //n.FuelingState = jsonObj.FuellingStartTime === null ? "FUELING" : "IDLE";
                        //n.HealthState = jsonObj.气液比值是否正常 === true ? "NORMAL" : "WARNING";
                        n.ALIsNormal = jsonObj.气液比值是否正常;
                        console.log("OnVaporRecoveryDataCollectorBoardNozzleFlowDataRead-VaporLiquidRatio:" + jsonObj.VaporLiquidRatio);
                    }
                })
            }
        } else if (apis.size > 0 && apis.has("OnVaporRecoveryDataCollectorBoardNozzleStateChange") && topic === apis.get("OnVaporRecoveryDataCollectorBoardNozzleStateChange")) {
            if (vm.Nozzles.length > 0) {
                vm.Nozzles.forEach(function (n) {
                    if (n.SiteLevelNozzleId === jsonObj.SiteLevelNozzleId) {
                        console.log("CollectorBoardNozzleStateChange:" + jsonObj.SiteLevelNozzleId + "-" + jsonObj.FuelingState);
                        n.imgsource = jsonObj.FuelingState === "IDLE" ? ((n.imgsource === "/WebConsole/images/smartFuel/fuelling.gif?a=" + n.SiteLevelNozzleId) ?
                            "/WebConsole/images/smartFuel/Idle.gif?a=" + n.SiteLevelNozzleId : "/WebConsole/images/smartFuel/idleStatic.png") :
                            "/WebConsole/images/smartFuel/fuelling.gif?a=" + n.SiteLevelNozzleId;
                        n.FuelingState = jsonObj.FuelingState;
                        n.HealthState = jsonObj.HealthState;
                    }
                })
            }
        } else if (apis.size > 0 && apis.has("OnVaporRecoveryDataCollectorBoardStateChange") && topic === apis.get("OnVaporRecoveryDataCollectorBoardStateChange")) {
            if (vm.Nozzles.length > 0 && jsonObj !== null) {
                if (jsonObj.State === "UnInit") {
                    jsonObj.Nozzles.forEach(function (bn) {
                        var tempNozzle = vm.Nozzles.find(n => n.SiteLevelNozzleId === bn.SiteLevelNozzleId);
                        if (tempNozzle !== undefined)
                            tempNozzle.imgsource = "/WebConsole/images/smartFuel/disconnect.png";
                    });
                } else if (jsonObj.State === "Initialized") {
                    jsonObj.Nozzles.forEach(function (bn) {
                        var tempNozzle = vm.Nozzles.find(n => n.SiteLevelNozzleId === bn.SiteLevelNozzleId);
                        //tempNozzle.imgsource = "/WebConsole/images/smartFuel/disconnect.png";
                        if (tempNozzle !== undefined && tempNozzle.imgsource === "/WebConsole/images/smartFuel/disconnect.png")
                            tempNozzle.imgsource = "/WebConsole/images/smartFuel/idleStatic.png";
                    });
                }
            }
        }
    }
    //In ascending order of site level nozzle Id
    function sortBySiteLevelNozzleId(n1, n2) {
        if (n1.SiteLevelNozzleId < n2.SiteLevelNozzleId)
            return -1;
        else
            return 1;
    }
    function ALNozzlesSubscribeEvents() {
        if (!mqttclient.connected || apis.size === 0) {
            console.log("ALNozzlesSubscribeEvents:client is not connected or haven't got APIS");
            return;
        }
        if (apis.has("GetVRBoardNozzles_Reply")) {
            mqttclient.subscribe(apis.get("GetVRBoardNozzles_Reply"), function (err) {
                if (!err) {
                    mqttclient.publish(apis.get("GetVRBoardNozzles"));
                }
            });
        }
        if (apis.has("OnVaporRecoveryDataCollectorBoardNozzleFlowDataRead")) {
            mqttclient.subscribe(apis.get("OnVaporRecoveryDataCollectorBoardNozzleFlowDataRead"), function (err) {
                if (!err) {
                    console.log("subscribe OnVaporRecoveryDataCollectorBoardNozzleFlowDataRead successfully");
                }
            });
        }
        if (apis.has("OnVaporRecoveryDataCollectorBoardNozzleStateChange")) {
            mqttclient.subscribe(apis.get("OnVaporRecoveryDataCollectorBoardNozzleStateChange"), function (err) {
                if (!err) {
                    console.log("subscribe OnVaporRecoveryDataCollectorBoardNozzleStateChange successfully");
                }
            });
        }
        if (apis.has("OnVaporRecoveryDataCollectorBoardStateChange")) {
            mqttclient.subscribe(apis.get("OnVaporRecoveryDataCollectorBoardStateChange"), function (err) {
                if (!err) {
                    console.log("subscribe OnVaporRecoveryDataCollectorBoardStateChange successfully");
                }
            });
        }
    }
    function UpdateFooterPage() {
        if (document.getElementById("PumpsPage_Bottom_pages") != null) {
            for (var p = 1; p < 6; p++) {
                var imgCurrentPageIdStr = "PumpsPage_Bottom_pages_img_" + p;
                var imgCurrentPageNotShowedIdStr = "PumpsPage_Bottom_pages_notshowed_img_" + p;
                if (p > totalPage) {
                    if (document.getElementById(imgCurrentPageIdStr) != null)
                        document.getElementById(imgCurrentPageIdStr).style.visibility = "hidden";
                    if (document.getElementById(imgCurrentPageNotShowedIdStr) != null)
                        document.getElementById(imgCurrentPageNotShowedIdStr).style.visibility = "hidden";
                } else if (p === currentPage || (p === 5 && currentPage > p)) {
                    if (document.getElementById(imgCurrentPageIdStr) != null)
                        document.getElementById(imgCurrentPageIdStr).style.visibility = "visible";
                    if (document.getElementById(imgCurrentPageNotShowedIdStr) != null)
                        document.getElementById(imgCurrentPageNotShowedIdStr).style.visibility = "hidden";
                } else {
                    if (document.getElementById(imgCurrentPageIdStr) != null)
                        document.getElementById(imgCurrentPageIdStr).style.visibility = "hidden";
                    if (document.getElementById(imgCurrentPageNotShowedIdStr) != null)
                        document.getElementById(imgCurrentPageNotShowedIdStr).style.visibility = "visible";
                }
            }
            //update next page img position
            var nextPageImg = document.getElementById("PumpsPage_Bottom_pages_img_next_page");
            var previousPageImg = document.getElementById("PumpsPage_Bottom_pages_img_previous_page");
            if (previousPageImg != null) {
                //previousPageImg.style.visibility = (totalPage === 1 || currentPage === 1) ? "hidden" : "visible";
                previousPageImg.style.visibility = "visible";
            }
            if (nextPageImg != null) {
                //if (totalPage < 5)
                nextPageImg.style.left = (16.5 * totalPage + 5).toString() + "%";
                nextPageImg.style.visibility = "visible";
                //nextPageImg.style.visibility = (totalPage === 1 || currentPage === totalPage) ? "hidden" : "visible";
            }
        }
    }
    //显示前一页
    function ShowPreviousPage() {
        if (currentPage === 1) {
            //alert("已经是第一页!");
            dialogBox("提示信息", "已經是第一頁",null,null);
            return;
        }
        currentPage--;
        if (apis.has("GetVRBoardNozzles_Reply")) {
            mqttclient.subscribe(apis.get("GetVRBoardNozzles_Reply"), function (err) {
                if (!err) {
                    mqttclient.publish(apis.get("GetVRBoardNozzles"));
                }
            });
        }
    }
    //显示下一页
    function ShowNextPage() {
        if (currentPage === totalPage) {
            //alert("已经是最后一页!");
            dialogBox("提示信息", "已經是最後一頁",null,null);
            return;
        }
        currentPage++;
        if (apis.has("GetVRBoardNozzles_Reply")) {
            mqttclient.subscribe(apis.get("GetVRBoardNozzles_Reply"), function (err) {
                if (!err) {
                    mqttclient.publish(apis.get("GetVRBoardNozzles"));
                }
            });
        }
    }
</script>
<style scoped>
    .HealthState {
        position: absolute;
        right: 2%;
        bottom: 4%;
        width: 20%;
        height: 25%;
    }

    .FuelingState {
        position: absolute;
        top: 0%;
        left: 0%;
        width: 100%;
        height: 100%;
    }

    .NozzleId {
        position: absolute;
        top: 0%;
        left: 0%;
        width: 100%;
        height: 15%;
        text-align: left;
        font-size: 1.375rem;
        font-weight: bold;
        /*border: 1px solid#ff0000*/
    }

    .NozzleDiv {
        position: relative;
        float: left;
        margin: 1%;
        width: 14.66%;
        height: 48%;
        /*border: 1px solid#ff0000;*/
    }
    .ALLable {
        position: relative;
        float: left;
        /*width: 15%;*/
        margin-left:12%;
        width: 33%;
        height: 100%;
        text-align: left;
        font-size: 1.1rem;
        font-weight: bold;
        /*border: 1px solid#ff0000;*/
    }
    .ALLableData {
        position: relative;
        float: left;
        /*width: 85%;*/
        width: 35%;
        height: 100%;
        text-align: right;
        font-size: 1.1rem;
        font-weight: bold;
        /*color:#808080;*/
        /*border: 1px solid#ff0000;*/
    }
    .ALDatas {
        position: relative;
        width: 100%;
        height: 15%;
        /*border: 1px solid#ff0000;*/
    }
</style>