apiready = function() {
    var ctrl = {
        init: {},
        bind: {},
        employeeId: null,
        roleId: null,
        orderContent: null,
        emptyTips: null,
        orderType: -1, // 状态 -1：全部 0：未接单 1：未处理 2:处理中 3：已处理
        currentPage: 1,
        pageSize: 10,
        isLoading: false,
        startDateStr: '',
        endDateStr: '',
    }

    ctrl.init = function() {
        // 适配安卓状态栏
        CommonModel.fitInStatusBar();
        var searcherTop = $('#heightHeader').height();
        $('#searcher').css('top',searcherTop);
        
        ctrl.employeeId = $api.getStorage('employeeId');
        ctrl.roleId = $api.getStorage('roleId');
        ctrl.emptyTips = $("#empty-tips");
        ctrl.orderContent = $('#systemOrderList');
        ctrl.ipStartTime = $("#ipStartTime");
        ctrl.lbStartTime = $("#lbStartTime");
        ctrl.ipEndTime = $("#ipEndTime");
        ctrl.lbEndTime = $("#lbEndTime");

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

        ctrl.bind();

        ctrl.initOrderList();
    }
    ctrl.bind = function() {
        //点击返回按钮
        $api.addEvt($api.dom("#back"), "touchend", function() {
            api.closeWin();
        });

        // 开始日期 监听日期选择器的改变事件
        $("#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.initOrderList);

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

        // 点击“未接单” btn
        $("#btn-unaccpted").on("touchend", function() {
            ctrl.orderType = 0;
            ctrl.currentPage = 1;
            $(this).siblings('.bg-touch').removeClass('bg-yellow');
            $(this).addClass('bg-yellow');
            ctrl.initOrderList();
        });

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

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

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

        // 点击 “创建工单”
        $("#create-systemOrder-btn").on("touchend", function() {
            api.openWin({
                'name': 'systemOrderCreate',
                'url': 'widget://html/feature/systemOrderCreate.html'
            });
        });

        // 点击系统工单 ，跳转到详情页
        $("#systemOrderList").on("touchend", ".left", function() {
            var orderId = $(this).data("systemorderid");
            var type = $(this).data("type");

            api.openWin({
                'name': 'systemOrderDetail',
                'url': 'widget://html/feature/systemOrderDetail.html',
                'pageParam': {
                    id: orderId,
                    type: type
                }
            })
        });

        // 点击 派单
        $("#systemOrderList").on("touchend", ".delivery-btn", function(e) {
            e.stopPropagation();

            var orderId = $(this).data("orderid");

            api.openWin({
                'name': 'systemOrderEdit',
                'url': 'widget://html/feature/systemOrderEdit.html',
                'pageParam': {
                    id: orderId
                }
            })
        });

        // 下拉刷新
        // api.setRefreshHeaderInfo({
        //     bgColor: "#CCCCCC",
        //     textColor: "#FFFFFF"
        // }, function(ret, err) {
        //     // 根据当前选择的tab 刷新对应的内容
        //     ctrl.currentPage = 1;
        //     ctrl.getOrderList();
        // });

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

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

    // 创建工单完成 触发的事件处理
    ctrl.orderListChanged = function(ret, err) {
        ctrl.initOrderList();
    };

    // 初始化系统工单列表
    ctrl.initOrderList = function () {
        ctrl.clearOrderList();

        ctrl.getOrderList();
    };

    // 清空工单列表
    ctrl.clearOrderList = function () {
        this.orderContent.empty();
    };

    // 获取工单列表
    ctrl.getOrderList = function () {
        api.showProgress();

        var url = '/test/gong-dan/queryByList/'
            + this.currentPage + '/'
            + this.pageSize + '/'
            + this.orderType + '/'
            + this.employeeId + '/'
            + this.roleId;

        var data = {};

        if (ctrl.startDateStr) {
            data.start = CommonModel.getFomattedDate((new Date(ctrl.startDateStr.replace(/-/g, '/'))).getTime(), 'yyyy-MM-dd') + ' 00:00:00';
        };

        if (ctrl.endDateStr) {
            data.end = CommonModel.getFomattedDate((new Date(ctrl.endDateStr.replace(/-/g, '/'))).getTime(), 'yyyy-MM-dd') + ' 23:59:59';
        };

        $api.post(url, data, function(res, err) {
            if (err) {
                ctrl.toast("网络请求失败");
                api.hideProgress();
            } else {
                if (!res.code || res.code != "200") {
                    ctrl.toast("服务器响应错误");
                    api.hideProgress();
                } else {
                    ctrl.totalPages = res.data.pages;
                    ctrl.renderOrderList(res.data.records);
                }
            }
        });
    };

    // 渲染 工单列表
    ctrl.renderOrderList = function (records) {
        var length = records.length;
        if (length > 0) {
            this.orderContent.show();
            this.emptyTips.hide();

            for (var i = 0; i < length; i++) {
                var item = records[i];
                ctrl.createOrderDom(item);
            }
        } else {
            this.orderContent.hide();
            this.emptyTips.show();
        };

        api.hideProgress();
    };

    // 创建 工单 DOM
    ctrl.createOrderDom = function (item) {
        var id = item.id;
        var prName = item.prName;
        var miaoShu = item.miaoShu;
        var tiJiaoShiJian = item.tiJiaoShiJian.split(' ')[0];
        var tiJiaoRenName = item.tiJiaoRenName;
        var type = item.zhuangTai;
        var textColor = '';
        var status = '';

        // -1：全部 0：未接单 1：未处理 2:处理中 3：已处理
        switch (type) {
            case 0:
                textColor = 'text-red';
                status = '未接单';
                break;
            case 1:
                textColor = 'text-gray';
                status = '未处理';
                break;
            case 2:
                textColor = 'text-yellow';
                status = '处理中';
                break;
            case 3:
                textColor = 'text-green';
                status = '已完成';
                break;
        };

        var template = ''
        template += '<div class="systemOrder">'
        template +=     '<div class="left" data-systemorderid="{id}" data-type={type}>'
        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">{miaoShu}</div>'
        template +=         '</div>'
        template +=     '</div>'
        template +=     '<div class="right text-align-r">'
        template +=         '<div class="text-gray">{time}'
        template +=             '<span class="{textColor}" style="margin-left: 0.4rem;">{status}</span>'
        template +=         '</div>'
        template +=         '<div class="height4"></div>'
        template +=         '<div>创建人: {person}'
        if (type == 0) {
            template +=             '<button class="delivery-btn" data-orderid={orderid}>派单</button></div>'
        }
        template +=         '</div>'
        template +=     '</div>'
        template += '</div>'

        template = template.replace("{id}", id)
                .replace("{type}", type)
                .replace("{prName}", prName)
                .replace("{miaoShu}", miaoShu)
                .replace("{time}", tiJiaoShiJian)
                .replace("{textColor}", textColor)
                .replace("{status}", status)
                .replace("{person}", tiJiaoRenName)
                .replace("{orderid}", id);
        
        ctrl.orderContent.append(template);
    };

    ctrl.init();
}
