var startDateStr;
var endDateStr;
var ipStartTime;
var ipEndTime;
var lbStartTime;
var lbEndTime;
var alarmList;
var btnLocation;
var btnClassification;
var btnProcess;
var emptyTips;

var prId = '';
var prName = "unkown";
var currentPage = 0; //当前页数
var totalPages = 1;
var isLoading = false;

var requestArgs = {
    startDate: null,
    endDate: null,
    alarmStatus: null, //null全部，"1"实时报警，"2"历史报警“
    handleStatus: null, //null全部，0未处理，1处理中，2已完成，3已确认
    location: null, //null全部，1高压侧，2低压侧，3变压器，4直流屏，5信号屏，6其他
    page: 1,
    pageSize: 10
}

/**
 * 显示右侧边栏
 */
function showRightPanel() {
    api.openDrawerPane({
        type: 'right'
    });
}

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

// /**
//  * 将字符型的日期解析为moment.js对象
//  * @param {String} dateStr
//  * @return {moment.js}
//  */
// function parseDate(dateStr, format) {
//     if (format) {
//         return moment(dateStr, format);
//     } else {
//         return moment(dateStr);
//     }
// }

// /**
//  * 将moment对象格式化输出
//  * @param {moment.js} date
//  * @param {String} format
//  * @return {String}
//  */
// function momentFormat(date, format) {
//     if (format) {
//         return date.format(format);
//     }
//     return date.format("YYYY-MM-DD");
// }

/**
 * 清空报警列表
 */
function clearAlarmList() {
    $("#alarmList").empty();
}

/**
 * 向界面中添加一条报警项
 * @param {*} record
 */
function addAlarmItem(record) {
    var template = "<div class=\"alarm bg-touch\"  data-alarm-id=\"{alarmId}\" data-order-id=\"{orderId}\"><div class=\"left\"><div class=\"icon-con\"><img src=\"../../image/black-pr-icon.png\"></div><div class=\"content font1\"><div class=\"pr-name-con\"><span class=\"pr-name\">{prName}</span>&nbsp;<img src=\"../../image/red-alarm-icon.png\"></div><div class=\"width100 ellipsis color-title\">{alarmDesc}</div></div></div><div class=\"right text-align-r\"><div class=\"color-title\">{time}</div><div class=\"height4\"></div><div class=\"text-{color}\">{status}</div></div></div>";

    var alarmDesc = record.alarmDesc ? record.alarmDesc : "";

    if ($api.getStorage('cus')) {
        alarmDesc = alarmDesc.replace($api.guestKeysPattern, $api.guestName);
    }

    template = template.replace("{alarmId}", record.alarmId).replace("{orderId}", record.qxOrderId ? record.qxOrderId : '');
    template = template.replace("{prName}", record.prName).replace("{alarmDesc}", record.alarmDesc);
    template = template.replace("{time}", moment(record.alarmTime).format('YYYY-MM-DD'));
    switch (record.handleStatus) {
        case 0:
            template = template.replace("{color}", "red");
            template = template.replace("{status}", "未处理");
            break;
        case 1:
            template = template.replace("{color}", "yellow");
            template = template.replace("{status}", "处理中");
            break;
        case 2:
            template = template.replace("{color}", "green");
            template = template.replace("{status}", "已完成");
            break;
        case 3:
            template = template.replace("{color}", "gray");
            template = template.replace("{status}", "已确认");
            break;
        default:
            break;
    }
    alarmList.append(template);
}

/**
 * 查询报警
 */
function queryData() {
    var url = '';
    var data = {};
    var isEmployee = $api.getStorage('isEmployee');

    requestArgs.page = currentPage;
    
    if (isEmployee) { // 员工登陆
        url = '/ems/rest/alarm/page';
        data = {
            page: requestArgs.page,
            pageSize: requestArgs.pageSize,
            alarmStatus: requestArgs.alarmStatus,
            handleStatus: requestArgs.handleStatus,
            location: requestArgs.location,
            employeeId: $api.getStorage('employeeId'),
            roleId: $api.getStorage('roleId')
        };
    } else { // 客户登录
        url = '/ems/rest/alarm/edpPage';
        data = {
            page: requestArgs.page,
            pageSize: requestArgs.pageSize,
            alarmStatus: requestArgs.alarmStatus,
            handleStatus: requestArgs.handleStatus,
            location: requestArgs.location,
            prId: powerRoom.prId,
            userType: $api.getStorage('userType')
        };
    };

    if (startDateStr) {
        data.startDate = (new Date(startDateStr.replace(/-/g, '/'))).getTime();
    }

    if (endDateStr) {
        data.endDate = (new Date(endDateStr.replace(/-/g, '/'))).getTime();
    }

    if (prId) {
        data.prId = prId;
    }

    var isLoading = true;
    api.showProgress({
        title: '载入中...',
        text: '请稍后',
        modal: false
    });
    $api.get(url, data, function(data, err) {
        isLoading = false;
        api.hideProgress();
        if (err) {
            toast("网络请求失败");
        } else {
            if (!data.code || data.code != "200" || !data.body) {
                toast("服务器响应错误" + (data.code ? ("，错误码：" + data.code) : ""));
            } else {
                totalPages = data.body.totalPages;

                if (data.body.records.length && data.body.records.length > 0) {
                    emptyTips.hide();
                    for (var i = 0; i < data.body.records.length; i++) {
                        var record = data.body.records[i];
                        addAlarmItem(record);
                    }
                } else {
                    //如果没有记录，则显示查询不到数据的提示
                    emptyTips.show();
                }

            }
        }
    });
}

/**
 * 初始化分页参数，并查询历史报警
 */
function firstQuery() {
    currentPage = 1;
    clearAlarmList();
    queryData();
}

/**
 * 筛选条件发生变化
 */
 function filterSelectionChanged(ret, err) {
    var result = ret.value;
    requestArgs.alarmStatus = result.alarmClasses; // 全部时效
    requestArgs.handleStatus = result.af; // 全部状态
    requestArgs.location = result.catalogType; // 全部位置
    prId = result.prId; // 配电室
    currentPage = 1;

    btnLocation.attr("value", result.locName);
    btnClassification.attr("value", result.alarmClassName);
    btnProcess.attr("value", result.afName);

    firstQuery();
}

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

    ctrl.init = function() {
        // 适配安卓状态栏
        CommonModel.fitInStatusBar();
        var searcherTop = $('#heightHeader').height();
        $('#searcher').css('top',searcherTop);
        //设置分页初始值
        currentPage = 1;
        totalPages = 1;
        powerRoom = $api.getStorage('powerRoom');
        //获取prId
        // prId = powerRoom.prId;
        // requestArgs.prId = prId;
        //获取prName
        prName = powerRoom.prName;

        ipStartTime = $("#ipStartTime");
        lbStartTime = $("#lbStartTime");
        ipEndTime = $("#ipEndTime");
        lbEndTime = $("#lbEndTime");
        alarmList = $("#alarmList");
        btnLocation = $("#btn-location");
        btnClassification = $("#btn-classification");
        btnProcess = $("#btn-process");
        emptyTips = $("#empty-tips");

        ctrl.bind();
        //筛选条件发生变化
        api.addEventListener({
            name: 'filterSelectionChanged'
        }, filterSelectionChanged);

        //用初始分页参数查询报警
        firstQuery();
    }

    ctrl.bind = function() {
        var height = $(window).height() - $("header").height() - $(".fix-top").height();
        $(".alarmList-content").css("height", height);
        //用户点击了返回按钮
        $(".back").on("touchend", function() {
            api.closeWin();
        });

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

        //用户点击了报警分类按钮
        $("#btn-classification").on("touchend", showRightPanel);

        //用户点击了处理状态按钮
        $("#btn-process").on("touchend", showRightPanel);

        //用户点击了筛选时效按钮
        $("#btn-filter").on("touchend", showRightPanel);

        //用户点击了查询按钮
        $("#btn-query").on("touchend", firstQuery);

        //监听日期选择器的改变事件
        $("#ipStartTime").on("change", function() {
            startDateStr = ipStartTime.val();
            if (startDateStr && startDateStr != "") {
                lbStartTime.html(startDateStr);
            } else {
                lbStartTime.html("开始日期");
            }
        });


        //监听日期选择器的改变事件
        $("#ipEndTime").on("change", function endDateChanged() {
            endDateStr = ipEndTime.val();
            if (endDateStr && endDateStr != "") {
                lbEndTime.html(endDateStr);
            } else {
                lbEndTime.html("结束日期");
            }
        });

        //点击报警
        //如果已经生成抢修单 直接跳转到抢修单页
        //如果没有 跳转到报警详情页
        $("#alarmList").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: 'scrolltobottom',
            extra: {
                threshold: 0 //设置距离底部多少距离时触发，默认值为0，数字类型
            }
        }, function(ret, err) {
            if (!isLoading) {
                if (currentPage >= totalPages) {
                    toast("没有更多了");
                    return;
                } else {
                    currentPage++;
                    queryData();
                }
            }
        });
    }

    ctrl.init();
}
