

apiready = function() {
    var ctrl = {
        init: {},
        bind: {},
        prefix: 'https://cdyfile.saas.dianwutong.com/',
        orderData: {
            pics: [],
            serverPicUrls: [],
            uploadPicNum: 0,
            desc: '',
            prId: null,
        },
        handleEmployeeId: '',
        handleEmployeeName: ''
    };

    ctrl.init = function() {
        CommonModel.fitInStatusBar();

        ctrl.orderId = api.pageParam.id;

        ctrl.inspectorGroup = $("#inspector-group");

        ctrl.bind();

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

        // 点击图片预览
        $("#content").on("touchend", ".problem-pic-item", function (e) {
            e.stopPropagation();
            var src = $(this).attr('src');
            
            $('#pic-review img').attr('src', src);
            $('#pic-review').css('display', 'block');
        });

        // 点击预览图片 关闭预览
        $('#pic-review').on("touchend", function () {
            $(this).css('display', 'none');
        });

        // 点击“派单保存”
        $("#save-btn").on("touchend", function () {
            api.confirm({
                title: '',
                msg: '确定要保存吗',
                buttons: ['确定', '取消']
            }, function(ret, err) {
                var index = ret.buttonIndex;
                if (index == 1) { // 确定
                    if (ctrl.handleEmployeeId !== '') {
                        ctrl.saveSystemOrder();
                    } else {
                        ctrl.toast('未选择派单人，请选择后保存');
                    }
                }
            });
        });
    };

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

    // 初始化 工单详情
    ctrl.initOrderDetail = function () {
        ctrl.getOrderDetail();
        ctrl.getInspectorList();
    };

    // 获取工单详情
    ctrl.getOrderDetail = function () {
        var url = '/test/gong-dan/queryById/' + ctrl.orderId;
        
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });
        $api.get(url, function(res, err) {
            api.hideProgress();
            if (err) {
                ctrl.toast("网络请求失败");
            } else {
                if (!res.code || res.code != "200" || !res.data) {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                } else {
                    ctrl.renderOrderDetail(res.data);
                }
            }
        });
    };

    // 渲染工单详情
    ctrl.renderOrderDetail = function (data) {
        $('#pr-name').text(data.prName);
        $('#person').text(data.tiJiaoRenName);
        $('#create-time').text(data.tiJiaoShiJian);
        $('#desc').text(data.miaoShu);
        $('#result-desc').text(data.chuLiMiaoShu || '无');
        $('#result-person').text(data.chuLiRenName || '无');
        
        // 渲染问题照片
        var picContentDom = $('#pic-content');
        if (data.zhaoPian) {
            ctrl.renderPics(picContentDom, data.zhaoPian);
        } else {
            picContentDom.html('无');
        };

        // 渲染处理照片
        var resultPicContentDom = $('#result-pic-content');
        if (data.chuLiZhaoPian) {
            ctrl.renderPics(resultPicContentDom, data.chuLiZhaoPian);
        } else {
            resultPicContentDom.html('无');
        };
    };

    // 渲染 图片
    ctrl.renderPics = function(dom, pics) {
        dom.empty();

        var picsArr = pics.split(',');
        var length = picsArr.length;

        for (var i = 0; i < length; i++) {
            var picUrl = ctrl.prefix + picsArr[i];
            var picDom = '<span class="pic-item"><img class="problem-pic-item" src="'+ picUrl +'" alt=""></span>';

            dom.append(picDom);
        }
    };

    /**
     * 获取人员列表
    */
     ctrl.getInspectorList = function() {
        // 判断当前登陆的账号是否是自己员工
        var flag = true;
        var isZTZ = $api.getStorage('isZTZ');
        var isXJZZ = $api.getStorage('isXJZZ');
        var url;
        var data;
        if (isZTZ || isXJZZ) { // ZTZ 组团长
            flag = true;
            url = '/ems/rest/xj/schedule/task/employee';
        } else { // KHZZ || KHZBZ 客户员工 站长 || 值长
            flag = false;
            url = '/ems/rest/employee/getEmployeeByEmployeeId';
        }
        data = {
            employeeId: $api.getStorage('employeeId')
        };
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });
        $api.get(url, data, function(res, err) {
            api.hideProgress();
            if (err) {
                ctrl.toast("网络请求失败");
            } else {
                if (!res.code || res.code != "200" || !res.body) {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                } else {
                    if (flag) {
                        ctrl.renderInspectorList(res.body)
                    } else {
                        ctrl.renderInspectorList(res.body.records)
                    }
                }
            }
        });
    };

    /**
     * 渲染人员列表
    */
    ctrl.renderInspectorList = function(inspectorlist) {
        var len = inspectorlist.length;
        var temp = '';

        ctrl.inspectorGroup.empty();

        ctrl.inspectorGroup.append('<input class="btn btn-highlight" type="button" value="无" group="inspector" data-inspectorid="" />');

        for (var i = 0; i < len; i++) {
            var inspectorItem = inspectorlist[i]
            var domStr = ''
            
            domStr = '<input class="btn" type="button" value="{inspector}" group="inspector" data-inspectorid="{inspectorId}" />'

            domStr = domStr.replace("{inspector}", inspectorItem.employeeName)
                        .replace("{inspectorId}", inspectorItem.employeeId);

            temp += domStr;
        }

        ctrl.inspectorGroup.append(temp);

        //为巡检人员绑定事件
        ctrl.bindSwitchButtonEvent(ctrl.inspectorGroup.children());
    }

    /**
     * 人员 选择按钮 点击事件绑定
     * @param {zepto object} buttons
     */
     ctrl.bindSwitchButtonEvent = function(buttons) {
        for (var i = 0; i < buttons.length; i++) {
            var btn = $(buttons[i]);
            btn.on('touchend', ctrl.switchButtonClicked);
        }
    }

    /**
     * 人员 按钮点击 事件处理函数
     */
     ctrl.switchButtonClicked = function() {
        var sender = $(this);
        var brothers = sender.parent().children();
        for (var i = 0; i < brothers.length; i++) {
            var inputElement = $(brothers[i]);
            inputElement.removeClass("btn-highlight");
        }
        sender.addClass("btn-highlight");

        ctrl.inspectorButton_clicked(sender);
    }

    // 人员选择
    ctrl.inspectorButton_clicked = function(dom) {
        var employeeId = dom.data('inspectorid');
        var employeeName = dom.val();

        ctrl.handleEmployeeId = employeeId;
        ctrl.handleEmployeeName = employeeName;
    }

    // 派单保存
    ctrl.saveSystemOrder = function () {
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });
        var url = '/test/gong-dan/updateById';
        var data = {
            id: ctrl.orderId,
            chuLiRenId: ctrl.handleEmployeeId,
            chuLiRenName: ctrl.handleEmployeeName,
            zhuangTai: 1
        };

        $api.post(url, data, function(res, err) {
            api.hideProgress();
            if (err) {
                ctrl.toast("网络请求失败");
            } else {
                if (!res.code || res.code != "200") {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                } else {
                    // 返回工单列表页
                    api.sendEvent({
                        name: 'orderListChanged'
                    });

                    ctrl.toast("删除成功");
                    api.closeWin();
                }
            }
        });
    };

    ctrl.init();
}
