apiready = function () {
    var ctrl = {
        cycle: 10000,
        init: {},
        bind: {},
        toast: {},
        getAlarmCount: {},
      //  getAlarmList: {},
        renderAlarmList: {},

        renderFilter: {}//渲染报警列表前的拦截器，用于处理体验账号模式下的数据
    };

    ctrl.init = function () {
        ctrl.bind();
        api.sendEvent({
            name: 'requestRtAlarm'
        });
    }

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

    ctrl.bind = function () {

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

            api.sendEvent({
                name: 'requestRtAlarm'
            });
            ctrl.getAlarmCount();
            var list = $api.getStorage('rtAlarmList');
            ctrl.refreshAlarmList(list);
            api.refreshHeaderLoadDone();

        });

        //点击报警
        //如果已经生成抢修单 直接跳转到抢修单页
        //如果没有 跳转到报警详情页
        $("#alarm-con").on("touchend", ".alarm", function () {
            var alarmId = $(this).data("alarm-id");
            var orderId = $(this).data("order-id");
            if (orderId) {
                api.openWin({
                    'name': 'repairDetail',
                    'url': 'widget://html/feature/logQuery/repairLogDetail.html',
                    'pageParam': {
                        id: orderId
                    }
                })
            } else {
                api.openWin({
                    'name': 'alarmDetail',
                    'url': 'widget://html/feature/alarmDetail.html',
                    'pageParam': {
                        id: alarmId
                    }
                })
            }
        })

        api.addEventListener({
            name: 'rtAlarmListUpdated'
        }, function (ret, err) {
            if (ret) {
                ctrl.getAlarmCount();

                var list = $api.getStorage('rtAlarmList');

                ctrl.renderAlarmList(list);

            }

        });
    }

    ctrl.getAlarmCount = function () {
        var url = '/ems/rest/alarm/statistics';
        var userId = $api.getStorage("userId");

        // add s 2023/7/20
        if ($api.getStorage("userType") == 2) { // 员工
            var roleId = $api.getStorage("roleId");
            url = '/ems/rest/alarm/statisticsByRole/' + roleId
        }
        // add e 2023/7/20

        $api.get(url, {}, function (res, err) {
            if (err) {
                ctrl.toast("网络请求失败");
            } else {
                if (!res.code || res.code != 200) {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                } else {
                    res = res.body;
                    $api.text($api.dom('#today-times'), res.currentDay);
                    $api.text($api.dom('#yesterday-times'), res.yesterday);
                    $api.text($api.dom('#this-month-times'), res.currentMonth);
                    $api.text($api.dom('#last-month-times'), res.lastMonth);
                }

            }
        });
    }
    // ctrl.getAlarmList = function () {
    //   var url = '/ems/rest/alarm/page';
    //   var userId = $api.getStorage("userId");
    //   var data = {
    //       "cusId": $api.getStorage('cusId'),
    //       "page" : 1,
    //       "pageSize": 999999
    //   };
    //     $api.post(url, data, function (res, err) {
    //         if (err) {
    //             ctrl.toast("网络请求失败");
    //
    //         } else {
    //             if (!res.code || res.code != 0) {
    //                 ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
    //                 api.refreshHeaderLoadDone();
    //             } else {
    //
    //                 ctrl.renderAlarmList(res);
    //
    //             }
    //         }
    //     });
    // }

    //渲染报警列表前的拦截器，用于处理体验账号模式下的数据
    ctrl.renderFilter = function (list) {

        if ($api.getStorage('cus') && list && list.length > 0) {
            for (var i = 0; i < list.length; i++) {
                var alarmItem = list[i];
                if (alarmItem.prName) {
                    alarmItem.prName = $api.guestPrName;
                }
            }
        }
    }
    //页面刷新时 重新从alarmList列表中取数据渲染
    ctrl.refreshAlarmList = function (list) {
        this.renderFilter(list);
        //清空页面
        $api.html($api.dom('#alarm-con'), '');
        var length = list.length;
        for (var i = 0; i < length; i++) {
          item = ctrl.getAlarmDom(list[i]);
          $api.append($api.dom('#alarm-con'), item);
        }
    }

    ctrl.renderAlarmList = function (list) {
        //对体验账号模式下的数据进行修改
        ctrl.renderFilter(list);
        var alarms = $(".alarm");

        // $api.html($api.dom('#alarm-con'), '');
        var length = list.length;
        //删除不存在元素
        ctrl.removeUnExistAlarm(list);

        var item = '';
        //var today = new Date().getDate();
        //判断是不是第一次 加载 如果是第一次加载  按照顺序append
        if(alarms.length == 0){
          for (var i = 0; i < length; i++) {

              if (!ctrl.isExistOnPage(list[i])) {

                  item = ctrl.getAlarmDom(list[i]);
                  $api.append($api.dom('#alarm-con'), item);
              }

          }
        }else{

          //如果不是第一次加载 如果新的列表 与 页面中列表重复 替换掉页面中列表
          //如果页面中不存在新的列表 将新的列表倒序插入到 页面第一个前面
          list = list.reverse();
          for(var i = 0;i < list.length;i++){
              var item = ctrl.getAlarmDom(list[i]);

              if(!ctrl.isExistOnPage(list[i])){
                $(alarms[0]).before(item);

              }
          }

        }

        var alarms = $api.domAll(".alarm");

        if (alarms.length != 0) {

            $api.css($api.dom('#alarm-list-empty-tips'), 'display:none');
            $api.css($api.dom('#alarm-con'), 'display:block');

        } else {

            $api.css($api.dom('#alarm-list-empty-tips'), 'display:block');
            $api.css($api.dom('#alarm-con'), 'display:none');

        }
    }

    //检测报警是不是存在页面上
    ctrl.isExistOnPage = function (item) {

        var alarms = $api.domAll('.alarm[alarm-id="' + item.alarmId + '"]');

        var length = alarms.length;


        return length > 0 ? true : false;

    }

    //删除页面上多余的报警
    ctrl.removeUnExistAlarm = function (list) {

        var alarms = $api.domAll('.alarm');

        var alarmsLength = alarms.length;
        var listLength = list.length;

        var id, isExist;
        for (var i = 0; i < alarmsLength; i++) {

            id = alarms[i].getAttribute('alarm-id');
            isExist = false;


            for (var j = 0; j < listLength; j++) {

                if (id == list[j].alarmId) {

                    isExist = true;
                    break;

                }

            }

            if (!isExist) {

                alarms[i].remove();

            }

        }

    }

    //获取报警dom
    ctrl.getAlarmDom = function (item) {
        var con = '';
        var alarmTime = CommonModel.formatDateTime(item.alarmTime);
        var alarmValue = '';
        if (item.varType == "1") {
            alarmValue = ((item.alarmValue || item.alarmValue == 0) ? (item.alarmValue + (item.unit ? item.unit : '')) : '');
        } else {
            if (item.showValue) {
                alarmValue = item.valueDefine;
            } else {
                alarmValue = "&nbsp;";
            }
        }
        con += '<div class="alarm bg-touch" data-alarm-id="' + item.alarmId + '" alarm-id="' + item.alarmId + '" data-order-id="' + (item.qjOrderId ? item.qjOrderId : '') + '">';
        con += '<div class="left">';
        con += '<div class="icon-con"><img src="../../image/black-pr-icon.png"></div>';
        con += '<div class="content font1">';
        con += '<div class="pr-name-con">';
        con += '<span class="pr-name ellipsis" style="max-width:55vw;">' + item.prName + '</span>&nbsp;<img src="../../image/red-alarm-icon.png">';
        con += '</div>';
        con += '<div class="ellipsis color-title" style="max-width:55vw;">' + (item.alarmDesc ? item.alarmDesc : '') + '</div>';
        con += '</div>';
        con += '</div>';
        con += '<div class="right text-align-r noWrap color-title"><div>' + alarmTime + '</div><div class="text-align-r color-red">' + alarmValue + '</div></div></div>';

        return con;

    }

    ctrl.init();
}
