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

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

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

        update: function (result) {

            var data = result.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": srvpmc_detaildata_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 == srvpmc_detaildata_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: "#srvpmcvueApp2",
                data: {
                    deviceData: null,
                    realDataSub: null,
                    totalTime: 86400,
                    showSelectRealTag: false,
                    showSelectHistTag: false,
                    wsconecttimes: 0,
                    statusColors: {
                        99:{
                            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 (item) {
                        console.log(item);
                        if(item.value != null){
                            return item.value + item.unit
                        }else{
                            return "--"
                        }
                    }
                },

                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.tags.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)
                        }
                    },
                    setDeviceData: function (allData) {

                        var that = this;
                        that.realdata = false;
                        that.deviceData = {
                            basicInfo: allData.basicInfo,
                            status: allData.status,
                            timeLong: allData.currentTimeLong,
                            tags: allData.tags,
                            statusBar: allData.statusBar || [],
                            srvpmc_detaildata_wsurl: null,
                            online: true,
                            realDataTags: [],
                            trendDataTags: [],
                        }
                        //将参数列表按照实时数据和走势数据分开
                        if (that.deviceData.tags) {
                            var tags = that.deviceData.tags;
                            tags.forEach(item => {
                                if ("true" == item.realData) {
                                    that.deviceData.realDataTags.push(item);
                                }
                                if ("true" == item.trendData) {
                                    that.deviceData.trendDataTags.push(item);
                                }
                            })
                        }

                        // 为了不重复链接,第一次打开页面的时候初始化，之后不再重新设置链接
                        if (that.deviceData.srvpmc_detaildata_wsurl == null) {
                            if (allData.wsurl) {
                                that.deviceData.srvpmc_detaildata_wsurl = allData.wsurl
                                that.realDataSub = new RealDataSub(that.deviceData.srvpmc_detaildata_wsurl)
                            }
                        }
                        that.subRealData();
                        var realData = allData.tagValues;
                        if (realData) {
                            realData.forEach(item => {
                                var tag = that.getMapFromArray(item.code);
                                if (tag) {
                                    tag.value = item.value;
                                    tag.time = item.ts;
                                }
                            })
                        }
                        var seriesData = allData.seriesData;

                        if (seriesData) {
                            seriesData.forEach(item => {
                                var tag = that.getMapFromArray(item.number);
                                if (tag) {
                                    tag.data = item.data;
                                }
                            })
                        }
                        that.drawChart();

                    },
                    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.statusBar;
                        var lastData = statusBar[statusBar.length - 1];
                        if (lastData) {
                            lastData.timelong = (new Date().getTime() - new Date(lastData.begin).getTime()) / 60000
                        }
                        statusBar.push({
                            begin: this.formatTime(new Date(), 0),
                            timelong: 1,
                            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") {
                                    // 属性数据

                                }
                            })
                        }
                    },
                    alarmColor: function (item) {
                        if (item.lower && item.upper) {
                            let value = parseFloat(item.value)
                            let lower = parseFloat(item.lower)
                            let upper = parseFloat(item.upper)
                            if (value < lower || value > upper) {
                                return "#ff0000";
                            }
                        }
                        return "#333333";

                    },
                    colorRgb: function (colorStr) {
                        // 16进制颜色值的正则
                        var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
                        // 把颜色值变成小写
                        var color = colorStr.toLowerCase();
                        if (reg.test(color)) {
                            // 如果只有三位的值，需变成六位，如：#fff => #ffffff
                            if (color.length === 4) {
                                var colorNew = "#";
                                for (var i = 1; i < 4; i += 1) {
                                    colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
                                }
                                color = colorNew;
                            }
                            // 处理六位的颜色值，转为RGB
                            var colorChange = [];
                            for (var i = 1; i < 7; i += 2) {
                                colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
                            }
                            return "RGB(" + colorChange.join(",") + "," + "0.2" + ")";
                        } else {
                            return color;
                        }
                    },
                    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 + "%";
                    },
                    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];
                        }
                    },
                    setAction: function (that, item) {
                        var assetCode = item.deviceId;
                        var values = item.values;
                        values.forEach(row => {
                            var tagName = row.code;
                            var tag = null;
                            for (var i = 0; i < that.deviceData.tags.length; i++) {
                                var item1 = that.deviceData.tags[i]
                                if (item1.assetCode == assetCode && item1.number == tagName) {
                                    tag = item1;
                                    break;
                                }
                            }
                            if (tag) {
                                var ts = that.formatTime(row.ts, 0);
                                var value = row.value;
                                if (tag.status) {
                                    that.setStatusData(value);
                                }

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

                                if (value != "*") {
                                    if (tag.data) {
                                        tag.data.push([ts, value])
                                    } else {
                                        tag.data = [[ts, value]]
                                    }
                                    that.drawChart();
                                }

                            } 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.statusBar;
                            var lastData = statusBar[statusBar.length - 1];
                            that.deviceData.online = true;

                            if (lastData) {
                                lastData.timelong = (onLineTime - new Date(lastData.begin).getTime()) / 60000
                            }
                            statusBar.push({
                                begin: that.formatTime(new Date(onLineTime), 0),
                                timelong: 1,
                                value: that.deviceData.status
                            })
                            srvpmc_detaildata_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 > srvpmc_detaildata_openTime) {
                            that.deviceData.online = false;
                            var statusBar = this.deviceData.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
                            })
                            srvpmc_detaildata_openTime = offlineTime;
                        }
                    },
                    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
                    },
                    checkTag: function (item, i) {
                        if (i == 0) {
                            item.real_checked = !item.real_checked
                        } else {
                            item.series_checked = !item.series_checked
                        }
                        this.drawChart();
                    },
                    toggleFold: function (i, b) {

                        if (i == 0) {
                            this.showSelectRealTag = b == 1;
                        } else {
                            this.showSelectHistTag = b == 1;
                        }
                    },
                    getMapFromArray: function (value, data, key) {
                        data = data || this.deviceData.tags;
                        key = key || "number";
                        var result = null;
                        data.forEach(item => {

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

                    },
                    drawChart: function () {
                        var that = this;
                        var option = {

                            tooltip: {
                                trigger: 'axis',
                                formatter: function (params) {
                                    var tip = "";
                                    params.forEach((item, index) => {
                                        if (index == 0) {
                                            tip += item.axisValueLabel + "<br>"
                                        }
                                        var number = item.seriesName;
                                        var seriesData = that.getMapFromArray(number);
                                        if (seriesData) {
                                            var name = seriesData.name;
                                            tip += (item.marker + name + ":" + item.data[1] + "<br>")
                                        }

                                    })

                                    return tip
                                }
                            },
                            /* dataZoom: [{
                                 type: 'inside',
                                 start: 90,
                                 end: 100
                             },
                                 {
                                     "type": "slider",
                                     "dataBackStyle": {
                                         areaStyle: {
                                             color: 'rgba(220,220,220,30)'
                                         }
                                     }
                                 }],*/
                            grid: {
                                left: "40px"
                            },
                            animation: false, //关闭动画看上去更连贯
                            xAxis: {
                                type: 'time',
                                //   type:'category',
                                axisLine: {
                                    lineStyle: {
                                        color: '#CCCCCC',
                                        fontSize: '12px'
                                    }
                                },
                                splitLine: {
                                    show: false
                                },
                                axisTick: {

                                    show: false,
                                },
                                /* axisLabel: {
                                     formatter: function(value, index) {
                                         var date = new Date(value);
                                         var texts = [date.getHours()];
                                         if (index === 0) {
                                             //texts.unshift(date.getDate()+"日");
                                         }
                                         return texts;
                                     }
                                 }*/
                            },
                            legend: {
                                icon: 'rect',
                                itemWidth: 30,
                                itemHeight: 1,
                                formatter: function (name) {
                                    var item = that.getMapFromArray(name);
                                    return item.name
                                }
                            },
                            yAxis: {
                                type: 'value',
                                axisLabel: {
                                    show: true,
                                    lineStyle: {
                                        color: '#CCCCCC',
                                        fontSize: '12px'
                                    }
                                },
                                splitLine: {
                                    show: true,
                                    lineStyle: {
                                        color: '#F0F0F0',
                                        fontSize: '12px'
                                    }
                                },
                                axisTick: {

                                    show: false,
                                },
                                axisLine: {
                                    lineStyle: {
                                        color: '#CCCCCC',
                                        fontSize: '12px'
                                    }
                                }
                            },
                        }

                        if (!this.myChart) {
                            let timer = setInterval(function () {
                                let elem = document.getElementById("icemdevice-real-data-chart-container2");
                                if (elem) {
                                    clearInterval(timer)
                                    that.myChart = echarts.init(elem);
                                    option.series = getChartSeries();
                                    that.myChart.setOption(option, true);
                                }


                            }, 100)
                        } else {
                            option.series = getChartSeries();
                            this.myChart.setOption(option, true);
                        }

                        /*   function getColor(index) {
                               var colors = [['#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)']];
                               var color = colors[index % colors.length];
                               return color
                           }*/

                        function getChartSeries() {
                            var tags = that.deviceData.trendDataTags;
                            var series = [];

                            tags.forEach((item, index) => {

                                if (!item.series_checked) {
                                    return;
                                }
                                var series1 = {
                                    type: 'line',
                                    name: item.number,
                                    smooth: true,
                                    data: item.data,
                                    color: item.color,
                                    symbol: "none",

                                }
                                series.push(series1);
                            })
                            return series;
                        }
                    }
                }
            });
        },
        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();
                        })
                    })
                })
            })
        }
    };

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