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

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

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

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

        //点击 “工单列表” tab按钮
        $api.addEvt($api.dom("#order-list-tab"), "touchend", function () {
            if (ctrl.tabType == 'order-list') {
                return
            };

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

            ctrl.tabType = 'order-list'

            // 初始化 工单 tab
            ctrl.initOrderListTab();

        }, false);

        //点击 “我的工单” tab按钮
        $api.addEvt($api.dom("#order-task-tab"), "touchend", function () {
            if (ctrl.tabType == 'order-task') {
                return
            };

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

            ctrl.tabType = 'order-task';

            // 初始化 我的工单 tab
            ctrl.initOrderTaskTab();

        }, false);

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

            api.openWin({
                name: 'systemOrderDetail',
                url: '../systemOrder/systemOrderDetail.html',
                pageParam: {
                    orderid: orderid,
                    status: 0
                }
            });
        });

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

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

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

        // 点击“处理中” btn
        $("#btn-handling").on("touchend", function() {
            ctrl.status = 2;
            $(this).siblings('.bg-touch').removeClass('bg-yellow');
            $(this).addClass('bg-yellow');
            ctrl.initOrderTaskTab();
        });

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

        // 跳转到 我的工单 详情页
        $("#order-content").on("touchend", ".order", function() {
            var orderid = $(this).data("orderid");
            // status：1 未处理，2 处理中，3 已完成
            var status = $(this).data("status");

            if (status == 3) {
                api.openWin({
                    name: 'systemOrderDetail',
                    url: '../systemOrder/systemOrderDetail.html',
                    pageParam: {
                        orderid: orderid,
                        status: 3
                    }
                });
            } else {
                api.openWin({
                    name: 'systemOrderEdit',
                    url: '../systemOrder/systemOrderEdit.html',
                    pageParam: {
                        orderid: orderid,
                        status: status
                    }
                });
            }

        });

        //下拉刷新
        api.setRefreshHeaderInfo({
            bgColor: "#CCCCCC",
            textColor: "#FFFFFF"
        }, function(ret, err) {
            // 根据当前选择的tab 刷新对应的内容
            if (ctrl.tabType == 'order-list') { // 工单列表
                ctrl.initOrderListTab();
            } else if (ctrl.tabType == 'order-task') { // 我的工单
                ctrl.initOrderTaskTab();
            }
        });
    };

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

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

    // 初始化 工单 tab
    ctrl.initOrderListTab = function () {
        ctrl.getOrderList();
    };

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

        var url = '/test/gong-dan/queryByList/1/9999/0/'
                + this.employeeId + '/'
                + this.roleId;

        $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('#order-list-panel'), "display:block");
                    $api.css($api.dom('#order-empty-tips'), "display:none");
                    $('#order-list-panel').empty();

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

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

    // 渲染 工单 列表
    ctrl.renderOrderList = function(record) {
        var prName = record.prName;
        var tiJiaoRenName = record.tiJiaoRenName;
        var id = record.id;
        var miaoShu = record.miaoShu;
        var template = ''
        template +='<div class="order">'
        template +=    '<div class="left" data-orderid=\"{orderid}\">'
        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}配电室</span>&nbsp;'
        template +=            '</div>'
        template +=            '<div class="width100 ellipsis color-red desc">{miaoShu}</div>'
        template +=        '</div>'
        template +=    '</div>'
        template +=    '<div class="right text-align-r">'
        template +=        '<div class="text-gray">创建人:<span>{tiJiaoRenName}</span></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("{orderid}", id)
                .replace("{prName}", prName)
                .replace("{miaoShu}", miaoShu)
                .replace("{tiJiaoRenName}", tiJiaoRenName)
                .replace("{id}", id);
        
        $('#order-list-panel').append(template);
    };

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

        var url = '/test/gong-dan/gongDanJieDan';
        var data = {
            id: orderId,
            chuLiRenId: this.employeeId
        };

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

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

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

                ctrl.initOrderListTab();

            } else {
                ctrl.toast(res.msg);
            }
        });
    };

    // 初始化 我的工单 panel
    ctrl.initOrderTaskTab = function() {
        ctrl.getOrderTask();
    };

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

        var url = '/test/gong-dan/queryChuLiRenByList/1/9999/'
                + this.status + '/'
                + this.employeeId;

        $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('#order-content'), "display:block");
                    $api.css($api.dom('#order-empty-tips'), "display:none");
                    $('#order-content').empty();

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

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

    // 渲染 我的工单 列表
    ctrl.renderOrderTask = function(record) {
        var id = record.id;
        var status = record.zhuangTai;
        var prName = record.prName;
        var tiJiaoRenName = record.tiJiaoRenName;
        var chuLiRenName = record.chuLiRenName;
        var miaoShu = record.miaoShu;
        var template = ''
        template +='<div class="order" data-orderid=\"{orderid}\" 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}配电室</span>&nbsp;'
        template +=            '</div>'
        template +=            '<div class="width100 ellipsis color-red desc">{miaoShu}</div>'
        template +=        '</div>'
        template +=    '</div>'
        template +=    '<div class="right text-align-r">'
        template +=        '<div class="text-gray">创建人:<span>{tiJiaoRenName}</span></div>'
        template +=        '<div class="height4"></div>'
        template +=         '<div>处理人:{chuLiRenName}</div>'
        template +=    '</div>'
        template +='</div>'
    
        template = template.replace("{orderid}", id)
                .replace("{status}", status)
                .replace("{prName}", prName)
                .replace("{miaoShu}", miaoShu)
                .replace("{tiJiaoRenName}", tiJiaoRenName)
                .replace("{chuLiRenName}", chuLiRenName);
        
        $('#order-content').append(template);
    };

    ctrl.init();
}
