apiready = function () {
    // 解决iphonex底部标签栏被虚拟home键遮挡
    $api.fixTabBar($api.byId('footer'));
    var ctrl = {
        init: {},
        bind: {},
        InspectorGroup: null,
        workTimeGroup: null,
        xjDate: null,
        xjDateStr: null,
        dateStr: null,
        employeeId: null,
        roleId: null,
        date: null,
        resultData: {
            xjDate: '',
            employeeId: '',
            employeeName: '',
            // workTime: '08:00',
            prList: [{
                prId: '',
                prName: '',
                count: 0,
                // type: 100, // 巡检类型：100日检； 110日检+周检； 101日检+月检； 111日检+周检+月检
            }],
            totalCount: 0, // 配电室总数量
        },
    }

    ctrl.init = function () {
        ctrl.employeeId = $api.getStorage('employeeId');
        ctrl.roleId = $api.getStorage('roleId');
        
        ctrl.xjDate = $("#xjDate");
        ctrl.xjDateStr = $("#xjDateStr");
        ctrl.inspectorGroup = $("#inspector-group");
        // ctrl.workTimeGroup = $("#work-time-group");
        ctrl.prList = $('#pr-list');

        ctrl.inspectionId = api.pageParam.id || null;
        
        ctrl.getInspectorList();
        ctrl.getPrList();

        // ctrl.bindSwitchButtonEvent(ctrl.workTimeGroup.children());
        
        ctrl.bind();
    }

    ctrl.bind = function () {
        //监听日期选择器的改变事件
        $("#xjDate").on("change", function() {
            ctrl.dateStr = ctrl.xjDate.val();
            if (ctrl.dateStr && ctrl.dateStr != "") {
                ctrl.xjDateStr.html(ctrl.dateStr);
            } else {
                ctrl.xjDateStr.html("巡检日期");
            }

            ctrl.resultData.xjDate = ctrl.dateStr;
        });
        
        //为确定和取消绑定事件
        $("#btn-cancel").on("touchend", ctrl.btCancel_clicked);
        $("#btn-ok").on("touchend", ctrl.btOk_clicked);
    }

    /**
     * 获取巡检单详情
    */
    ctrl.getInspectDetail = function() {
        api.showProgress();

        var url = '/test/xun-jian-dan/queryById/' + ctrl.inspectionId;
        
        $api.get(url, function(res, err) {
            if (err) {
                ctrl.toast("网络请求失败");
                api.hideProgress();
            } else {
                if (!res.code || res.code != "200") {
                    ctrl.toast("服务器响应错误");
                    api.hideProgress();
                } else {
                    var data = res.data;
                    // 更新巡检日期
                    ctrl.xjDate.val(data.xunJianShiJian);
                    ctrl.xjDateStr.html(data.xunJianShiJian);
                    ctrl.resultData.xjDate = data.xunJianShiJian;
                    // 更新巡检人员
                    if (data.jieDanRenId != -1) {
                        ctrl.employeeId = data.jieDanRenId;
                        ctrl.resultData.employeeId = data.jieDanRenId;
                        ctrl.resultData.employeeName = data.jieDanRen;
                        ctrl.inspectorGroup.find('input').removeClass('btn-highlight');
                        ctrl.inspectorGroup.find("input[data-inspectorid='" + data.jieDanRenId + "']").addClass('btn-highlight');
                    }
                    
                    // 获取当前巡检单对应的巡检配电室列表
                    ctrl.getInspectPrList();
                }
            }
        });
    }

    /**
     * 获取巡检单中巡检配电室列表
    */
    ctrl.getInspectPrList = function() {
        api.showProgress();

        var url = '/test/xun-jian-pr/queryByList/1/9999/' + ctrl.inspectionId;
        
        $api.get(url, function(res, err) {
            if (err) {
                ctrl.toast("网络请求失败");
                api.hideProgress();
            } else {
                if (!res.code || res.code != "200") {
                    ctrl.toast("服务器响应错误");
                    api.hideProgress();
                } else {
                    // 更新配电室数量 和 巡检类型
                    ctrl.updatePrMsg(res.data.records);
                }
            }
        });
    };

    // 更新显示配电室数量 和 巡检类型
    ctrl.updatePrMsg = function(prList) {
        var length = prList.length;
        var map = {};
        if (length > 0) {
            for (var i = 0; i < length; i++) {
                var prItem = prList[i];
                var prId = prItem['prId'];
                var count;
                if (map.hasOwnProperty(prId)) {
                    count = ++map[prId];
                    map[prId] = count;
                } else {
                    count = 1;
                    map[prId] = 1;
                }
                $("#pr-list .pr-item[data-prid='" + prId + "']").data('count', count).find('.count').text(count);

                // 更新 每个配电室 巡检类型选中状态
                var xunJianLeiXing = prItem.xunJianLeiXing - 0;
                var type = 'routine';
                switch (xunJianLeiXing) {
                    case 1:
                        type = 'routine';
                        break;
                    case 2:
                        type = 'special';
                        break;
                    case 3:
                        type = 'huizhen';
                        break;
                    case 4:
                        type = 'xideng';
                        break;
                };
                $("#pr-list .pr-item[data-prid='" + prId + "'] input[data-type='" + type + "']").attr('checked', 'checked');
            }
        }
        api.hideProgress();
    }

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

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

        ctrl.resultData.employeeId = employeeId;
        ctrl.resultData.employeeName = employeeName;
    }

    // 工作时间选择
    ctrl.worktimeButton_clicked = function(dom) {
        var workTime = dom.val();

        ctrl.resultData.workTime = workTime;
    }

    /**
     * 巡检员 按钮点击事件处理函数
     */
    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");

        var groupName = sender.attr('group');
        switch (groupName) {
            case "inspector":
                ctrl.inspectorButton_clicked(sender);
                break;
            case "worktime":
                ctrl.worktimeButton_clicked(sender);
                break;
        }
    }

    /**
     * 巡检员 选择
     * @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.formatResultData = function() {
        ctrl.resultData.prList = [];

        var prDomList = $('#pr-list .pr-item');
        var length = prDomList.length;
        var totalCount = 0;
        for (var i = 0; i < length; i++) {
            var prDom = $(prDomList[i]);
            var count = $(prDom.find('.count')[0]).text() - 0;
            if (count == 0) {
                continue;
            }
            var prId = prDom.data('prid');
            var prName = $(prDom.find('.pr-name')[0]).text();
            var routine = prDom.find('input[data-type="routine"]')[0].checked;
            var special = prDom.find('input[data-type="special"]')[0].checked;
            var huizhen = prDom.find('input[data-type="huizhen"]')[0].checked;
            var xideng = prDom.find('input[data-type="xideng"]')[0].checked;
            var type = 1; // 巡检类型：1例行，2特殊，3会诊，4熄灯，默认1

            totalCount += count;

            if (routine) {
                type = 1;
            };

            if (special) {
                type = 2;
            };

            if (huizhen) {
                type = 3;
            };

            if (xideng) {
                type = 4;
            };

            var prData = {
                prId: prId,
                prName: prName,
                count: count,
                type: type
            }

            ctrl.resultData.prList.push(prData);
        }

        ctrl.resultData.totalCount = totalCount
    }

    // 数据验证
    ctrl.checkResultData = function() {
        ctrl.formatResultData();

        var flag = true;

        if (ctrl.resultData.xjDate == '') {
            flag = false;

            ctrl.toast('请选择巡检日期');
        };

        return flag;
    }

    /**
     * 向主窗体发送巡检信息选择结果
     */
    ctrl.sendInspectionResult = function() {
        var flag = ctrl.checkResultData();

        if (!flag) {
            return;
        }

        api.sendEvent({
            name: 'inspectionMsgChanged',
            extra: ctrl.resultData
        });

        api.closeDrawerPane();
    }

    /**
     * 确定
     */
    ctrl.btOk_clicked = function() {
        ctrl.sendInspectionResult();
    }

    /**
     * 取消
     */
    ctrl.btCancel_clicked = function() {
        api.closeDrawerPane();
    }

    /**
     * 渲染巡检员列表
    */
    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());
    }

    /**
     * 获取巡检人员列表
    */
    ctrl.getInspectorList = function() {
        // 判断当前登陆的账号是否是ZTZ
        var flag = $api.getStorage('isZTZ') || false;
        var url;
        var data;
        if (flag) { // ZTZ
            url = '/ems/rest/xj/schedule/task/employee';
        } else { // KHZZ || KHZBZ 客户员工 站长 、值长
            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.bindPrItemEvent = function() {
        // 减
        $('#pr-list .sub').on('touchend', function () {
            var prItemDom = $(this).parent('.pr-item');
            var countDom = $(this).siblings('.count')
            var count = countDom.text() - 1;
            if (count < 0) {
                count = 0
            }
            countDom.text(count);
        })

        // 加
        $('#pr-list .sum').on('touchend', function () {
            var prItemDom = $(this).parent('.pr-item');
            var countDom = $(this).siblings('.count')
            var count = (countDom.text() - 0) + 1;

            countDom.text(count);
        })
    }

    // 渲染配电室列表
    ctrl.renderPrList = function(prListData) {
        var len = prListData.length;

        var temp = '';

        ctrl.prList.empty();

        for (var i = 0; i < len; i++) {
            var prItem = prListData[i];
            var domStr = '';
            
            domStr += '<div class="pr-item" data-prid="{prId}" data-count="{count}">';
            domStr += '<div class="pr-name">{prName}</div>';
            domStr += '<div class="count-controler">';
            domStr += '<span class="sub">-</span>';
            domStr += '<span class="count">0</span>';
            domStr += '<span class="sum">+</span>';
            domStr += '</div>';
            domStr += '<div class="inspect-type-radio">'
            domStr +=    '<label><input name="inspect-type-{prId}" data-type="routine" type="radio" checked> 例行</label>'
            domStr +=    '<label><input name="inspect-type-{prId}" data-type="special" type="radio"> 特殊</label>'
            domStr +=    '<label><input name="inspect-type-{prId}" data-type="huizhen" type="radio"> 会诊</label>'
            domStr +=    '<label><input name="inspect-type-{prId}" data-type="xideng" type="radio"> 熄灯</label>'
            domStr += '</div>'
            domStr += '</div>';

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

            temp += domStr;
        }

        ctrl.prList.append(temp);

        //为配电室列表绑定事件
        ctrl.bindPrItemEvent();
    }

    // 获取配电室列表
    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);
                    // 新增和修改都需要获取配电室列表，修改时需要将巡检安排中的配电室数量同步到计数器中
                    // 根据inspectionId判断，当前是编辑还是新建
                    if (ctrl.inspectionId) {// 编辑
                        // 1、获取巡检单详情，更新巡检日期、巡检人员
                        // 2、获取巡检单对应的巡检配电室列表，更新配电室列表
                        ctrl.getInspectDetail();
                    }
                }
            }
        });
    }

    ctrl.init();
}
