apiready = function() {
    var ctrl = {
        prId: null, // 配电室id
        startTime: null, // 查询历史数据的开始时间
        endTime: null, // 查询历史数据的结束时间
        ddNum: null, // 调度号
        location: null, // 位置
        interval: null, // 频率
        dataList: {}, // 数据列表
        init: {},
        bind: {}
    }
    ctrl.init = function() {
        // 适配安卓状态栏
        CommonModel.fitInStatusBar();
        // 初始化表格容器的高度
        var winHeight = api.winHeight;
        var winWidth = api.winWidth;
        var headerHeight = $("#header").height() + $('.heightGap').height();
        var tableHeight = winHeight - headerHeight;
        $("#table-panel").height(tableHeight);
        $("#table-panel").css("top", headerHeight + "px");

        //计算table-head-right的宽度和位置
        var tableHeadLeftWidth = $("#table-head-left").width() - 1; //由于四舍五入 可能多出1像素  -1 保证没有缝隙
        $("#table-head-right").width(winWidth - tableHeadLeftWidth);
        $("#table-head-right").css("left", tableHeadLeftWidth + "px");

        //算出table-body的高度和位置
        var tableHeadHeight = $("#table-head").height();
        var tableBodyHeight = tableHeight - tableHeadHeight;

        $("#table-body").height(tableBodyHeight);
        $("#table-body").css("top", (tableHeadHeight + 3) + "px"); //3像素的border
        $("#table-body-left").height(tableBodyHeight);
        $("#table-body-right").css("left", tableHeadLeftWidth + "px");
        $("#table-body-right").height(tableBodyHeight);
        $("#table-body-right").width(winWidth - tableHeadLeftWidth);
        ctrl.initParam();
        ctrl.bind();
        ctrl.getData();
    }

    // 初始化调取历史数据所需要的参数
    ctrl.initParam = function() {
        ctrl.prId = $api.getStorage('powerRoom').prId; // 获取配电室id
        ctrl.cusRoleType = $api.getStorage('cusRoleType'); // 获取客户角色id
        ctrl.location = api.pageParam.location; // 获取location
        ctrl.ddNum = api.pageParam.ddNum; // 获取调度号
        ctrl.interval = 2 * 60 * 60; // 以秒为单位，目前默认是两个小时
        // 获取获取历史数据所需的起止时间和结束时间 目前默认是查看前一天的00
        var currentTime = api.pageParam.time - 1 * 24 * 60 * 60 * 1000; // 推送时间 - 1 = 前一天的时间戳
        var dateUtil = new DateUtils();
        dateUtil.setDate(currentTime);
        ctrl.startTime = dateUtil.getMillisecondOfDate();
        ctrl.endTime = dateUtil.getMillisecondOfDateEnd();

        $('#title').text(POSITIONCLASSIFY[ctrl.location] + ctrl.ddNum + '报表');
    }
    ctrl.bind = function() {
            //用户点击了返回按钮
            $(".back").on("touchend", function() {
                api.closeWin();
            });
            //阻止ios的返回事件
            api.addEventListener({
                name: 'swiperight'
            }, function(ret, err) {
                return false;
            });
            //监听表的滚动事件 同步各区域滚动
            $("#table-body-right").on("scroll", function() {
                var top = $(this).scrollTop();
                var left = $(this).scrollLeft();
                $("#table-body-left").scrollTop(top);
                $("#table-head-right").scrollLeft(left);
            })

            $("#table-body-left").on("scroll", function() {
                var top = $(this).scrollTop();
                $("#table-body-right").scrollTop(top);

            })

            $("#table-head-right").on("scroll", function() {
                var left = $(this).scrollLeft();
                $("#table-body-right").scrollLeft(left);

            })

        }
        /**
         * 弹出提示框
         */
    ctrl.toast = function(msg) {
            api.toast({
                msg: msg,
                duration: 5000,
                locaiton: 'top'
            });
        }
        // 请求历史数据
    ctrl.getData = function() {
            //显示载入动画
            api.showProgress({
                title: '载入中...',
                text: '请稍后',
                modal: false
            });
            //var url = '/edp/rest/data/history';
            var url = '/edp/rest/data/report/ai/history'
            var args = {
                flag: 2, // 1: 查询历史数据 2: 查询报表数据
                cusRoleType: ctrl.cusRoleType,
                prId: ctrl.prId,
                ddNum: ctrl.ddNum,
                location: ctrl.location,
                interval: ctrl.interval,
                startTime: ctrl.startTime,
                endTime: ctrl.endTime
            };
            $api.get(url, args, function(data, err) {
                //隐藏载入动画
                api.hideProgress();
                if (err) {
                    ctrl.toast('网络请求失败');
                } else {
                    if (!data.code || data.code != 200) {
                        ctrl.toast("服务器响应错误" + (data.code ? ("，错误码：" + data.code) : ""));
                    } else {
                        if (data.body && data.body.timeList && data.body.timeList.length && data.body.categories) {
                            ctrl.dataList = data.body;
                            // 渲染时间列
                            ctrl.renderTime();

                            // 渲染表头
                            ctrl.renderTableHeader();

                            // 渲染表格里的数值

                            ctrl.renderValue();

                            $('#empty-tips').hide();
                            $('.heightGap').show();
                            $('#table-panel').show();
                        } else {
                            $('#table-panel').hide();
                            $('.heightGap').hide();
                            $('#empty-tips').show();
                        }
                    }
                }
            })

        }
        // 渲染表格时间列
    ctrl.renderTime = function() {
        var list = ctrl.dataList.timeList;
        // 首先清空时间列
        $('#timeColumn').empty();
        for (var i = 0; i < list.length; i++) {
            var dateUtil = new DateUtils();
            dateUtil.setDate(list[i]);
            var time = dateUtil.getFormattedDate('MM-dd hh:mm:ss');
            var template = '<tr><td>{time}</td></tr>';
            template = template.replace("{time}", time);
            $("#timeColumn").append(template);

        }

    }

    // 渲染表头
    ctrl.renderTableHeader = function() {
        // 清空表头
        $('#table-header-list').empty();
        $('#table-title-list').empty();
        $('#header-table').width(0);
        var list = ctrl.dataList.categories;
        for (var i = 0; i < list.length; i++) {
            var headerItem = list[i];
            var templateHead = '<td colspan="{col}">{name}</td>';
            templateHead = templateHead.replace("{col}", headerItem.vars.length);
            templateHead = templateHead.replace("{name}", headerItem.categotyName);

            $("#table-header-list").append(templateHead);

            var templateTitle = '<td>{title}</td>';
            var titleList = $("#table-title-list");
            for (var j = 0; j < headerItem.vars.length; j++) {
                var item = headerItem.vars[j];
                var title = item.tagKey + (item.unit ? '(' + item.unit + ')' : '');
                titleList.append(templateTitle.replace("{title}", title));
            }
        }

    }

    // 渲染表格里的数值

    ctrl.renderValue = function() {
        //清空表格中的值
        $('#tbHistroyValue').empty();
        var historyValueTable = $("#tbHistroyValue");
        historyValueTable.width(0);
        var rowCount = ctrl.dataList.timeList.length;
        for (var i = 0; i < rowCount; i++) {
            //生成第一行的数据
            var row = '<tr>';
            for (var j = 0; j < ctrl.dataList.categories.length; j++) {
                var type = ctrl.dataList.categories[j];
                for (var k = 0; k < type.vars.length; k++) {
                    var values = type.vars[k].values;
                    values[i] = parseFloat(values[i]);
                    if (isNaN(values[i])) {
                        values[i] = '-'
                    } else {
                        values[i] = parseFloat(values[i]).toFixed(2)
                    }
                    row += "<td>";
                    row += values[i];
                    row += "</td>";
                }
            }
            row += "</tr>";
            historyValueTable.append(row);
            setTimeout(function() {
                //计算列宽
                var tableTitleTds = $('#table-title-list>td');
                var tableValuesTds = $('#tbHistroyValue>tr').eq(0).find('td');
                var columnCounts = tableTitleTds.length;
                var widthSum = 0;
                for (var i = 0; i < columnCounts; i++) {
                    var title = $(tableTitleTds[i]);
                    var value = $(tableValuesTds[i]);
                    var titleWidth = title.width();
                    var valueWidth = value.width();
                    var width = titleWidth > valueWidth ? titleWidth : valueWidth;

                    width += 10;
                    widthSum += width;
                    title.width(width);
                    value.width(width);
                }
                $("#header-table").width(widthSum);
                $("#tbHistroyValue").width(widthSum);
            }, 100);
        }
    }

    ctrl.init();
}
