/* 此函数只有初次加载js的时候才会执行一次
    直至清除缓存后
  */
(function (KDApi, $) {
    var srvemc_realdata_topic = "getdetaildata";
    var srvemc_realdata_openTime = new Date().getTime();

    function MyComopnent(model) {
        this._setModel(model);
        this.vueInstance = null;


    }

    MyComopnent.prototype = {
        _setModel: function (model) {
            this.model = model;
            controller.setModel(model);
        },
        init: function () {
            srvemc_realdata_openTime = new Date().getTime();
            this.initHtml(this.model);
            // this.resetOriginPageStyle();
        },

        update: function (result) {

            var data = result.data;
            console.log("================update===================");
            console.log(data);
            if (!data) {
                return;
            }
            var that = this;

            let timer = setInterval(function () {
                if (that.vueInstance) {
                    clearInterval(timer);
                    that.vueInstance.setDeviceData(data);
                }
            }, 100)

        },
        destoryed: function () {

        },

        initVue: function () {
            function RealDataSub(url) {
                try {
                    this.ws = new WebSocket(url);
                    console.log("实时启动连接")
                } catch (error) {
                    console.error("实时连接失败")
                }

            }


            RealDataSub.prototype.connect = function (url) {
                this.ws = new WebSocket(url);
            }
            RealDataSub.prototype.leave = function () {

            }
            RealDataSub.prototype.keepalive = function () {
                if (this.ws) {
                    var msg = {
                        "type": "ping"
                    }
                    if (this.ws.readyState == 1) {
                        this.ws.send(JSON.stringify(msg));
                    } else {
                        this.ws.onopen = function () {
                            this.ws.send(JSON.stringify(msg));
                        }
                    }
                }
            }
            RealDataSub.prototype.sub = function (data, callback, errorback) {
                //一个客户端只能订阅一个参数
                var that = this;
                if (!this.ws) {
                    callback && callback({code: "401"})
                    return;
                }
                var msg = {
                    "topic": srvemc_realdata_topic,
                    "type": "sub",
                    "deviceIds": data.devices || [],
                    "content": {
                        "action": data.actions || [],
                        "on_line": [],
                        "down_line": []
                    },
                }
                if (this.ws.readyState == 1) {
                    that.ws.send(JSON.stringify(msg));
                } else {
                    this.ws.onopen = function () {
                        //that.leave();
                        that.ws.send(JSON.stringify(msg));
                    }
                }
                that.ws.onmessage = function (evt) {
                    var received_msg = JSON.parse(evt.data);
                    if (received_msg && received_msg.topic == srvemc_realdata_topic) {
                        var data = received_msg.data;
                        callback && callback(data);
                    } else if (received_msg.data == "pong") {
                        callback(received_msg)
                    } else {
                        console.log(evt)
                    }
                };
            }

            this.vueInstance = new Vue({
                el: "#srvemcvueAPP3",
                data: {
                    deviceData: null,
                    realDataSub: null,
                    totalTime: 86400,
                    statusColors: {
                        99: {
                            name: '未连接同步IOT',
                            color: '#eeeeee',
                        },
                        3: {
                            name: '停机',
                            color: '#FF716A',
                            background: "linear-gradient(142deg,#ffaaa3 0%, #ff716a 96%)",
                        },
                        1: {
                            name: '运行',
                            color: '#41C193',
                            background: "linear-gradient(142deg,#55e2af 5%, #41c193 95%)"
                        },
                        2: {
                            name: '空闲',
                            color: '#FFAD57',
                            background: "linear-gradient(142deg,#ffbf6d 5%, #ff8e2f 95%)"
                        },
                        0: {
                            name: '离线',
                            color: '#969696',
                            background: "linear-gradient(142deg,#d6d6d6 5%, #969696 95%)"
                        }

                    },
                    colorList: [['#648CF9', 'rgba(100,140,249,0.20)'], ['#2EC6C8', 'rgba(46,198,200,0.20)'], ['#FC8555', 'rgba(252,133,85,0.20)'], ['#FFBA30', 'rgba(255,186,48,0.20)']]
                },

                filters: {
                    showValue: function (value, unit) {
                        if (value == "--") {
                            return value;
                        }
                        return value + " " + unit;
                    }
                },

                methods: {
                    buildSocketReq: function (topic, message) {
                        var a = {
                            topic: topic,
                            message: message || ""
                        };
                        return JSON.stringify(a)
                    },
                    subRealData: function () {
                        var that = this;
                        if (this.realDataSub != null) {
                            var devices = [];
                            var actions = [];
                            this.deviceData.tagList.forEach(function (item) {
                                if (devices.indexOf(item.assetCode) < 0) {
                                    devices.push(item.assetCode)
                                }

                                var tags = {
                                    "code": item.number,
                                    "expression": "has"
                                }
                                actions.push(tags)
                            });
                            this.realDataSub.sub({
                                "devices": devices,
                                "properties": [],
                                "actions": actions
                            }, this.messageHandle);
                            setTimeout(function () {
                                that.realDataSub.keepalive();
                            }, 60 * 1000)
                        }

                        // this.deviceStatusSub.sub(devices,this.statusMessageHandle)
                    },
                    setDeviceData: function (allData) {
                        var that = this;
                        console.log("================");
                        console.log(allData.basicInfo);
                        console.log("================");
                        that.deviceData = {
                            basicInfo: allData.basicInfo,
                            statusInfo: allData.statusInfo,
                            tagList: allData.tagList || [],
                            status: allData.statusInfo.currentStatus,
                            timeLong: allData.statusInfo.currentTimeLong,
                            online: true,
                            srvemc_realdata_wsurl: null
                        }

                        // 为了不重复链接,第一次打开页面的时候初始化，之后不再重新设置链接
                        if (that.deviceData.srvemc_realdata_wsurl == null) {
                            if (allData.wsurl) {
                                that.deviceData.srvemc_realdata_wsurl = allData.wsurl
                                that.realDataSub = new RealDataSub(that.deviceData.srvemc_realdata_wsurl)
                            }
                        }
                        that.subRealData();

                        var realData = allData.tagValues;
                        if (realData) {
                            realData.forEach(item => {
                                var tag = that.getMapFromArray(item.code);
                                if (tag) {
                                    var values = item.values;
                                    while (values.length < 3) {
                                        values.push({value: "--", ts: ''})
                                    }
                                    tag.values = values;
                                }
                            })
                        }
                    },
                    setRadius: function (index) {
                        if (index === 0) {
                            return "25%";
                        }
                        return "0%";
                    },
                    clickProgress(e, data, index) {
                        if (this.progressIndex != undefined) {
                            let box = document.getElementById('mouse' + this.progressIndex);
                            box.style.display = 'none';
                        }
                        if (this.progressIndex == index) {
                            this.progressIndex = undefined;
                            let box = document.getElementById('mouse' + this.progressIndex);
                            box.style.display = 'none';
                            return
                        }
                        const rect = e.target.getBoundingClientRect()//获取点击的dom的位置
                        console.log(rect)
                        let showDiv = document.getElementById('mouse' + index);
                        this.progressIndex = index;
                        showDiv.style = 'background-color:rgba(0,0,0,0.6);padding: 8px 8px;';
                        showDiv.style.width = '134px'
                        showDiv.style.height = '64px'
                        showDiv.style.borderRadius = '4px'
                        showDiv.style.position = 'relative'
                        showDiv.style.textAlign = 'left'
                        showDiv.style.top = (0 - 74) + "px"
                        showDiv.style.left = (rect.width / 2) + "px"
                        showDiv.style.display = 'block'
                        let time = data.timeLong;
                        let keyValue = this.statusColors[data.value].name;
                        let start = this.formatTodayDate(data.begin);
                        let end = this.formatTodayDate(data.end);
                        let html = "<p style='color: white; font-size: 14px'>" + keyValue + time + "h" + "</p>";
                        let html2 = "<p style='color: white; font-size: 14px; margin-top: 2px'>" + start + "~" + end + "</p>" + "<div class='triangle-bottom'></div>";
                        showDiv.innerHTML = html + html2;
                        // setTimeout(() => this.init(), 5000);
                    },
                    init: function () {
                        let box = document.getElementById('mouse' + this.progressIndex);
                        box.style.display = 'none';
                    },
                    widthStop: function (item) {
                        let {getPercentage, totalTime} = this;
                        let time = parseFloat(item.timeLong);
                        console.log(getPercentage(parseFloat(item.timeLong), totalTime));
                        return getPercentage(time, totalTime);
                    },
                    getPercentage: function (num, total) {
                        return num * 3600 / total * 100 + "%";
                    },
                    getMapFromArray: function (value, data, key) {
                        data = data || this.deviceData.tagList;
                        key = key || "number";
                        var result = null;
                        data.forEach(item => {

                            if (item[key] == value) {
                                result = item;
                            }
                        })
                        return result;

                    },
                    setStatusData: function (value) {
                        value = parseInt(value);
                        if (isNaN(value) || value > 3 || value < 0) {
                            value = 0;
                        }
                        value = value + ""
                        this.deviceData.status = value;
                        if (!this.deviceData.online) {
                            return;
                        }
                        var statusBar = this.deviceData.statusInfo.statusBar;
                        var lastData = statusBar[statusBar.length - 1];
                        if (lastData) {
                            var time = (new Date().getTime() - new Date(lastData.begin).getTime()) / (60 * 60 * 1000)
                            lastData.timeLong = time.toFixed(2)
                        }
                        statusBar.push({
                            begin: this.formatTime(new Date(), 0),
                            timeLong: (10 / 3600).toFixed(2), //默认给10s,保留两位小数
                            value: value
                        })
                    },
                    messageHandle: function (message) { // 订阅实时消息处理
                        var that = this;
                        if (message.data == "pong") {
                            if (message.success) {
                                that.wsconecttimes = 0;
                                setTimeout(function () {
                                    that.realDataSub.keepalive();
                                }, 60 * 1000)
                            } else {
                                // 如果失败重连3次
                                if (that.wsconecttimes < 3) {
                                    that.wsconecttimes++;
                                    that.subRealData();
                                }

                            }
                            return;
                        }
                        if (message) {
                            if (!Array.isArray(message)) {
                                return;
                            }
                            message.forEach(item => {
                                var functiontype = item.functionType;

                                if (functiontype == "action") {
                                    //行为数据
                                    that.setAction(that, item);
                                } else if (functiontype == "on_line") {
                                    // 上线事件
                                    that.setOnLine(that, item)
                                } else if (functiontype == "down_line") {
                                    // 下线事件
                                    that.setOffLine(that, item)
                                } else if (functiontype == "properties") {
                                    // 属性数据

                                }
                            })
                        }
                    },
                    toHistoryTrend: function (basicInfo, tag) {
                        // model.invoke，用于给后端发送请求，第一个参数是事件名，可自定义；第二个参数是发送给后端的数据，可以是任意类型
                        let param = {
                            customer: basicInfo.customer,
                            device: basicInfo.id,
                            tagNumber: tag.number
                        }
                        controller.toHistoryTrend(param);
                    },
                    setAction: function (that, item) {
                        var assetCode = item.deviceId;
                        var values = item.values;
                        values.forEach(row => {
                            var tagName = row.code;
                            var tag = null;
                            var index = 0;
                            for (var i = 0; i < that.deviceData.tagList.length; i++) {
                                var item1 = that.deviceData.tagList[i]
                                if (item1.assetCode == assetCode && item1.number == tagName) {
                                    tag = item1;
                                    index = i;
                                    break;
                                }
                            }
                            if (tag) {
                                var ts = that.formatTime(row.ts, 0);
                                var value = row.value;
                                if (tag.status) {
                                    that.setStatusData(value);
                                }

                                //增加属性不会改变界面不会改变
                                Vue.set(tag, "ts", ts);
                                Vue.set(tag, "value", value);

                                var values = tag.values;
                                if (value && values.length == 3 && values[0].value != value) {
                                    values.pop();
                                    values.unshift({value: value, ts: ts})
                                }

                                //增加属性不会改变界面不会改变
                                Vue.set(that.deviceData.tagList, index, tag)

                            } else {
                                console.error("tag is null")
                            }
                        })

                    },
                    setOnLine: function (that, item) {
                        var values = item.values;
                        var onLineTime = null;
                        values.some(row => {
                            if (row.code == "onLineTime") {
                                onLineTime = row.value;
                                return true;
                            }
                        })

                        if (onLineTime) {
                            var statusBar = that.deviceData.statusInfo.statusBar;
                            var lastData = statusBar[statusBar.length - 1];
                            that.deviceData.online = true;

                            if (lastData) {
                                lastData.timeLong = (onLineTime - new Date(lastData.begin).getTime()) / (1000 * 60 * 60)
                            }
                            statusBar.push({
                                begin: that.formatTime(new Date(onLineTime), 0),
                                timeLong: 0,
                                value: that.deviceData.status
                            })
                            srvemc_realdata_openTime = onLineTime;
                        }
                    },
                    setOffLine: function (that, item) {
                        var values = item.values;
                        var sessionStartTime = null;
                        var sessionOnLineTime = null;
                        values.forEach(row => {
                            if (row.code == "sessionStartTime") {
                                sessionStartTime = row.value;
                            }
                            if (row.code == "sessionOnLineTime") {
                                sessionOnLineTime = row.value;
                            }
                        })
                        // 离线开始时间 = session开始时间 + 它存活的时间
                        var offlineTime = Number(sessionStartTime) + Number(sessionOnLineTime);
                        if (offlineTime > srvemc_realdata_openTime) {
                            that.deviceData.online = false;
                            var statusBar = this.deviceData.statusInfo.statusBar;
                            var lastData = statusBar[statusBar.length - 1];
                            if (lastData) {
                                lastData.timeLong = (offlineTime - new Date(lastData.begin).getTime()) / 60000
                            }
                            statusBar.push({
                                begin: this.formatTime(new Date(offlineTime), 0),
                                timeLong: 1,
                                value: 0
                            })
                            srvemc_realdata_openTime = offlineTime;
                        }
                    },
                    alarmColor: function (tag, tagValues) {
                        if (tag.lower && tag.upper) {
                            let value = parseFloat(tagValues.value)
                            let lower = parseFloat(tag.lower)
                            let upper = parseFloat(tag.upper)
                            if (value < lower || value > upper) {
                                return "#ff0000";
                            }
                            return "#666666";
                        }
                    },
                    formatTodayDate: function (ts) {
                        if (ts == null) {
                            return "--"
                        } else {
                            var timeArr = ts.split(' ');
                            var day = timeArr[1];
                            let dayArr = day.split(':');
                            return dayArr[0] + ":" + dayArr[1];
                        }
                    },
                    formatTime: function (ts, h) {
                        let tdate = null;
                        try {
                            tdate = new Date(ts.replace("T", " ").slice(0, 19));
                        } catch (error) {

                        }
                        if (!tdate || isNaN(tdate.getHours())) {
                            tdate = new Date();
                        }
                        tdate.setHours(tdate.getHours() + h);
                        var strDate = [tdate.getFullYear(), tdate.getMonth() + 1, tdate.getDate()].map(item => {
                            item = item + "";
                            return item.length > 1 ? item : '0' + item
                        }).join("-") + " " + [tdate.getHours(), tdate.getMinutes(), tdate.getSeconds()].map(item => {
                            item = item.toString();
                            return item.length > 1 ? item : '0' + item
                        }).join(":");
                        return strDate
                    }
                }
            });
        },
        resetOriginPageStyle: function () {//重写原页面的样式

            var container = $("#selfcontrol_container");
            var times = 0;
            var timer1 = setInterval(
                function () {
                    if (times > 10) {
                        clearInterval(timer1);
                    }
                    times++;
                    $("#treevew_comtainer>div").css("height", $("#treevew_comtainer").parent().parent().height() - 60 + "px");
                    $("#selfcontrol_container").css("height", $("#selfcontrol_container").parent().height() + "px");
                    $("#selfcontrol_container").css("width", $("#selfcontrol_container").parent().width() - 280 + "px");

                }, 300);


        },


        initHtml: function (model) {
            var that = this;
            KDApi.loadFile(['./css/main.css'], model.schemaId, function () {
                KDApi.loadFile(['./lib/echarts.min.js'], model.schemaId, function () {
                    KDApi.loadFile(['./lib/vue.min.js'], model.schemaId, function () {
                        KDApi.templateFilePath('./html/main.html', model.schemaId, {}).then(function (result) {
                            model.dom.innerHTML = result;
                            that.initVue();
                        })
                    })
                })
            })
        }
    };
    var controller = {
        setModel: function (model) {
            this.model = model;
        },
        toHistoryTrend: function (param) {
            this.model.invoke("toHistoryTrend", param);
        },
    }

    KDApi.register("srvemcdevice_real_data_new", MyComopnent);
})(KDApi, jQuery);
