var prId = -1;
var serverId = -1;
var serverIp; //实时数据服务器的ip
var rtDataServerAddr;
var rtDataServerAddrTemplate = "ws://{ip}:{port}/GetFrameViewRTDataRapidly";
var websocket;
var varList; // 保留原始的点信息
var varInfoList; //实时值的索引
var varValueList; //实时值的dom元素

var locName; //高压侧
var ctValue; //1：高压侧、2：低压侧、3：变压器、4：直流屏
var ddNumber; //201
var varType; //AI DI
var varTypeName; //遥测 遥信
var isDi = false;
var currentType = { // 当前点击查看曲线的数据类型
    index: 1, // 索引
    type: null, // 类型 eg频率
    unit: '', // 单位i
};
var cusId = $api.getStorage('cusId');
var prIdList = [];
times: []; // 存放图表时间轴的值
values: []; // 存放图表每个时刻的历史值
realChart: {}; // 实时数据的图表
realChartOption: {}; // 实时数据图表配置项
/**
 * 显示右侧边栏
 */
function showRightPanel() {
    api.openDrawerPane({
        type: 'right'
    });
}
/**
 * 界面显示完成后的回调
 */
function viewAppear(ret, err) {
    //获取prId
    var powerRoom = $api.getStorage('powerRoom');
    if (powerRoom) {
        // 获取服务器配置
        prId = powerRoom.prId;
        var configId = powerRoom.configId;

        if (!configId || configId < 0) {
            toast("获取配电室信息失败");
            return false;
        }
        //获取serverId
        var url = "/admin/rest/api/config/server/" + configId;
        $api.get(url, {}, function(data, err) {
            if (err) {
                toast("网络请求失败");
            } else {
                if (!data.code || data.code != 200) {
                    toast("服务器响应错误" + (data.code ? ("，错误码：" + data.code) : ""));
                } else {
                    // edit start 2019/12/16 kangzhi
                    // serverIp = data.body.dataServiceIp;
                    // serverPort = data.body.rtPort;
                    serverIp = data.body.realTimeIp;
                    serverPort = data.body.realTimePort;
                    // edit end 2019/12/16 kangzhi
                    rtDataServerAddr = rtDataServerAddrTemplate.replace("{ip}", serverIp).replace("{port}", serverPort);
                    //通知侧栏开始加载数据
                    api.sendEvent({
                        name: "rtDataLoadData"
                    });
                    // 初始化图表
                    initChart();
                }
            }
        });

    } else {
        toast("无法获取配电室相关信息");
    }
}

/**
 * 右侧边栏的筛选条件发生变化
 */
function filterSelectionChanged(ret, err) {
    var result = ret.value;
    locName = result.locName;
    ctValue = result.ctValue;
    ddNumber = result.ddNumber;
    varType = result.varType;
    varTypeName = result.varTypeName;

    $("#btn-location").attr("value", locName);
    $("#btn-ddnumber").attr("value", (ddNumber ? ddNumber : "-"));

    if (varType == "1") {
        isDi = false;
        $('.chart-content').show();
    } else {
        isDi = true;
        $('.chart-content').hide();
    }

    $("#btn-type").attr("value", varTypeName);

    if (ddNumber) {
        //加载实时值的列表
        initVarList();
    } else {
        //该分类下唔调度号
        toast("请选择查询条件");
    }


}

/**
 * 弹出提示框
 */
function toast(msg) {
    api.toast({
        msg: msg,
        duration: 3000,
        locaiton: 'top'
    });
}

/**
 * 根据id清空所有子元素
 */
function clearAllChildren(id) {
    var tobeRemoved = $("#" + id);
    tobeRemoved.empty();
}

/**
 * 初始化变量列表
 */
function initVarList() {
    var tmpVarInfoList = [];
    var tmpVarValueList = [];
    //清空界面上的变量列表
    clearAllChildren("rtlist");

    if (prId < 0) {
        return;
    }
    var url = '/ems/rest/var/page';
    var args;
    if (varType == "1") { //AI
        $("#data-table").removeClass("di-table").addClass("ai-table");
        $("#table-header").removeClass("di-table").addClass("ai-table");
        args = {
            prId: prId,
            ddNum: ddNumber,
            location: ctValue,
            varType: varType,
            page: 1,
            pageSize: 999999
        };

    } else {
        $("#data-table").removeClass("ai-table").addClass("di-table");
        $("#table-header").removeClass("ai-table").addClass("di-table");
        args = {
            prId: prId,
            ddNum: ddNumber,
            location: ctValue,
            varType: varType,
            page: 1,
            pageSize: 999999,
            filterDI: true // 筛选DI点
        };
    }
    api.showProgress({
        title: '数据加载中',
        text: '请稍等',
        modal: true
    });

    $api.get(url, args, function(data, err) {
        api.hideProgress();
        if (err) {
            toast("网络请求失败");
        } else {
            if (!data.code || data.code != "200") {
                toast("服务器响应错误" + (data.code ? ("，错误码：" + data.code) : ""));
            } else {
                var tbody = $("#rtlist"); //表格主体
                if (data.body && data.body.records.length) {
                    $('#empty-tips').hide();
                    varList = data.body.records;
                    var purpose = null;
                    for (var i = 0; i < varList.length; i++) {
                        var element = varList[i];
                        var trDom = '<tr data-index=' + i + '></tr>'
                        var tr = $(trDom);
                        var tdValue = $("<td></td>");
                        var tagName;

                        var cname = element.varCnName;
                        try {

                            var lastSpaceIndex = cname.lastIndexOf(' ');
                            tagName = cname.slice(lastSpaceIndex + 1);

                            if (!purpose) {

                                purpose = cname.slice(0, lastSpaceIndex);
                                //修改用途的名称
                                $("#purpose").text(purpose);
                            }

                        } catch (e) {
                            tagName = '';
                        }

                        tr.append("<td>" + tagName + "</td>");
                        tr.append(tdValue);
                        tr.append("<td>" + (element.unit ? element.unit : "") + "</td>");
                        tr.append("<td class='enableClick view-chart'>点击查看</td>");
                        tbody.append(tr);

                        //保留变量的索引及类型
                        // tmpVarInfoList.push({
                        //     index: element.varIndex,
                        //     type: element.varType
                        // });
                        // add s 2023/8/25
                        var flag = prIdList.indexOf(prId + '') == -1? false : true;
                        if (flag) {
                            tmpVarInfoList.push({
                                index: element.varName,
                                type: element.varType
                            });
                        } else {
                            tmpVarInfoList.push({
                                index: element.varIndex,
                                type: element.varType
                            });
                        }
                        // add e 2023/8/25
                        //保留这个dom元素，当接收实时值的时候使用
                        tmpVarValueList.push(tdValue);


                    }
                    varInfoList = tmpVarInfoList;
                    varValueList = tmpVarValueList;
                    // 默认选中表格中的第一行（AI点）
                    if (varType == 1) {
                        var currentTd = tbody.find('.enableClick').eq(0);
                        currentTd.addClass('disableClick');
                        getCurrentTrData(currentTd);
                    }

                    //初始化WebSocket
                    if (websocket) {
                        //初始化webSocket的索引
                        sendVarInfoList();
                    } else {
                        connectAndInitParams();
                    }

                }else{

                    $('#empty-tips').show();
                }
            }
        }
    });
}

/**
 * 建立WebSocket连接并初始化索引参数
 */
function connectAndInitParams() {
    shutdownWebSocket();
    // add start 2023/8/25
    var flag = prIdList.indexOf(prId + '') == -1? false : true;
    if (flag) { // MQTT 客户使用新实时数据
        rtDataServerAddr = 'wss://cdyapi.saas.dianwutong.com/mqtt/websocket'
    }
    // add end 2023/8/25
    setTimeout(function() {
        websocket = new WebSocket(rtDataServerAddr);
        websocket.binaryType = 'arraybuffer';
        websocket.onopen = onOpen;
        websocket.onerror = onError;
        websocket.onmessage = onMessage;
        websocket.onclose = onClose;
    }.bind(this), 0);
}

/**
 * 断开WebSocket连接
 */
function shutdownWebSocket() {
    try {
        if (websocket) {
            websocket.close();
        }
    } catch (error) {

    }
}

/**
 * 发送初始化webSocket的索引的请求
 */
function sendVarInfoList() {
    try {
        websocket.send(JSON.stringify({
            code: 0,
            Indexs: varInfoList
        }));
    } catch (error) {
        toast(JSON.stringify(error));
    }
}

/**
 * 发送获取变量值的请求
 */
function sendGetVarValueRequset() {
    try {
        websocket.send(JSON.stringify({
            code: 1
        }));
    } catch (error) {
        toast(JSON.stringify(error));
    }
}

/**
 * WebSocket连接建立成功，初始化索引
 * @param {*} evt
 */
function onOpen(evt) {
    times = [];
    values = [];
    sendVarInfoList();
}

/**
 * 对实时数据服务器返回的数据进行解析
 * @param {*} evt
 */
function onMessage(evt) {
    var response = JSON.parse(evt.data);
    if (response.code == 0) {
        for (var i = 0; i < varValueList.length && i < response.Values.length; i++) {
            var domVarValue = varValueList[i];
            if (response.Values[i] != null) {
                if (isDi) {
                    //0是分，1是合

                    domVarValue.html(response.Values[i] < 0.5 ? varList.zeroDefine || '分' : varList.oneDefine || '合');
                } else {
                    domVarValue.html(response.Values[i].toFixed(2));
                }
            } else {
                domVarValue.html("-");
            }

        }
        if(!isDi) {
          // 此时选中类型的value值
          var value = response.Values[currentType.index];
          // 获取图表需要的数据
          getChartData(value);
        }
        setTimeout(sendGetVarValueRequset, 5000); //5秒后再次请求数据
    } else {
        toast("实时数据服务器报告了一个错误，错误码：" + response.code + "，原因：" + response.result);
    }
}

/**
 * 连接断开，5秒后重试连接
 * @param {*} evt
 */
function onError(evt) {
    toast("实时数据连接意外断开，正在重新连接...");
    setTimeout(function() {
        connectAndInitParams();
    }, 5000);
}

function onClose(evt) {

}

/**
 * 应用程序进入后台
 * 断开WebSocket连接
 */
function onPause(ret, err) {
    shutdownWebSocket();
}

/**
 * 应用程序恢复前台
 * 重新连接WebSocket
 */
function onResume(ret, err) {
    connectAndInitParams();
}
// 初始化图表
function initChart() {
    realChartOption = {
        title: {
            show: true,
            text: '',
            left: 'center',
            top: 'top',
            textStyle: {
                fontSize: 14,
                fontWeight: 'normal'
            }
        },
        grid: {
            left: '3%',
            right: '9%',
            bottom: '10%',
            top: "15%",
            containLabel: true
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                animation: false
            },
            position: function(pos, params, el, elRect, size) {
                var obj = {
                    top: 10
                };
                obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
                return obj;
            }
        },
        xAxis: {
            type: 'category',
            splitLine: {
                show: true
            },
            axisTick: {
                inside: true
            },
            boundaryGap: ['0%', '100%'],
            axisLabel: {
              margin:12
            },
            data: []
        },
        yAxis: {
            name: '',
            nameTextStyle: {
              color: '#5a5a5a'
            },
            type: 'value',
            splitLine: {
                show: true
            },
            axisTick: false,
            min: 'dataMin'
        },
        series: []
    }
    realChart = echarts.init(document.getElementById('chart'));
    realChart.setOption(realChartOption);
}

// 根据点击查看曲线按钮 获取相应的索引，类型，单位
function getCurrentTrData(td) {
    values = [];
    times = [];
    var currentTr = td.parent();
    var index = $(currentTr).data('index');
    var tds = $(currentTr).children();
    if (currentType[index] == index) {
        return;
    }
    currentType = {
        index: index,
        type: tds.eq(0).text(),
        unit: tds.eq(2).text()
    }
}

function getChartData(currentValue) {
    if (isNaN(currentValue)) {
        currentValue = 0;
    }
    var time = new Date().getTime();
    var dateUtil = new DateUtils();
    var now = dateUtil.getFormattedDate('MM-dd hh:mm:ss', time);
    now = now.toString();
    var nowArr = now.split(' ');
    now = nowArr[1] +'\n' + nowArr[0];
    // y轴的值
    var data = {
            name: now.toString(),
            value: currentValue
        }
        // 设置title
    realChartOption.title.text = currentType.type;
    // 设置单位
    realChartOption.yAxis.name = '单位: ' + (currentType.unit ? currentType.unit : '无');
    // 设置y轴
    values.push(data);
    realChartOption.series = [{
        name: currentType.type,
        type: 'line',
        showSymbol: false,
        hoverAnimation: false,
        data: values,
        lineStyle: {
          width:1
        }
    }]

    // 设置x轴
    times.push(now);
    realChartOption.xAxis.data = times;
    api.hideProgress();
    realChart.setOption(realChartOption);
}

apiready = function() {
    var ctrl = {
        init: {},
        bind: {}
    }

    ctrl.init = function() {
        this.initLayout();
        // 适配安卓状态栏
        CommonModel.fitInStatusBar();
        ctrl.bind();

        // 获取 MQTT 上线配电室列表
        var url = '/mqtt/tb-mqtt-client/getMqttPr';
            
        $api.get(url, function(res, err) {
            if (err) {
                ctrl.toast("网络请求失败");
                api.hideProgress();
            } else {
                if (!res.code || res.code != "200") {
                    ctrl.toast("服务器响应错误");
                    api.hideProgress();
                } else {
                    prIdList = res.data.split(',');
                    
                    //初始化与边栏的通信事件机制
                    //筛选条件发生变化
                    api.addEventListener({
                        name: 'filterSelectionChanged'
                    }, filterSelectionChanged);
                    //界面显示完成后的回调
                    api.addEventListener({
                        name: 'viewappear'
                    }, viewAppear);
                    api.addEventListener({
                        name: 'pause'
                    }, onPause);
                    api.addEventListener({
                        name: 'resume'
                    }, onResume);
                }
            }
        });

        //初始化与边栏的通信事件机制
        //筛选条件发生变化
        // api.addEventListener({
        //     name: 'filterSelectionChanged'
        // }, filterSelectionChanged);
        // //界面显示完成后的回调
        // api.addEventListener({
        //     name: 'viewappear'
        // }, viewAppear);
        // api.addEventListener({
        //     name: 'pause'
        // }, onPause);
        // api.addEventListener({
        //     name: 'resume'
        // }, onResume);
    }
    ctrl.initLayout = function() {
        var panelHeight = $('#heightHeader').height();
        $('.panel-height').css('height', panelHeight);
        var headerHeight = $('#table-header').height();
        $('.header-height').css('height', headerHeight);
    }
    ctrl.bind = function() {
        //用户点击了返回按钮
        $(".back").on("touchend", function() {
            shutdownWebSocket();
            api.closeWin();
        });

        //用户点击了手机的返回按键
        api.addEventListener({
            name: 'keyback'
        }, function(ret, err) {
            shutdownWebSocket();
            api.closeWin();
        });

        //用户点击了位置按钮
        $("#btn-location").on("touchend", function() {
            showRightPanel();
        });

        //用户点击了调度号按钮
        $("#btn-ddnumber").on("touchend", function() {
            showRightPanel();
        });

        //用户点击了类型按钮
        $("#btn-type").on("touchend", function() {
            showRightPanel();
        });

        //用户点击了筛选按钮
        $("#btn-filter").on("touchend", function() {
            showRightPanel();
        });
        $('#rtlist').on('touchend', '.enableClick', function() {
            $('.view-chart').removeClass('disableClick');
            $(this).addClass('disableClick');
            api.showProgress({
                title: '数据加载中',
                text: '请稍等',
                modal: true
            });

            getCurrentTrData($(this));
        })
    }

    ctrl.init();
}
