apiready = function() {
    var ctrl = {
        roleId: $api.getStorage('roleId'),
        employeeId: $api.getStorage('employeeId'),
        tabType: 'inspection-list',
        isFinish: 1,
        
        init: {},
        bind: {},
    }

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

        //巡检单 状态发生变化
        api.addEventListener({
            name: 'inspectionTaskChanged'
        }, ctrl.inspectionTaskChanged);

        ctrl.bind();
        
        ctrl.initInspectionListTab();
    }
    ctrl.bind = function() {

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

            $api.addCls(this, "active");
            $api.removeCls($api.dom("#inspection-task-tab"), "active");
            $api.css($api.dom("#inspection-list-panel"), 'display:block');
            $api.css($api.dom("#inspection-task-panel"), 'display:none');
            $api.css($api.dom('#inspection-empty-tips'), "display:none");

            ctrl.tabType = 'inspection-list'

            // 初始化 巡检单 tab
            ctrl.initInspectionListTab();

        }, false);

        //点击 “巡检任务” tab按钮
        $api.addEvt($api.dom("#inspection-task-tab"), "touchend", function () {
            if (ctrl.tabType == 'inspection-task') {
                return
            }

            $api.addCls(this, "active");
            $api.removeCls($api.dom("#inspection-list-tab"), "active");
            $api.css($api.dom("#inspection-task-panel"), 'display:block');
            $api.css($api.dom("#inspection-list-panel"), 'display:none');
            $api.css($api.dom('#inspection-empty-tips'), "display:none");

            ctrl.tabType = 'inspection-task';

            // 初始化 巡检任务 tab
            ctrl.initInspectionTaskTab();

        }, false);

        //跳转到 巡检单 详情页
        $("#inspection-list-panel").on("touchend", ".left", function() {
            var inspectionid = $(this).data("inspectionid");

            api.openWin({
                name: 'inspectionListDetail',
                url: '../inspection/inspectionListDetail.html',
                pageParam: {
                    inspectionid: inspectionid
                }
            });
        });

        // 点击 “接单”
        $('#inspection-list-panel').on("touchend", ".accept-btn", function(e) {
            e.stopPropagation();

            var inspectId = $(this).data("id");
            api.confirm({
                title: '',
                msg: '确定要接单吗',
                buttons: ['确定', '取消']
            }, function(ret, err) {
                var index = ret.buttonIndex;
                if (index == 1) { // 确定
                    ctrl.acceptInspection(inspectId);
                }
            });
        });

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

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

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

        // 跳转到 巡检任务 详情页
        $("#inspection-content").on("touchend", ".inspection", function() {
            var inspectionid = $(this).data("inspectionid");
            // status：0 未接单，1 未开始，2 巡检中，3 已完成
            var status = $(this).data("status");

            api.openWin({
                name: 'inspectionTaskDetail',
                url: '../inspection/inspectionTaskDetail.html',
                pageParam: {
                    inspectionid: inspectionid,
                    status: status
                }
            });
        });

        // 防止退出后继续轮询
        api.addEventListener({
            name: 'loginout'
        }, function(ret, err) {
           
        });

        //下拉刷新
        api.setRefreshHeaderInfo({
            bgColor: "#CCCCCC",
            textColor: "#FFFFFF"
        }, function(ret, err) {
            // 根据当前选择的tab 刷新对应的内容
            if (ctrl.tabType == 'inspection-list') { // 巡检单
                ctrl.initInspectionListTab();
            } else if (ctrl.tabType == 'inspection-task') { // 巡检任务
                ctrl.initInspectionTaskTab()
            }
        })
    };

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

    // 巡检任务中的巡检单状态改变 触发的事件处理
    ctrl.inspectionTaskChanged = function(ret, err) {
        ctrl.initInspectionTaskTab();
    };

    // 初始化 巡检单 tab
    ctrl.initInspectionListTab = function () {
        ctrl.getInspectionList();
    };

    // 获取 巡检单 列表
    ctrl.getInspectionList = function() {
        //显示载入动画
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        var startDate = $api.getFormattedDate('yyyy-MM-dd', new Date());
        var endDate = '2100-01-01';
        var url = '/test/xun-jian-dan/queryByListWithDate/1/9999/'
                + startDate + 'T' + endDate + '/'
                + this.roleId + '/'
                + this.employeeId + '/0';

        $api.get(url, function(res, err) {
            //隐藏载入动画
            api.hideProgress();
            // 隐藏下拉刷新提示
            api.refreshHeaderLoadDone();

            if (res && res.code == 200 && res.data) {

                var list = res.data.records || [];
                var length = list.length;

                if (length > 0) {
                    $api.css($api.dom('#inspection-list-panel'), "display:block");
                    $api.css($api.dom('#inspection-empty-tips'), "display:none");
                    $('#inspection-list-panel').empty();

                    for (var i = 0; i < length; i++) {
                        ctrl.renderInspectionList(list[i]);
                    }
                } else {
                    $api.css($api.dom('#inspection-list-panel'), "display:none");
                    $api.css($api.dom('#inspection-empty-tips'), "display:block");
                }

            } else {
                ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
            }
        });
    };

    // 渲染 巡检单 列表
    ctrl.renderInspectionList = function(record) {
        var prName = record.prName;
        var prCount = record.prShuLiang;
        var problemCount = record.xunJianWenTi;
        var id = record.id;
        var xunJianShiJian = record.xunJianShiJian;
        var template = ''
        template +='<div class="inspection">'
        template +=    '<div class="left" data-inspectionid=\"{inspectionId}\">'
        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>'
        template +=             '<button class="accept-btn" data-id="{id}">接单</button>'
        template +=         '</div>'
        template +=    '</div>'
        template +='</div>'
    
        template = template.replace("{inspectionId}", id)
                .replace("{prName}", prName + '等' || '')
                .replace("{prCount}", prCount)
                .replace("{inspectProblemCount}", problemCount)
                .replace("{xjDate}", xunJianShiJian || '')
                .replace("{id}", id);
        
        $('#inspection-list-panel').append(template);
    };

    // 接单
    ctrl.acceptInspection = function(inspectId) {
        //显示载入动画
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        var url = '/test/xun-jian-dan/insert';
        var data = {
            id: inspectId,
            employeeId: this.employeeId,
            roleId: this.roleId,
            jieDanRenId: this.employeeId
        };

        $api.post(url, data, function(res, err) {
            //隐藏载入动画
            api.hideProgress();

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

                ctrl.toast("接单成功");

                ctrl.initInspectionListTab();

            } else {
                ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
            }
        });
    };

    // 初始化 巡检任务 panel
    ctrl.initInspectionTaskTab = function() {
        ctrl.getInspectionTask();
    };

    // 获取 巡检任务 列表
    ctrl.getInspectionTask = function() {
        //显示载入动画
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        var url = '/test/xun-jian-dan/queryByListByEmployeeId/1/9999/'
                + this.employeeId + '/'
                + this.isFinish;

        $api.get(url, function(res, err) {
            //隐藏载入动画
            api.hideProgress();
            // 隐藏下拉刷新提示
            api.refreshHeaderLoadDone();

            if (res && res.code == 200 && res.data) {

                var list = res.data.records || [];
                var length = list.length;

                if (length > 0) {
                    $api.css($api.dom('#inspection-content'), "display:block");
                    $api.css($api.dom('#inspection-empty-tips'), "display:none");
                    $('#inspection-content').empty();

                    for (var i = 0; i < length; i++) {
                        ctrl.renderInspectionTask(list[i]);
                    }
                } else {
                    $api.css($api.dom('#inspection-content'), "display:none");
                    $api.css($api.dom('#inspection-empty-tips'), "display:block");
                }

            } else {
                ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
            }
        });
    };

    // 渲染巡检任务列表
    ctrl.renderInspectionTask = function(record) {
        var prName = record.prName;
        var prCount = record.prShuLiang;
        var problemCount = record.xunJianWenTi;
        var id = record.id;
        var xunJianShiJian = record.xunJianShiJian;
        var status = record.shiFouWanCheng;
        var template = ''
        template +='<div class="inspection" data-inspectionid=\"{inspectionId}\" data-status=\"{status}\">'
        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>{jiedanren}</div>'
        template +=    '</div>'
        template +='</div>'
    
        template = template.replace("{inspectionId}", id)
                .replace("{status}", status)
                .replace("{prName}", (prName || '') + '  ')
                .replace("{prCount}", prCount || '0')
                .replace("{inspectProblemCount}", problemCount || '0')
                .replace("{xjDate}", xunJianShiJian || '')
                .replace("{jiedanren}", record.jieDanRen || '');
        
        $('#inspection-content').append(template);
    };

    ctrl.init();
}
