

apiready = function() {
    var ctrl = {
        init: {},
        bind: {},
        orderData: {
            pics: [],
            serverPicUrls: [],
            uploadPicNum: 0,
            desc: '',
            prId: null,
        },
    };

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

        ctrl.employeeId = $api.getStorage('employeeId');
        ctrl.roleId = $api.getStorage('roleId');
        ctrl.prListDom = $('#pr-list');
        ctrl.inspectorGroup = $("#inspector-group");

        ctrl.bind();

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

        // 点击 配电室下拉选择框
        $api.addEvt($api.dom("#pr-selected"), "touchend", function() {
            $('.pr-picker-modal').toggleClass('show');
        });

        // 选择配电室
        $("#pr-list").on("touchend", ".pr", function () {
            ctrl.orderData.prId = $(this).data('prid');

            var prName = $(this).data('prname');
            $('#pr-name').text(prName);

            $('.pr-picker-modal').removeClass('show');
        });

        // 点击 相册选择 添加 设备缺陷图片
        $("#pic-add-btn").on("touchend", function () {
            var picContentDom = $('#pic-content');
            var params = {
                sourceType: 'library',
                // sourceType: 'camera',
                // sourceType: 'album',
                destinationType: 'base64'
            }
            api.getPicture(params, function(ret, err){
                if (ret && ret.data) {
                    // 创建图片预览dom
                    var picItemDom = '<span class="pic-item"><i></i><img class="problem-pic-item" src="{{url}}" alt=""></span>'
                    var dom = picItemDom.replace('{{url}}', ret.data)
                    picContentDom.prepend(dom)

                    // 保存 图片 base64 和 url
                    ctrl.orderData.pics.push({
                        url: ret.data
                    });
                }
            })
        });

        // 点击 照相机 拍照添加 设备缺陷图片
        $("#camera-btn").on("touchend", function () {
            var picContentDom = $('#pic-content');
            var params = {
                // sourceType: 'library',
                sourceType: 'camera',
                // sourceType: 'album',
                destinationType: 'base64'
            }
            api.getPicture(params, function(ret, err){
                if (ret && ret.data) {
                    // 创建图片预览dom
                    var picItemDom = '<span class="pic-item"><i></i><img class="problem-pic-item" src="{{url}}" alt=""></span>'
                    var dom = picItemDom.replace('{{url}}', ret.data)
                    picContentDom.prepend(dom)

                    // 保存 图片 base64 和 url
                    ctrl.orderData.pics.push({
                        url: ret.data
                    });
                }
            })
        });

        // 点击图片预览
        $("#pic-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');
        });

        // 图片 删除按钮
        $("#pic-content").on("touchend", "i", function (e) {
            e.stopPropagation();

            var _this = this;

            api.confirm({
                title: '',
                msg: '确定要删除吗',
                buttons: ['确定', '取消']
            }, function(ret, err) {
                var index = ret.buttonIndex;
                if (index == 1) { // 确定
                    var url = $($(_this).siblings('img')[0]).attr('src');
        
                    $(_this).parent('.pic-item').remove();

                    // 从 ctrl.orderData.pics 中删除对应url
                    ctrl.orderData.pics = ctrl.orderData.pics.filter(function (item) {
                        return item.url != url;
                    });
                }
            });

        });

        // 点击“保存”
        $("#save-btn").on("touchend", function () {
            api.confirm({
                title: '',
                msg: '确定要保存吗',
                buttons: ['确定', '取消']
            }, function(ret, err) {
                var index = ret.buttonIndex;
                if (index == 1) { // 确定
                    ctrl.save();
                }
            });
        });
    };

    // 初始化 prList 下拉框
    ctrl.initPrList = function () {
        ctrl.getPrList();
        ctrl.getInspectorList();
    };

    /**
     * 获取人员列表
    */
    ctrl.getInspectorList = function() {
        // 判断当前登陆的账号是否是自己员工
        var isZTZ = $api.getStorage('isZTZ');
        var isXJZZ = $api.getStorage('isXJZZ');
        var url;
        var data;
        var flag;
        if (isZTZ || isXJZZ) { // ZTZ || XJZZ
            url = '/ems/rest/xj/schedule/task/employee';
            flag = true;
        } else { // KHZZ || KHZBZ 客户员工 站长 || 值长
            url = '/ems/rest/employee/getEmployeeByEmployeeId';
            flag = false;
        }
        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.getPrList = function () {
        var url = '/ems/rest/power/room/list';
        var data = {
            employeeId: ctrl.employeeId,
            roleId: ctrl.roleId
        }
        
        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 {
                    ctrl.renderPrList(res.body);
                }
            }
        });
    };

    // 渲染配电室下拉框
    ctrl.renderPrList = function (data) {
        var len = data.length;

        var temp = '';

        ctrl.prListDom.empty();

        for (var i = 0; i < len; i++) {
            var prItem = data[i];
            var domStr = '';
            
            domStr += '<div class="pr" data-prid="{prId}" data-prname="{prName}">'
            domStr +=     '<div class="icon-con">'
            domStr +=         '<img src="../../image/black-pr-icon.png">'
            domStr +=     '</div>'
            domStr +=     '<div>{prName}</div>'
            domStr += '</div>'

            domStr = domStr.replace("{prId}", prItem.prId)
                        .replace("{prName}", prItem.prName)
                        .replace("{prName}", prItem.prName);

            temp += domStr;
        }

        ctrl.prListDom.append(temp);
    };

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

    /**
     * 保存
    */
    ctrl.save = function () {
        // 数据校验
        var flag = ctrl.checkData();

        if (flag == 1) {
            ctrl.toast("请选择配电室");
            return;
        } else if (flag == 2) {
            ctrl.toast("请填写工单描述");
            return;
        };

        api.showProgress();

        var pics = ctrl.orderData.pics;
        var length = pics.length;
        if (length > 0) { // 有图片
            // 上传 图片
            for (var i = 0; i < length; i++) {
                var url = pics[i]['url'];
                ctrl.uploadPic(url);
            }
        } else { // 没图片
            ctrl.submitOrder();
        };
    };

    // 数据校验
    ctrl.checkData = function () {
        ctrl.orderData.desc = $('#problem-text').val().trim();

        if (!ctrl.orderData.prId) { // 验证配电室选择
            return 1;
        } else if (!ctrl.orderData.desc) { // 验证工单描述
            return 2;
        };
    };

    // 上传图片
    ctrl.uploadPic = function (file) {

        var url = "/ems/rest/common/file/pad_upload";
        var data = file;

        $api.uploadFile(url, data, function (res, err) {

            if (err) {
                api.hideProgress();
                ctrl.toast("网络请求失败,请稍后再试");
            } else {
                if (res.code == 200) {
                    // 将返回的图片路径保存
                    if (res.body && res.body.fileUrl) {
                        ctrl.orderData.serverPicUrls.push(res.body.fileUrl)
                        ctrl.orderData.uploadPicNum++;

                        if (ctrl.orderData.uploadPicNum == ctrl.orderData.pics.length) {// 代表全部图片上传完成
                            // 2、调用接口
                            ctrl.submitOrder();
                        }
                    } else {
                        api.hideProgress();
                        ctrl.toast("服务器错误，未返回数据");
                    }
                } else {
                    api.hideProgress();
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }

        })
    };

    // 提交工单
    ctrl.submitOrder = function () {
        api.showProgress();

        var zhaoPian = ctrl.orderData.serverPicUrls.join(',');
        var url = '/test/gong-dan/insert';
        var data = {
            tiJiaoRenId: ctrl.employeeId,
            prId: ctrl.orderData.prId,
            miaoShu: ctrl.orderData.desc
        };

        if (ctrl.handleEmployeeId) {
            data.chuLiRenId = ctrl.handleEmployeeId;
            data.chuLiRenName = ctrl.handleEmployeeName;
            data.chuLiShiJian = CommonModel.getFomattedDate();
            data.zhuangTai = 1;
        }

        if (zhaoPian) {
            data.zhaoPian = zhaoPian;
        };

        $api.post(url, data, function (res, err) {

            if (err) {
                api.hideProgress();
                ctrl.toast("创建工单失败,请稍后再试");
            } else {
                if (res.code == 200) {
                    // 返回工单列表页
                    api.sendEvent({
                        name: 'orderListChanged'
                    });

                    api.hideProgress();
                    ctrl.toast("提交成功");
                    api.closeWin();
                } else {
                    api.hideProgress();
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            };

        });
    };

    ctrl.init();
}
