apiready = function() {
    var ctrl = {
        init: {},
        bind: {},
        employeeId: null,
        roleId: null,
        prList: null,
        inspectionId: null,
        xjDate: null,
        jieDanRenId: null,
        // inspectionMsg: {
        //     xjDate: '2023-11-21',
        //     inspector: '张三',
        //     workTime: '08:00',
        //     prCount: '10',
        //     prList: [{
        //         prName: '敦豪配电室',
        //         prId: 1,
        //         count: 1
        //     }, {
        //         prName: '敦豪配电室1',
        //         prId: 2,
        //         count: 2
        //     }, {
        //         prName: '敦豪配电室2',
        //         prId: 3,
        //         count: 3
        //     }]
        // }
    }
    /**
     * 弹出提示框
     */
    ctrl.toast = function(msg) {
        api.toast({
            msg: msg,
            duration: 3000,
            locaiton: 'top'
        });
    }

    /**
     * 显示右侧边栏
     */
    ctrl.showRightPanel = function() {
        api.openDrawerPane({
            type: 'right',
            pageParam: {
                id: 123
            },
        });
    }

    /**
     * 新建 保存巡检配电室
    */
    ctrl.saveCreateInspectPrList = function(inspectionId) {
        api.showProgress();
        var url = '/test/xun-jian-pr/inserts';
        var data = [];
        var PrDomList = $('#prList .pr');
        var len = PrDomList.length;

        if (len) {
            for (var i = 0; i < len; i++) {
                var prDom = PrDomList[i];
                var prId = $(prDom).data('prid');
                var prName = $(prDom).data('prname');
                var inspectType = $(prDom).data('inspecttype');
                var dataItem = {
                    xunJianDanId: inspectionId,
                    prId: prId,
                    prName: prName,
                    employeeId: ctrl.employeeId,
                    xunJianLeiXing: inspectType
                }

                data.push(dataItem)
            }
        }

        $api.post(url, data, function(res, err) {
            api.hideProgress();
            if (err) {
                ctrl.toast("网络请求失败");
            } else {
                if (!res.code || res.code != "200") {
                    ctrl.toast("服务器响应错误");
                } else {
                    // 返回巡检安排列表页 并触发巡检安排页面定义的 inspectionCreateChanged 事件
                    api.sendEvent({
                        name: 'inspectionCreateChanged'
                    });
                    toast("保存成功");
                    // 关闭当前页，返回到巡检任务列表页
                    api.closeWin();
                }
            }
        });
    }

    /**
     * 编辑 保存巡检配电室
    */
    ctrl.saveEditInspectPrList = function() {
        api.showProgress();
        var url = '/test/xun-jian-pr/inserts';
        var data = [];
        var PrDomList = $('#prList .pr');
        var len = PrDomList.length;

        if (len) {
            for (var i = 0; i < len; i++) {
                var prDom = PrDomList[i];
                // var id = $(prDom).data('id');
                var prId = $(prDom).data('prid');
                var prName = $(prDom).data('prname');
                var inspectType = $(prDom).data('inspecttype');
                var dataItem = {
                    // id: id,
                    xunJianDanId: ctrl.inspectionId,
                    prId: prId,
                    prName: prName,
                    employeeId: ctrl.employeeId,
                    xunJianLeiXing: inspectType
                }

                data.push(dataItem)
            }
        }

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

                    // 返回巡检安排列表页 并触发巡检安排页面定义的 inspectionCreateChanged 事件
                    api.sendEvent({
                        name: 'inspectionCreateChanged'
                    });
                    // 关闭当前页，返回到巡检任务列表页
                    api.closeWin();
                }
            }
        });
    }

    /**
     * 新建 保存巡检单
    */
    ctrl.saveCreateInspect = function() {
        api.showProgress();
        var url = '/test/xun-jian-dan/insert';
        var data = {
            xunJianShiJian: ctrl.xjDate,
            employeeId: ctrl.employeeId,
            roleId: ctrl.roleId
        };

        (ctrl.jieDanRenId != '') && (data.jieDanRenId = ctrl.jieDanRenId)
        
        $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.saveCreateInspectPrList(res.data);
                }
            }
        });
    }

    /**
     * 编辑 保存巡检单
    */
    ctrl.saveEditInspect = function() {
        api.showProgress();
        var url = '/test/xun-jian-dan/insert';
        var data = {
            id: ctrl.inspectionId,
            xunJianShiJian: ctrl.xjDate,
            employeeId: ctrl.employeeId,
            roleId: ctrl.roleId
        };

        (ctrl.jieDanRenId != '') && (data.jieDanRenId = ctrl.jieDanRenId)
        
        $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.saveEditInspectPrList();
                }
            }
        });
    }

    /**
     * 保存
    */
    ctrl.save = function() {
        
        api.showProgress({
            title: '保存中...',
            text: '请稍后',
            modal: false
        });

        // 需要区分“新建”和“修改”
        if (ctrl.inspectionId != null) { // 修改
            ctrl.saveEditInspect()
        } else { // 新建
            ctrl.saveCreateInspect()
        }

    }

    /**
     * 清空配电室列表
     */
    ctrl.clearPrList = function() {
        $("#prList").empty();
    }

    /**
     * 创建一个配电室DOM
    */
    ctrl.createPrDom = function(prName, prId, inspectType, id) {
        var type = '例行巡检';
        switch (inspectType) {
            case 1:
                type = '例行巡检';
                break;
            case 2:
                type = '特殊巡检';
                break;
            case 3:
                type = '会诊巡检';
                break;
            case 4:
                type = '熄灯巡检';
                break;
        };

        var template = ''
        
        template +='<div class="pr" data-id="{id}" data-prid="{prId}" data-prname="{prname}" data-inspecttype="{inspectType}">'
        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> < <span class="inspect-type">{type}</span> > </div>'
        template +=        '</div>'
        template +=    '</div>'
        template +=    '<div class="right">'
        template +=        '<div class="btn-danger show-right-panel">删除</div>'
        template +=    '</div>'
        template +='</div>'

        template = template.replace("{prname}", prName)
                            .replace("{prName}", prName)
                            .replace("{inspectType}", inspectType)
                            .replace("{type}", type)
                            .replace("{prId}", prId)
                            .replace("{id}", id || '');
        
        ctrl.prList.append(template);
    }

    /**
     * 更新巡检信息
    */
    ctrl.renderInspectionMsg = function(inspectionMsg) {
        ctrl.xjDate = inspectionMsg.xjDate;
        $('#xjDate').text(inspectionMsg.xjDate);
        ctrl.jieDanRenId = inspectionMsg.employeeId || '';
        $('#inspector').text(inspectionMsg.employeeName || '无');
        // $('#workTime').text(inspectionMsg.workTime);
        $('#prCount').text(inspectionMsg.totalCount);

        var prList = inspectionMsg.prList;
        var length = prList.length;

        ctrl.clearPrList();

        if (length <= 0) {
            ctrl.emptyTips.show();
        } else {
            ctrl.emptyTips.hide();
        }

        for (var i = 0; i < length; i++) {
            var prItem = prList[i];
            var count = prItem.count;
            var prName = prItem.prName;
            var prId = prItem.prId;
            var inspectType = prItem.type;

            for (var j = 0; j < count; j++) {
                ctrl.createPrDom(prName, prId, inspectType);
            }
        }
    }

    /**
     * 巡检信息发生变化(从右侧滑栏传递的数据)
    */
    ctrl.inspectionMsgChanged = function(ret, err) {
        ctrl.renderInspectionMsg(ret.value)
    }

    /**
     * 获取巡检单详情
    */
    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 {
                    ctrl.renderInspectDetail(res.data);
                    // 获取当前巡检单对应的巡检配电室列表
                    ctrl.getInspectPrList();
                }
            }
        });
    }

    ctrl.renderInspectDetail = function(data) {
        // 更新巡检日期
        ctrl.xjDate = data.xunJianShiJian;
        $('#xjDate').text(data.xunJianShiJian);
        // 更新巡检人员
        ctrl.jieDanRenId = data.jieDanRenId || null;
        $('#inspector').text(data.jieDanRen || '无');
    }

    /**
     * 获取巡检配电室列表
    */
    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 {
                    api.hideProgress();
                    ctrl.renderInspectPrList(res.data);
                }
            }
        });
    }

    // 渲染巡检配电室列表
    ctrl.renderInspectPrList = function(data) {
        // 判断配电室数量
        if (data.total <= 0) {
            ctrl.prCountDom.text('0')
            ctrl.emptyTips.show();

            return;
        } else {
            // 更新配电室数量
            ctrl.prCountDom.text(data.total)
            ctrl.emptyTips.hide();

            // 渲染配电室列表
            ctrl.clearPrList();
            var records = data.records;
            var len = data.records.length;
            for (var i = 0; i < len; i++) {
                var prItem = records[i];
                ctrl.createPrDom(prItem.prName, prItem.prId, prItem.xunJianLeiXing, prItem.id);
            }
        }

    }

    ctrl.init = function() {
        // 适配安卓状态栏
        CommonModel.fitInStatusBar();
        var searcherTop = $('#heightHeader').height();
        $('#searcher').css('top',searcherTop);
        
        ctrl.inspectionId = api.pageParam.id || null;
        ctrl.employeeId = $api.getStorage('employeeId');
        ctrl.roleId = $api.getStorage('roleId');
        ctrl.prList = $("#prList");
        ctrl.emptyTips = $("#empty-tips");
        ctrl.title = $('#title');
        ctrl.xjDateDom = $('#xjDate');
        ctrl.prCountDom = $('#prCount');

        // 判断新增、编辑
        if (ctrl.inspectionId) {// 编辑
            ctrl.title.text('编辑巡检单');
            // 获取巡检单详情
            ctrl.getInspectDetail();

            ctrl.emptyTips.hide();
        } else { // 新增
            ctrl.title.text('新增巡检单');
            ctrl.xjDate = $api.getFormattedDate('yyyy-MM-dd');
            ctrl.xjDateDom.text(ctrl.xjDate);
            ctrl.emptyTips.show();
        }

        ctrl.bind();

        //巡检任务信息发生变化
        api.addEventListener({
            name: 'inspectionMsgChanged'
        }, ctrl.inspectionMsgChanged);
    }
    ctrl.bind = function() {
        //点击返回按钮
        $api.addEvt($api.dom("#back"), "touchend", function() {
            api.closeWin();
        })

        //用户点击了"日期选择、人员选择、上班时间、选择配电室、删除"按钮
        $("#container").on("touchend", ".show-right-panel", ctrl.showRightPanel);

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

    ctrl.init();
}
