apiready = function () {
    var ctrl = {
        updateCycle: 30000,
        uiList: null,
        init: {},
        bind: {},
        initBadge: {},
        initUiList: {},
        getPr: {},
    }

    ctrl.init = function () {
        moment.locale("zh-CN")

        ctrl.bind();
        ctrl.initProject(); // 初始化项目
        ctrl.getPr();
        privilegeModule.getMenuList(function () {
            ctrl.initMessagerMenu(); // 初始化消息菜单
        });
        ctrl.initBadge();
        ctrl.initLatestTime();
        if (ctrl.timer) {
            window.clearInterval(ctrl.timer);
        }
        ctrl.timer = setInterval(function () {
            ctrl.getPr();
        }, ctrl.updateCycle);

        //获取消息
        messageDao.updateData();
    }
    // 初始化项目信息
    ctrl.initProject = function () {
        // 如果是普通客户登录 不显示项目名和 下拉项目选择
        var customers = $api.getStorage('customers');
        // add s 2023/7/5
        if (!customers) {
            return
        }
        // add e
        ctrl.customers = customers;
        if (customers.length <= 1) {
            $('#projectName').css('display', 'none');
        } else {
            $('#projectName').css('display', 'block');
            // 初始化当前客户名（项目名）
            var cusName = $api.getStorage('realName');
            $('#projectName').text(cusName);
            // 初始化项目列表
            for (var i = 0; i < customers.length; i++) {
                var str = '<li class="bg-touch" data-id="{{cusId}}">{{projectName}}</li>';
                str = str.replace('{{cusId}}', customers[i].cusId)
                    .replace('{{projectName}}', customers[i].cusName);
                $('#project-panel').append(str);
            }
        }
    }
    // 初始化消息菜单如抢修管家，巡检管家权限
    ctrl.initMessagerMenu = function () {
        if (!privilegeModule.hasMenu('抢修管家')) {
            $('.repair-keeper').css('display', 'none');
        }
        if (!privilegeModule.hasMenu('巡检管家')) {
            $('.inspect-keeper').css('display', 'none');
        }
        if (!privilegeModule.hasMenu('报表管家')) {
            $('.report-keeper').css('display', 'none');
        }
        if (!privilegeModule.hasMenu('报警管家')) {
            $('.alarm-keeper').css('display', 'none');
        }
        if (!privilegeModule.hasMenu('操作票助手')) {
            $('.oper-ticket-assistantor').css('display', 'none');
        }
        if (!privilegeModule.hasMenu('工作票助手')) {
            $('.work-ticket-assistantor').css('display', 'none');
        }
        if (!privilegeModule.hasMenu('电务小蜜蜂')) {
            $('.bee').css('display', 'none');
        }
    }
    ctrl.bind = function () {
        // 防止退出后继续轮询
        api.addEventListener({
            name: 'loginout'
        }, function (ret, err) {
            window.clearInterval(ctrl.timer);
        });

        // 切换客户（项目）
        $('#project-panel').on('touchend', 'li', function () {
            var cusId = $(this).data('id');
            var customers = ctrl.customers;
            for (var i = 0; i < customers.length; i++) {
                if (customers[i].cusId === cusId) {
                    $api.setStorageOfCus(customers[i]);
                    var cusName = customers[i].cusName;
                    $('#projectName').text(cusName); // 选择之后更新客户名
                    // 发送客户发生改变的消息
                    api.sendEvent({
                        name: 'projectChanged'
                    });
                    ctrl.getPr();
                    return;
                }
            }
        })

        //跳转到消息列表页
        $(".messager").on("touchend", function () {
            var type = $(this).data("type");
            api.openWin({
                name: 'messageList',
                url: 'widget://html/message/messageList.html',
                pageParam: {
                    type: type
                }
            });
        })

        //监听消息改变事件 初始化badge
        api.addEventListener({
            name: 'messageUpdated'
        }, function (ret, err) {
            ctrl.initBadge();
            ctrl.initLatestTime();
        });

        // add by guoyuanyuan 2018/9/25
        // 监听项目改变的消息 更新当前显示的项目
        api.addEventListener({
            name: 'requestChangeProject'
        }, function (ret, err) {
            $('#project-panel').css('display', 'block');
        });
        //如果body收到touchend事件 隐藏掉modal
        $api.addEvt($api.dom("body"), "touchend", function () {
            $api.css($api.dom("#project-panel"), "display:none");
        }, false);

        api.addEventListener({
            name: 'requestCloseModal'
        }, function (ret, err) {
            $('#project-panel').css('display', 'none');
        });


        //下拉刷新
        api.setRefreshHeaderInfo({
            bgColor: "#CCCCCC",
            textColor: "#FFFFFF"
        }, function (ret, err) {
            // 下拉刷新 隐藏掉项目下拉panel
            $api.css($api.dom("#project-panel"), "display:none");
            ctrl.initBadge();
            ctrl.initLatestTime();
            messageDao.updateData(function () {
                api.refreshHeaderLoadDone();
            })
        })
    }

    //初始化页面的badge
    ctrl.initBadge = function () {

        //显示未读信息的条数
        messageDao.getTypeUnReadCount(function (list) {
            //先隐藏掉所有badge
            $("#bee-badge").css("display", "none");
            $("#repair-keeper-badge").css("display", "none");
            // 报表管家
            $("#report-keeper-badge").css("display", "none");
            $("#alarm-keeper-badge").css("display", "none");
            $("#inspect-keeper-badge").css("display", "none");
            $("#oper-ticket-assistantor-badge").css("display", "none");
            $("#work-ticket-assistantor-badge").css("display", "none");

            var length = list.length;

            for (var i = 0; i < length; i++) {

                switch (parseInt(list[i].type)) {
                    case 10:
                        showBadge("bee-badge", list[i].sum);
                        break; //自定义消息
                    case 20:
                        showBadge("repair-keeper-badge", list[i].sum);
                        break; //抢修管家消息
                    case 30:
                        showBadge("inspect-keeper-badge", list[i].sum);
                        break; //巡检管家消息
                    case 40:
                        showBadge("oper-ticket-assistantor-badge", list[i].sum);
                        break; //操作票助手
                    case 50:
                        showBadge("work-ticket-assistantor-badge", list[i].sum);
                        break; //工作票助手
                    case 60:
                        showBadge("alarm-keeper-badge", list[i].sum);
                        break; //工作票助手

                    //报表管家
                    case 70:
                        showBadge("report-keeper-badge", list[i].sum);
                        break; //报表管家消息
                }

            }
        })

        function showBadge(id, sum) {
            var text = sum;

            if (sum == 0) {
                $("#" + id).css("display", "none");
                return false;
            }

            if (sum > 99) {
                text = "99+";
            }

            $("#" + id).css("display", "block");
            $("#" + id).text(text);

        }
    }


    //初始化每类消息最新消息的时间
    ctrl.initLatestTime = function () {
        messageDao.getTypeLatestTime(function (list) {
            //先清空时间
            $("#bee-time").text("");
            $("#repair-keeper-time").text("");
            $("#inspect-keeper-time").text("");
            $("#report-keeper-time").text("");
            $("#alarm-keeper-time").text("");
            $("#oper-ticket-assistantor-time").text("");
            $("#work-ticket-assistantor-time").text("");

            var length = list.length;

            for (var i = 0; i < length; i++) {

                switch (parseInt(list[i].type)) {
                    case 10:
                        showTime("bee-time", list[i].create_time);
                        break; //自定义消息
                    case 20:
                        showTime("repair-keeper-time", list[i].create_time);
                        break; //抢修管家消息
                    case 30:
                        showTime("inspect-keeper-time", list[i].create_time);
                        break; //巡检管家消息
                    case 40:
                        showTime("oper-ticket-assistantor-time", list[i].create_time);
                        break; //操作票助手
                    case 50:
                        showTime("work-ticket-assistantor-time", list[i].create_time);
                        break; //工作票助手
                    case 60:
                        showTime("alarm-keeper-time", list[i].create_time);
                        break; //报警管家

                    case 70:
                        showTime("report-keeper-time", list[i].create_time);
                        break; //报表管家消息
                }
            }

            function showTime(dom, time) {
                var content = CommonModel.formatDateTime(parseInt(time));
                $("#" + dom).text(content);
            }

        })

    }

    //获取配电室并显示
    ctrl.getPr = function () {
        var data = {
            cusId: $api.getStorage('cusId')
        }

        // 员工登陆
        var isEmployee = $api.getStorage('isEmployee')
        if (isEmployee) {
            data = {
                employeeId: $api.getStorage('employeeId'),
                roleId: $api.getStorage('roleId')
            }
        }

        /**
         * 注意在客户体验模式下要拦截此接口的数据，另外在最外层的index.html中也有此接口的调用，如果需要修改，则两处都要该，别忘了
         */
        $api.get("/ems/rest/power/room/list", data, function (ret, err) {

            if (ret && ret.code == 200) {

                //判断是否是体验账号，如果是体验账号，则对云端返回的数据进行拦截
                if ($api.getStorage('cus')) {
                    //对云端返回的数据进行拦截
                    if (ret.body && ret.body.length > 0) {
                        for (var i = 0; i < ret.body.length; i++) {
                            // var prInfo = ret.body[i];
                            ret.body[i].prName = $api.guestPrName;
                            if (i > 0) {
                                ret.body[i].prName += (" #" + (i + 1));
                            }
                        }
                    }
                }

                render(ret.body);
            }
        });

        function render(list) {
            $('#pr-container').empty();
            var length = list.length;
            var tpl = '<div class="pr item" prid="{{prId}}">';
            tpl += '<div><div class="icon-con"><img src="../../image/black-pr-icon.png"></div>';
            tpl += '<div class="name">{{prName}}</div>';
            tpl += '</div>';
            tpl += '<div>';
            // tpl += '<div class="status">{{status}}</div>';
            tpl += '<div class="safe-content">安全运行&nbsp;<span class="color-green days">{{days}}</span>&nbsp;天</div>';
            tpl += '</div>';
            tpl += '</div>';

            var powerRooms = [];
            for (var i = 0; i < length; i++) {
                var status = '<span class="color-green">正常</span>';

                if (list[i].xjStatus == 1) {
                    status = '<span class="color-yellow">巡检</span>';
                }

                if (list[i].bjStatus == 1) {
                    status = '<span class="color-red">故障</span>';
                }

                if (list[i].qxStatus == 1) {
                    status = '<span class="color-red">抢修</span>';
                }


                var dom = $api.dom('.pr[prid="' + list[i].prId + '"]');
                if (dom) {
                    // $api.html($api.dom(dom, ".status"), status);
                    $api.html($api.dom(dom, ".days"), list[i].safetyDay);
                } else {
                    var item = tpl.replace('{{prId}}', list[i].prId)
                        .replace('{{prName}}', list[i].prName)
                        // .replace('{{status}}', status)
                        .replace('{{days}}', list[i].safetyDay);
                    $api.append($api.dom('#pr-container'), item);
                }
                //保存最新的配电室列表
                powerRooms.push({
                    "prId": list[i].prId,
                    "prName": list[i].prName,
                    "configId": list[i].configId
                })

            }
            if ($api.getStorage('cus')) {
                if (powerRooms.length > 0) {
                    $api.setStorage("prList", powerRooms);
                }
                $api.setStorage("powerRoom", powerRooms[0]);
            }

        }
    }

    ctrl.init();
}
