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

var current = 1;
var size = 99999;
var totalPages = 1;
var startDate = 1;
var endDate = 1;
var roleId = $api.getStorage("roleId");
var employeeId = $api.getStorage("employeeId");
var isFinish = -1; // 默认选择未接单，3已完成，2巡检中，1未开始，0未接单 -1全部

var isLoading = false;

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

/**
 * 清空巡检安排列表
 */
 function clearInspectionList() {
    $("#inspectionList").empty();
}

/**
 * 向界面中添加一条巡检安排
 * @param {*} record
 */
 function addInspectionItem(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 template = '<div class="alarm" data-inspection-id=\"{inspectionId}\"><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}等共{prCount}个</span>&nbsp;</div><div class="width100 ellipsis color-red">共{inspectProblemCount}个设备缺陷</div></div></div><div class="right text-align-r"><div class="text-gray">{xjDate}</div><div class="height4"></div><div>{inspector}</div></div></div>'
    var prName = record.prName
    var prCount = record.prShuLiang
    var problemCount = record.xunJianWenTi
    var template = ''
    template +='<div class="inspection" data-inspection-id=\"{inspectionId}\">'
    template +=    '<div class="left">'
    template +=        '<div class="icon-con"><img src="../../image/black-pr-icon.png"></div>'
    template +=        '<div class="content font1">'
    template +=            '<div class="pr-name-con"><span class="pr-name">{prName}等共{prCount}个配电室</span>&nbsp;'
    template +=            '</div>'
    template +=            '<div class="width100 ellipsis color-red">共{inspectProblemCount}个设备缺陷</div>'
    template +=        '</div>'
    template +=    '</div>'
    template +=    '<div class="right text-align-r">'
    template +=        '<div class="text-gray">{xjDate}</div>'
    template +=        '<div class="height4"></div>'
    template +=        '<div>{inspector}</div>'
    template +=    '</div>'
    template +='</div>'

    template = template.replace("{inspectionId}", record.id)
            .replace("{prName}", prName)
            .replace("{prCount}", prCount)
            .replace("{inspectProblemCount}", problemCount)
            .replace("{xjDate}", record.xunJianShiJian || '')
            .replace("{inspector}", record.jieDanRen || '')
    
    inspectionList.append(template);
}

/**
 * 查询巡检单列表
 */
function queryData() {
    api.showProgress();
    
    if (startDateStr) {
        startDate = CommonModel.getFomattedDate((new Date(startDateStr.replace(/-/g, '/'))).getTime(), 'yyyy-MM-dd');
    } else {
        // 默认开始日期为当天
        startDate = CommonModel.getFomattedDate(new Date().getTime(), 'yyyy-MM-dd');
    }

    if (endDateStr) {
        endDate = CommonModel.getFomattedDate((new Date(endDateStr.replace(/-/g, '/'))).getTime(), 'yyyy-MM-dd');
    } else {
        // 默认开始日期为当天
        endDate = CommonModel.getFomattedDate(new Date().getTime(), 'yyyy-MM-dd');
    }

    var url = '/test/xun-jian-dan/queryByListWithDate/'
            + current + '/'
            + size + '/'
            + startDate + 'T' + endDate + '/'
            + roleId + '/'
            + employeeId + '/'
            + isFinish;
    isLoading = true;
    api.showProgress({
        title: '载入中...',
        text: '请稍后',
        modal: false
    });
    $api.get(url, function(res, err) {
        isLoading = false;
        api.hideProgress();
        if (err) {
            toast("网络请求失败");
        } else {
            if (!res.code || res.code != "200" || !res.data) {
                toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
            } else {
                var records = res.data.records
                totalPages = res.total;
                if (records.length && records.length > 0) {
                    emptyTips.hide();
                    for (var i = 0; i < records.length; i++) {
                        var record = records[i];
                        addInspectionItem(record);
                    }
                } else {
                    //如果没有记录，则显示查询不到数据的提示
                    emptyTips.show();
                }

            }
        }
    });
}

/**
 * 初查询巡检单列表
 */
 function getInspectionList() {
    clearInspectionList();
    queryData();
}

// 巡检单创建完成 触发的事件处理
function inspectionCreateChanged(ret, err) {
    getInspectionList();
};

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

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

        ipStartTime = $("#ipStartTime");
        lbStartTime = $("#lbStartTime");
        ipEndTime = $("#ipEndTime");
        lbEndTime = $("#lbEndTime");
        inspectionList = $("#inspectionList");
        emptyTips = $("#empty-tips");

        // 判断当前角色是否是组团长、客户站长、客户值长,控制新增按钮
        var isZTZ =  $api.getStorage("isZTZ");
        var isKHZZ =  $api.getStorage("isKHZZ");
        var isKHZBZ =  $api.getStorage("isKHZBZ");
        if (isZTZ || isKHZZ || isKHZBZ) {
            $("#create-inspection-btn").show()
        } else {
            $("#create-inspection-btn").hide()
        }

        //巡检任务信息发生变化
        api.addEventListener({
            name: 'inspectionCreateChanged'
        }, inspectionCreateChanged);

        ctrl.bind();

        getInspectionList();
    }
    ctrl.bind = function() {
        var height = $(window).height() - $("header").height() - $(".fix-top").height();
        $(".inspectionList-content").css("height", height);
        //点击返回按钮
        $api.addEvt($api.dom("#back"), "touchend", function() {
            api.closeWin();
        })

        // 点击“全部”
        $("#all").on("touchend", function() {
            isFinish = -1
            $(this).siblings('.bg-touch').removeClass('bg-yellow')
            $(this).addClass('bg-yellow')
            getInspectionList();
        });

        // 点击“未接单”
        $("#btn-accept").on("touchend", function() {
            isFinish = 0
            $(this).siblings('.bg-touch').removeClass('bg-yellow')
            $(this).addClass('bg-yellow')
            getInspectionList();
        });

        // 点击“已完成”
        $("#btn-finished").on("touchend", function() {
            isFinish = 3
            $(this).siblings('.bg-touch').removeClass('bg-yellow')
            $(this).addClass('bg-yellow')
            getInspectionList();
        });

        // 点击“巡检中”
        $("#btn-inspecting").on("touchend", function() {
            isFinish = 2
            $(this).siblings('.bg-touch').removeClass('bg-yellow')
            $(this).addClass('bg-yellow')
            getInspectionList();
        });
        
        // 点击“未开始”
        $("#btn-nostart").on("touchend", function() {
            isFinish = 1
            $(this).siblings('.bg-touch').removeClass('bg-yellow')
            $(this).addClass('bg-yellow')
            getInspectionList();
        });

        // 点击“查询”
        $("#btn-query").on("touchend", function() {
            getInspectionList();
        });

        // 点击“新增巡检任务”
        $("#create-inspection-btn").on("touchend", function() {
            //侧边栏的宽度为250
            var edge = api.winWidth * 0.2;
            (edge < 0) && (edge = 60);
            api.openDrawerLayout({
                'name': 'inspectionArrangeCreate',
                'url': 'widget://html/feature/inspectionArrangeCreate.html',
                'pageParam': {
                    inspectionId: ''
                },
                'rightPane': {
                    edge: edge,
                    name: 'inspectionArrangeCreateRightPanel',
                    url: 'widget://html/feature/inspectionArrangeCreateRightPanel.html',
                },
            })
        });

         //监听滚动到底部事件
        //  api.addEventListener({
        //     name: 'scrolltobottom',
        //     extra: {
        //         threshold: 0 //设置距离底部多少距离时触发，默认值为0，数字类型
        //     }
        // }, function(ret, err) {
        //     if (!isLoading) {
        //         if (currentPage >= totalPages) {
        //             toast("没有更多了");
        //             return;
        //         } else {
        //             current++;
        //             getInspectionList();
        //         }
        //     }
        // });

        //监听日期选择器的改变事件
        $("#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("结束日期");
            }
        });

        //点击巡检单 跳转到详情页
        $("#inspectionList").on("touchend", ".inspection", function() {
            var inspectionId = $(this).data("inspection-id");
            // 根据当前点击的巡检单状态，跳转到不同页。未接单、未开始状态跳转到编辑页，其他跳转到详情页
            if (isFinish == 0 || isFinish == 1) { // 未接单、未开始
                //侧边栏的宽度为250
                var edge = api.winWidth * 0.2;
                (edge < 0) && (edge = 60);
                api.openDrawerLayout({
                    'name': 'inspectionArrangeCreate',
                    'url': 'widget://html/feature/inspectionArrangeCreate.html',
                    'pageParam': {
                        id: inspectionId
                    },
                    'rightPane': {
                        edge: edge,
                        name: 'inspectionArrangeCreateRightPanel',
                        url: 'widget://html/feature/inspectionArrangeCreateRightPanel.html',
                        'pageParam': {
                            id: inspectionId
                        },
                    },
                })
            } else {
                api.openWin({
                    'name': 'inspectionArrangeDetail',
                    'url': 'widget://html/feature/inspectionArrangeDetail.html',
                    'pageParam': {
                        id: inspectionId
                    }
                })
            }
        });

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

    }

    ctrl.init();
}
