apiready = function () {
    var ctrl = {
        currentPage: 1,
        pageSize: 20,
        status: null, // null 全部 0 未处理 1 处理中 2 处理完成
        init: {},
        bind: {},
        toast: {},
        getBugList: {},
        startDateStr: '',
        endDateStr: '',
        prId: ''
    }
    ctrl.init = function () {
        var height = $('.select-panel').height();
        $('.select-placeholder').css('height', height);

        ctrl.isEmployee = $api.getStorage('isEmployee');

        ctrl.ipStartTime = $("#ipStartTime");
        ctrl.lbStartTime = $("#lbStartTime");
        ctrl.ipEndTime = $("#ipEndTime");
        ctrl.lbEndTime = $("#lbEndTime");

        ctrl.bind();

        ctrl.getBugList();
    };

    //判断是不是在体验模式
    ctrl.isCus = function () {
        if ($api.getStorage('cus')) {
            return true;
        } else {
            return false;
        }
    };

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

    ctrl.bind = function () {
        // 选择条件
        $('#select-btns .btn').on('touchend', function () {
            $('#select-btns .btn').removeClass('btn-active');
            $(this).addClass('btn-active');
            var status = $(this).attr('status');
            if (status == -1) {
                ctrl.status = null;
            } else {
                ctrl.status = status;
            }

            ctrl.currentPage = 1;
            ctrl.getBugList();
        })

        // 查看详情
        $("#inspect-bugs").on('touchend', '.bug-item', function () {
            var id = $(this).data('id');
            api.openWin({
                name: 'inspectBug',
                url: './inspectBug.html',
                pageParam: {
                    id: id
                }
            });
        });

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

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

        // 点击 查询
        $("#btn-query").on("touchend", ctrl.getBugList);

        // 点击 选择配电室 按钮
        $("#pr-select-btn").on("touchend", function () {
            ctrl.showRightPanel();
        });

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

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

        // 上拉加载更多
        api.addEventListener({
            name: 'scrolltobottom'
        }, function (ret, err) {
            ctrl.currentPage++;
            if (ctrl.currentPage > ctrl.totalPages) {
                ctrl.toast("没有更多了");
                return;
            }
            ctrl.getBugList();

        });
    };

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

    // 配电室选择改变 触发事件
    ctrl.filterSelectionChanged = function (ret, err) {
        ctrl.prId = ret.value.prId; // 配电室Id
        ctrl.prName = ret.value.prName; // 配电室Id
        ctrl.currentPage = 1;

        $('#prName').text(ctrl.prName);

        ctrl.getBugList();
    };

    // 获取问题列表
    ctrl.getBugList = function () {
        //显示载入动画
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });
        var url = '/ems/rest/xj/problem/page';
        var data = null;

        if (isEmployee) { // 员工登陆
            data = {
                page: ctrl.currentPage,
                pageSize: ctrl.pageSize,
                employeeId: $api.getStorage('employeeId'),
                roleId: $api.getStorage('roleId'),
                status: ctrl.status
            };
        } else { // 客户登陆
            data = {
                page: ctrl.currentPage,
                pageSize: ctrl.pageSize,
                cusId: $api.getStorage('cusId'),
                status: ctrl.status
            };
        };

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

        var isEmployee = $api.getStorage('isEmployee');
        if (isEmployee) {
            data = {
                page: ctrl.currentPage,
                pageSize: ctrl.pageSize,
                prId: ctrl.prId,
                employeeId: $api.getStorage('employeeId'),
                roleId: $api.getStorage('roleId'),
                status: ctrl.status
            }
        }

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

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

        if (ctrl.status == null) {
            delete data['status'];
        };

        $api.get(url, data, function (res, err) {
            if (err) {
                //隐藏载入动画
                api.hideProgress();
                ctrl.toast("网络请求失败");
            } else {
                if (res.code === 200 || res.code === 404) {
                    ctrl.renderInspectBugList(res);
                } else {
                    //隐藏载入动画
                    api.hideProgress();
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }
        })
    }
    ctrl.renderInspectBugList = function (res) {
        ctrl.bugList = res.body.records;
        ctrl.totalPages = res.body.totalPages;
        $('#total-count').text(res.body.totalCount);
        if (ctrl.currentPage == 1) {
            $api.html($api.dom('#inspect-bugs'), '');
        }
        if (res.code == 404) {
            //隐藏载入动画
            api.hideProgress();
            api.refreshHeaderLoadDone();
            $api.css($api.dom('#inspect-bugs'), 'display:none');
            $api.css($api.dom('#inspect-bug-empty-tips'), "display:block");
        } else {
            var bugList = ctrl.bugList;
            var length = bugList.length;
            for (var i = 0; i < length; i++) {
                $("#inspect-bugs").append(ctrl.getBugDom(bugList[i]));
            }
            //隐藏载入动画
            api.hideProgress();
            $api.css($api.dom('#inspect-bugs'), "display:block");
            $api.css($api.dom('#inspect-bug-empty-tips'), "display:none");
        }
    }
    ctrl.getBugDom = function (item) {
        if (ctrl.isCus()) {
            //如果是体验账号，拦截替换配电室名称
            item.prName = $api.guestPrName;
            item.problemDesc = item.problemDesc.replace($api.guestKeysPattern, $api.guestName);
        }
        var bugGrade = ['一般', '严重', '危急'];
        var statusColor = ['text-red', 'text-yellow', 'text-green']; // 未处理，处理中，已处理
        var statusContent = ['未处理', '处理中', '已处理'];
        var dateUtil = new DateUtils();
        dateUtil.setDate(item.createTime);
        var time = item.createTime && dateUtil.getFormattedDate('yyyy-MM-dd hh:mm');
        var tpl = '<div class="bug-item bg-touch" data-id="' + item.problemId + '">';
        tpl += '<div class="left">';
        tpl += '<div class="icon-con"><img src="../../../image/black-pr-icon.png"></div>';
        tpl += '<div class="content font1">';
        tpl += '<div class="pr-name-con"><span class="pr-name width100 ellipsis">' + item.prName + '</span>&nbsp;</div>'
        tpl += '<div class="height4"></div>';
        tpl += '<div class="width100 ellipsis color-title">' + item.problemDesc + '</div>';
        tpl += '</div></div>';
        tpl += '<div class="right text-align-r">';
        tpl += '<div class="color-title">' + time + '</div>';
        tpl += '<div class="height4"></div>';
        tpl += '<div class="status ' + statusColor[item.status] + '">' + statusContent[item.status] + '</div>';
        tpl += '<div class="height4"></div>';
        // tpl += '<div class="status text-gray">' + bugGrade[item.quesGrade] + '</div>';
        tpl += '</div></div>';
        return tpl;
    }
    ctrl.init();
}
