apiready = function () {
    //默认显示对比分页tab-panel 即 ctrl.mode = ctrl.modes.COMPARE;
    //默认时间粒度是日数据 即 ctrl.dimension = ctrl.dimensions.DAY;
    //默认时间是当前月

    //当收到侧栏页的 “energySelectedNumber”的消息，也就是侧栏页选中了调度号，同时在消息体里把调度号传回主页 调用获取数据的方法 getData
    //getData方法调用各个获取数据的具体方法
    //	getTimeData()
    //	getCompareData()
    //获取到数据之后 保存在对用的数据对象里
    //	compareAChartData
    //	compareATableData
    //	timeAChartData
    //	timeBChartData
    //	timeCChartData
    //	然后调用分别在各个获取数据的方法里调用对应的render方法来渲染表格或者图表

    //当切换了“分时分析”和“对比分析”panel 调用对应的render方法，不在调用getData();

    //当点击“选择回路”按钮 弹出侧栏 选中调度号后 点击确定 主页收到“energySelectedNumber”消息 重新调用getData()方法，重复上述步骤

    //当选择了“日数据”或“月数据”按钮， 重新调用getData()方法

    //重新选择了日期之后， 重新调用getData()方法
    var ctrl = {
        init: {},
        bind: {},
        backCallback: {},

        // 当前展示的tab 页类型，msg:配电室资料   inspection：巡检日志  repair：抢修日志
        tabType: 'msg',

        prId: null,
        prName: '',
        baseUrl: '',
        currentPage: 1,
        pageSize: 20,
        repairCurrentPage: 1,
        repairPageSize: 20,

        flag: 2, // 处理完（日志）
    }

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

        ctrl.bind();

        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        ctrl.prId = api.pageParam.prid;
        ctrl.prName = api.pageParam.prname;
        ctrl.taskId = api.pageParam.taskid;

        ctrl.initPrMsgTab()

    }

    ctrl.bind = function () {
        var $startTime = $('#startTime-select');
        var $endTime = $('#endTime-select');
        var $lbStartTime = $('#lbStartTime');
        var $lbEndTime = $('#lbEndTime');

        var $repairStartTime = $('#repair-startTime-select');
        var $repairEndTime = $('#repair-endTime-select');
        var $repairLbStartTime = $('#repair-lbStartTime');
        var $repairLbEndTime = $('#repair-lbEndTime');

        var _this = this;

        var height = $(window).height() - $("header").height() - $(".tabs").height();
        $(".content-container").css("height", height);
        //绑定返回按钮
        $api.addEvt($api.dom("#back"), "touchend", function () {
            ctrl.backCallback();
        })

        //点击系统返回按钮
        api.addEventListener({
            name: 'keyback'
        }, function (ret, err) {
            ctrl.backCallback();
        });

        //点击开始巡检按钮
        $api.addEvt($api.dom("#start-inspect-btn"), "touchend", function () {
            ctrl.handleStartInspect()
        })

        //点击配电室资料tab按钮
        $api.addEvt($api.dom("#pr-msg-tab"), "touchend", function () {
            if (ctrl.tabType == 'msg') {
                return
            }

            $api.addCls(this, "active");
            $api.removeCls($api.dom("#inspection-log-tab"), "active");
            $api.removeCls($api.dom("#repair-log-tab"), "active");
            $api.css($api.dom("#pr-msg-panel"), 'display:block');
            $api.css($api.dom("#inspection-log-panel"), 'display:none');
            $api.css($api.dom("#repair-log-panel"), 'display:none');

            ctrl.tabType = 'msg'

            ctrl.initPrMsgTab()
        }, false);

        //点击巡检日志tab按钮
        $api.addEvt($api.dom("#inspection-log-tab"), "touchend", function () {
            if (ctrl.tabType == 'inspection') {
                return
            }

            $api.addCls(this, "active");
            $api.removeCls($api.dom("#pr-msg-tab"), "active");
            $api.removeCls($api.dom("#repair-log-tab"), "active");
            $api.css($api.dom("#inspection-log-panel"), 'display:block');
            $api.css($api.dom("#pr-msg-panel"), 'display:none');
            $api.css($api.dom("#repair-log-panel"), 'display:none');

            ctrl.tabType = 'inspection'

            // 初始化巡检日志 tab
            ctrl.getInspectLog();

        }, false);

        //点击抢修日志tab按钮
        $api.addEvt($api.dom("#repair-log-tab"), "touchend", function () {
            if (ctrl.tabType == 'repair') {
                return
            }

            $api.addCls(this, "active");
            $api.removeCls($api.dom("#pr-msg-tab"), "active");
            $api.removeCls($api.dom("#inspection-log-tab"), "active");
            $api.css($api.dom("#repair-log-panel"), 'display:block');
            $api.css($api.dom("#pr-msg-panel"), 'display:none');
            $api.css($api.dom("#inspection-log-panel"), 'display:none');

            ctrl.tabType = 'repair'

            ctrl.getRepairLogs();

        }, false);

        /*
            ====================配电室资料  tab 相关事件====================
        */
        // 点击配电室资料列表 ，在线浏览 pdf
        $("#pr-msg-list").on("touchend", ".pr-msg-list-item", function () {

            var url = ctrl.baseUrl + $(this).data("url");

            api.download({
                url: url,  // 填写要下载文档的url
                report: true,
                cache: true,
                allowResume: true
            }, function (ret, err) {
                if (ret.state == 1) {					//下载成功

                    var superFile = api.require('superFile');
                    superFile.open({
                        path: ret.savePath,
                    })

                }
            });

        })

        /*
            ====================巡检日志 tab 中相关事件====================
        */
        $startTime.on('change', function () {
            var startTimeValue = $startTime.val();
            var endTimeValue = $endTime.val();
            if (startTimeValue) {
                $lbStartTime.html(startTimeValue);
            } else {
                $lbStartTime.html("开始日期");
            }
        })

        $endTime.on('change', function () {
            var startTimeValue = $startTime.val();
            var endTimeValue = $endTime.val();
            if (endTimeValue) {
                $lbEndTime.html(endTimeValue);
            } else {
                $lbEndTime.html("结束日期");
            }
        })
        // 点击巡检日志跳转到详情页
        $("#inspect-logs").on("touchend", ".item", function () {
            var id = $(this).data('id');
            var name = $(this).data('name');
            api.openWin({
                name: 'inspectionLogDetail',
                url: './inspectionLogDetail.html',
                pageParam: {
                    id: id,
                    name: name
                }
            });
        })
        //点击查询巡检日志
        $api.addEvt($api.dom("#query"), "touchend", function () {
            $api.html($api.dom('#inspect-logs'), '');
            _this.currentPage = 1;
            _this.getInspectLog();
        });

        /*
            =======================抢修日志 tab 相关事件======================
        */

        $repairStartTime.on('change', function () {
            var startTimeValue = $repairStartTime.val();
            if (startTimeValue) {
                $repairLbStartTime.html(startTimeValue);
            } else {
                $repairLbStartTime.html("开始日期");
            }
        })

        $repairEndTime.on('change', function () {
            var endTimeValue = $repairEndTime.val();
            if (endTimeValue) {
                $repairLbEndTime.html(endTimeValue);
            } else {
                $repairLbEndTime.html("结束日期");
            }

        })

        $api.addEvt($api.dom("#repair-query"), "touchend", function () {
            $api.html($api.dom('#repair-logs'), '');
            ctrl.repairCurrentPage = 1;
            ctrl.getRepairLogs();
        });

        //跳转到抢修日志详情页
        $("#repair-logs").on("touchend", ".item", function () {
            var id = $(this).data('id');
            var name = $(this).data('name');
            api.openWin({
                name: 'repairDetail',
                url: './repairLogDetail.html',
                pageParam: {
                    id: id,
                    name: name
                }
            });
        })

        // 查询抢修日志
        $api.addEvt($api.dom("#repair-query"), "touchend", function () {
            $api.html($api.dom('#repair-logs'), '');
            ctrl.repairCurrentPage = 1;
            ctrl.getRepairLogs();
        });

    }
    /**
     * 弹出提示框
     */

    ctrl.toast = function (msg) {
        api.toast({
            msg: msg,
            duration: 3000,
            locaiton: 'top'
        });
    }

    ctrl.backCallback = function () {
        //关闭首页正在加载的提示框
        api.execScript({
            name: 'index',
            frameName: 'featureFrame',
            script: "api.hideProgress();"
        });
        api.setScreenOrientation({
            orientation: 'auto_portrait'
        });
        api.setFullScreen({
            fullScreen: false
        });
        api.closeWin({});
    }

    //上拉加载
    api.addEventListener({
        name: 'scrolltobottom'
    }, function (ret, err) {
        if (ctrl.tabType == 'inspection') {

            ctrl.currentPage++;
            if (ctrl.currentPage > ctrl.totalPages) {
                ctrl.toast("没有更多了");
                return;
            }
            ctrl.getInspectionLog();

        } else if (ctrl.tabType == 'repair') {

            ctrl.repairCurrentPage++;
            if (ctrl.repairCurrentPage > ctrl.repairTotalPages) {
                ctrl.toast("没有更多了");
                return;
            }
            ctrl.getRepairLogs();

        }

    });

    //下拉刷新
    api.setRefreshHeaderInfo({
        loadingImg: 'widget://image/refresh.png',
        bgColor: '#ccc',
        textColor: '#fff',
        textDown: '下拉刷新...',
        textUp: '松开刷新...'
    }, function (ret, err) {
        if (ctrl.tabType == 'msg') {

            ctrl.initPrMsgTab()

        } else if (ctrl.tabType == 'inspection') {

            $startTime.val('');
            $endTime.val('');
            $lbStartTime.html("开始日期");
            $lbEndTime.html("结束日期");
            _this.currentPage = 1;
            _this.getInspectLog();

        } else if (ctrl.tabType == 'repair') {

            $repairStartTime.val('');
            $repairEndTime.val('');
            $repairLbStartTime.html("开始日期");
            $repairLbEndTime.html("结束日期");
            ctrl.repairCurrentPage = 1;
            ctrl.getRepairLogs();

        }

        api.refreshHeaderLoadDone();
    });

    /*
        ====================配电室资料 tab 相关===================
    */
    // 初始化 配电室资料 tab
    ctrl.initPrMsgTab = function () {
        ctrl.getPrMsg()
        ctrl.getPrMsgList()
    }

    // 获取配电室信息
    ctrl.getPrMsg = function () {
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        var url = "/ems/rest/power/room/detail";
        var data = {
            prId: ctrl.prId,
        }
        $api.get(url, data, function (res, err) {
            api.hideProgress();

            if (err) {
                ctrl.toast("网络请求失败");
            } else {
                if (res.code == 200) {
                    ctrl.renderPrMsg(res.body);
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }
        })
    }

    // 渲染配电室信息panel
    ctrl.renderPrMsg = function (data) {

        $('#pr-msg').empty();

        var tpl = '';
        tpl += '<p>配电室联系人：{{people}}</p>';
        tpl += '<p>联系人电话：{{tel}}</p>';
        tpl += '<p>配电室位置：{{province}} {{city}} {{address}}</p>';

        var dom = tpl.replace('{{people}}', data.lxr1)
            .replace('{{tel}}', data.lxr1Mobile)
            .replace('{{province}}', data.province)
            .replace('{{city}}', data.city)
            .replace('{{address}}', data.address)

        $api.html($api.dom('#pr-msg'), dom);
    }

    // 获取配电室资料列表
    ctrl.getPrMsgList = function () {
        var url = "/ems/rest/pr/file/list";
        var data = {
            prId: ctrl.prId,
        }
        $api.get(url, data, function (res, err) {

            if (err) {
                ctrl.toast("网络请求失败");
            } else {
                if (res.code == 200 && res.body) {
                    var length = res.body.length;

                    ctrl.baseUrl = res.prefix;

                    $('#pr-msg-list').empty();

                    for (var i = 0; i < length; i++) {
                        var listItem = res.body[i]
                        $api.append($api.dom('#pr-msg-list'), ctrl.getPrMsgListDOM(listItem));
                    }
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }
        })
    }

    // 渲染配电室信息列表
    ctrl.getPrMsgListDOM = function (listItem) {

        var tpl = '';

        tpl += '<div class="item bg-touch pr-msg-list-item" data-url="{{url}}">'
        tpl += '<div class="nav">'
        tpl += '<span class="pr-name">{{name}}</span>'
        tpl += '<span class="date-time color-title">详情</span>'
        tpl += '</div>'
        tpl += '</div>'

        var dom = tpl.replace('{{url}}', listItem.fileUrl)
            .replace('{{name}}', listItem.fileName)

        return dom;
    }

    /*
        ===================巡检日志 tab 相关==============
    */
    //获取巡检日志
    ctrl.getInspectLog = function () {
        //显示载入动画
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });
        var dateUtil = new DateUtils();
        var startDate = $('#startTime-select').val();
        if (startDate) {
            dateUtil.setDate(startDate);
            startDate = dateUtil.getMillisecond();
        }
        var endDate = $('#endTime-select').val();
        if (endDate) {
            dateUtil.setDate(endDate);
            endDate = dateUtil.getMillisecond();
        }
        // 如果开始时间大于结束时间 交换
        startDate && endDate && (startDate > endDate) && (startDate = [endDate, endDate = startDate][0]);
        var url = '/ems/rest/common/xj/log/page';
        var data = {
            "page": ctrl.currentPage,
            "pageSize": ctrl.pageSize,
            "prId": ctrl.prId,
            "startDate": startDate,
            "endDate": endDate,
        };

        $api.get(url, data, function (res, err) {
            if (err) {
                //隐藏载入动画
                api.hideProgress();
                ctrl.toast("网络请求失败");
            } else {
                if (!res.code || res.code != 200) {
                    //隐藏载入动画
                    api.hideProgress();
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                } else {
                    ctrl.renderInspectLog(res);
                }

            }
        });

    }
    ctrl.renderInspectLog = function (res) {

        ctrl.logList = res.body.records;
        ctrl.totalPages = res.body.totalPages;
        if (ctrl.currentPage == 1) {
            $api.html($api.dom('#inspect-logs'), '');
        }

        if (ctrl.totalPages == 0) {
            //隐藏载入动画
            api.hideProgress();
            api.refreshHeaderLoadDone();
            $api.css($api.dom('#inspect-logs'), "display:none");
            $api.css($api.dom('#inspect-log-empty-tips'), "display:block");
        } else {
            var logList = ctrl.logList;
            var length = logList.length;
            for (var i = 0; i < length; i++) {
                $("#inspect-logs").append(ctrl.getLogDom(logList[i]));
            }
            //隐藏载入动画
            api.hideProgress();
            $api.css($api.dom('#inspect-logs'), "display:block");
            $api.css($api.dom('#inspect-log-empty-tips'), "display:none");

        }
    }
    ctrl.getLogDom = function (item) {

        var tpl = '<div class="item  bg-touch" data-id="{{id}}" data-name="{{name}}">';
        tpl += '<div class="nav">';
        tpl += '<span class="pr-name">{{title}}</span>';
        tpl += '<span class="date-time color-title" data-id="{{id}}">{{date}}</span></div>';
        tpl += '<div class="con">';
        tpl += '<div class="con-item"><div><span class="color-title">日检：</span><span>{{dailyCount}}项</span></div>';
        tpl += '<div><span class="color-title">周检：</span><span>{{weekCount}}项</span></div>'
        tpl += '<div><span class="color-title">月检：</span><span>{{monthCount}}项</span></div></div>'

        tpl += '<div class="con-item"><div><span class="color-title">复检：</span><span>{{reviewCount}}项</span></div>';
        tpl += '<div><span class="color-title">突发：</span><span>{{burstCount}}项</span></div>';
        tpl += '<div><span class="color-title">异常：</span><span>{{abnormalCount}}项</span></div></div>';


        tpl += '<div class="con-item"><span class="color-title">巡检组长：</span><span>{{by}}</span></div>';
        //tpl += '<div class="con-item"><span>巡检人电话</span><span>{{tel}}</span></div></div></div>';
        tpl += '</div></div>';

        return tpl.replace('{{title}}', item.prName)
            .replace('{{date}}', item.xjDate)
            .replace('{{dailyCount}}', item.dayInspectCount)
            .replace('{{weekCount}}', item.weekInspectCount)
            .replace('{{monthCount}}', item.monthInspectCount)
            .replace('{{abnormalCount}}', item.exceptionCount)

            .replace('{{reviewCount}}', item.fjCount)
            .replace('{{burstCount}}', item.tfCount)
            .replace('{{by}}', item.employeeName)
            // .replace('{{tel}}', item.xjzz.lxMobile)
            .replace('{{id}}', item.taskId)
            .replace('{{name}}', item.prName)
    }

    /*
        ===================抢修日志 tab 相关==================
    */
    ctrl.getRepairLogs = function () {
        var $startTime = $('#repair-startTime-select');
        var $endTime = $('#repair-endTime-select');
        //显示载入动画
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        var dateUtil = new DateUtils();

        var startDate = $startTime.val();
        if (startDate) {
            dateUtil.setDate(startDate);
            startDate = dateUtil.getMillisecond();
        }

        var endDate = $endTime.val();
        if (endDate) {
            dateUtil.setDate(endDate);
            endDate = dateUtil.getMillisecond();
        }
        // 如果开始时间大于结束时间 交换
        startDate && endDate && (startDate > endDate) && (startDate = [endDate, endDate = startDate][0]);
        var url = '/ems/rest/qx/order/page';
        var data = {
            "page": ctrl.repairCurrentPage,
            "pageSize": ctrl.repairPageSize,
            "prId": ctrl.prId,
            "startDate": startDate || null,
            "endDate": endDate || null,
            "flag": ctrl.flag // 处理完（日志）
        };
        $api.get(url, data, function (res, err) {
            if (err) {
                //隐藏载入动画
                api.hideProgress();
                ctrl.toast("网络请求失败");
            } else {
                if (!res.code || res.code != 200) {
                    //隐藏载入动画
                    api.hideProgress();
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                } else {
                    ctrl.renderRepairLogs(res);
                }

            }
        });
    }

    ctrl.renderRepairLogs = function (res) {
        var logList = res.body.records;
        if (ctrl.repairCurrentPage == 1) {
            $api.html($api.dom('#repair-logs'), '');
        }

        ctrl.repairTotalPages = res.body.totalPages;
        if (ctrl.repairTotalPages == 0) {
            // 隐藏载入动画
            api.hideProgress();
            api.refreshHeaderLoadDone();
            $api.css($api.dom('#repair-logs'), "display:none");
            $api.css($api.dom('#repair-log-empty-tips'), "display:block");

        } else {
            var length = logList.length;
            for (var i = 0; i < length; i++) {
                $api.append($api.dom('#repair-logs'), ctrl.getRepairLogDom(logList[i]));
            }
            //隐藏载入动画
            api.hideProgress();
            $api.css($api.dom('#repair-logs'), "display:block");
            $api.css($api.dom('#repair-log-empty-tips'), "display:none");

        }

    }

    ctrl.getRepairLogDom = function (item) {

        var tpl = '';
        tpl += '<div class="item bg-touch"  data-id="{{id}}">';
        tpl += '<div class="nav">';
        tpl += '<span class="pr-name">{{title}}</span>';
        tpl += '<span class="date-time color-title">{{date}}</span>';
        tpl += '</div>';
        tpl += '<div class="con">';
        tpl += '<div class="con-item color-title">';
        tpl += '<span>{{problem}}</span>';
        tpl += '</div></div></div>';
        if (!item.orderDesc) {
            item.orderDesc = '';
        }
        var dateUtil = new DateUtils();
        dateUtil.setDate(item.createTime);
        var createTime = dateUtil.getFormattedDate('yyyy-MM-dd hh:mm:ss');
        return tpl.replace('{{title}}', item.prName).replace('{{problem}}', item.orderDesc)
            .replace('{{date}}', createTime)
            .replace('{{id}}', item.qxOrderId);
    }

    ctrl.handleStartInspect = function () {
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        var url = "/ems/rest/xj/task/start";
        var data = {
            taskId: ctrl.taskId,
        }
        $api.put(url, data, function (res, err) {
            api.hideProgress();
            
            if (err) {
                ctrl.toast("网络请求失败,请稍后再试");
            } else {
                if (res.code == 200) {
                    // 跳转到巡检内容页
                    api.openWin({
                        name: 'inspectionItem',
                        url: './inspectionItem.html',
                        pageParam: {
                            id: ctrl.prId,
                            name: ctrl.prName,
                            taskid: ctrl.taskId
                        }
                    });
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }
        })
    }

    ctrl.init();

}
