apiready = function() {
    var ctrl = {
        init: {},
        bind: {},
        employeeId: null,
        roleId: null,
        prList: null,
        inspectionId: null,
        xjDate: null,
        jieDanRenId: null,
        status: null, // status：0 未接单，1 未开始，2 巡检中，3 已完成
        tabType: 'content', // 当前激活的 tab
        prefix: 'https://cdyfile.saas.dianwutong.com/',
        problemType: 0, // 设备缺陷类型
        hasUnfinishedPr: false, // 当前巡检任务下,是否存在未完成巡检的配电室,默认不存在
    };

    ctrl.init = function() {
        // 适配安卓状态栏
        CommonModel.fitInStatusBar();

        ctrl.inspectionId = api.pageParam.inspectionid;
        // status：1 未开始，2 巡检中，3 已完成
        ctrl.status = api.pageParam.status;
        if (ctrl.status == 1) {
            $('#start-inspect-btn').show();
            $('#finish-inspect-btn').hide();
        } else if (ctrl.status == 2) {
            $('#start-inspect-btn').hide();
            $('#finish-inspect-btn').show();
        } else if (ctrl.status == 3) {
            $('#start-inspect-btn').hide();
            $('#finish-inspect-btn').hide();
        }

        ctrl.employeeId = $api.getStorage('employeeId');
        ctrl.roleId = $api.getStorage('roleId');
        ctrl.prList = $("#prList");
        ctrl.contentEmptyTips = $("#content-empty-tips");
        ctrl.problemEmptyTips = $("#problem-empty-tips");
        ctrl.title = $('#title');
        ctrl.xjDateDome = $('#xjDate');
        ctrl.prCountDom = $('#prCount');

        //巡检任务信息发生变化
        api.addEventListener({
            name: 'inspectionPrChanged'
        }, ctrl.inspectionPrChanged);

        ctrl.bind();

        ctrl.initInspectContentTab()
    };

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

         //点击 “巡检内容” tab按钮
         $api.addEvt($api.dom("#content-tab"), "touchend", function () {
            if (ctrl.tabType == 'content') {
                return
            }

            $api.addCls(this, "active");
            $api.removeCls($api.dom("#problem-tab"), "active");
            $api.css($api.dom("#content-panel"), 'display:block');
            $api.css($api.dom("#problem-panel"), 'display:none');
            $api.css($api.dom('#content-empty-tips'), "display:none");

            ctrl.tabType = 'content'

            // 初始化 巡检内容 tab
            ctrl.initInspectContentTab();

        }, false);

        //点击 “设备缺陷” tab按钮
        $api.addEvt($api.dom("#problem-tab"), "touchend", function () {
            if (ctrl.tabType == 'problem') {
                return
            }

            $api.addCls(this, "active");
            $api.removeCls($api.dom("#content-tab"), "active");
            $api.css($api.dom("#problem-panel"), 'display:block');
            $api.css($api.dom("#content-panel"), 'display:none');
            $api.css($api.dom('#problem-empty-tips'), "display:none");

            ctrl.tabType = 'problem';

            // 初始化 设备缺陷 tab
            ctrl.initInspectProblemTab();

        }, false);

        // 点击“未处理” btn
        $("#btn-unhandle").on("touchend", function() {
            ctrl.problemType = 0;
            $(this).siblings('.bg-touch').removeClass('bg-yellow');
            $(this).addClass('bg-yellow');
            ctrl.initInspectProblemTab();
        });

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

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

        // 点击配电室 跳转到对应配电室巡检详情页
        $('#prList').on("touchend", ".pr", function(e) {
            e.stopPropagation();

            // 只有巡检中的单子才能跳转到配电室详情页
            if (ctrl.status == 0 || ctrl.status == 1) {
                ctrl.toast('开始巡检后才能查看');

                return;
            };

            var id = $(this).data('id');
            var prId = $(this).data('prid');
            var prName = $(this).data('prname');
            var status = $(this).data('status');

            if (status == '2') { // 已完成 巡检的配电室禁止跳转
                ctrl.toast('已完成巡检，无法查看');

                return;
            };
            
            api.openWin({
                name: 'inspectionPrDetail',
                url: './inspectionPrDetail.html',
                pageParam: {
                    id: id,
                    prid: prId,
                    prname: prName
                }
            });
        });

        // 点击 "开始巡检" 按钮
        $('#start-inspect-btn').on("touchend", function(e) {
            e.stopPropagation();

            api.confirm({
                title: '',
                msg: '确定要开始吗',
                buttons: ['确定', '取消']
            }, function(ret, err) {
                var index = ret.buttonIndex;
                if (index == 1) { // 确定
                    ctrl.startInspect();
                }
            });
        });

        // 点击 “巡检完成” 按钮
        $('#finish-inspect-btn').on("touchend", function(e) {
            e.stopPropagation();

            api.confirm({
                title: '',
                msg: '确定所有配电室巡检完成了吗',
                buttons: ['确定', '取消']
            }, function(ret, err) {
                var index = ret.buttonIndex;
                if (index == 1) { // 确定
                    if (ctrl.hasUnfinishedPr) {
                        ctrl.toast('存在未巡检完成的配电室！');
                    } else {
                        ctrl.finishInspect();
                    };
                }
            });
        });
    };

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

    // 初始化 巡检内容 tab
    ctrl.initInspectContentTab = function() {
        ctrl.getInspectDetail();
    };

    // 初始化 设备缺陷 tab
    ctrl.initInspectProblemTab = function() {
        ctrl.getProblemList();
    };

    // 获取设备缺陷 列表
    ctrl.getProblemList = function() {
        api.showProgress();

        var url = '/test/xun-jian-dan/queryProblemById/' + ctrl.inspectionId + '/' + ctrl.problemType;
        
        $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.renderProblemList(res.data);
                }
            }
        });
    };

    // 清空设备缺陷 列表
    ctrl.clearProblemList = function() {
        $("#problem-list-container").empty();
    };

    // 渲染设备缺陷 列表
    ctrl.renderProblemList = function(data) {
        var length = data.length;

        ctrl.clearProblemList();

        if (length > 0) {
            ctrl.problemEmptyTips.hide();

            for (var i = 0; i < length; i++) {
                var dataItem = data[i];
                ctrl.createProblemDom(i + 1, dataItem);
            };
        } else {
            ctrl.problemEmptyTips.show();
        };

        api.hideProgress();
    };

    // 创建 设备缺陷 DOM
    ctrl.createProblemDom = function(index, problemItem) {
        var tpl = '';
        var status = '';
        var colorClass = '';
        var problemDesc = problemItem.problemDesc;
        var pics = [];
        
        if (problemItem.picture) {
            pics = problemItem.picture.split(',');
        };
        var picsLength = pics.length;

        if (problemItem.status == 0) {
            status = '未处理';
            colorClass = 'text-red';
        } else if (problemItem.status == 1) {
            status = '处理中';
            colorClass = 'text-yellow';
        };

        tpl += '<li class="problem-item">';
        tpl +=     '<div class="problem-index">';
        tpl +=         '<div class="problem-item-title">问题<span>{index}</span></div>';
        tpl +=         '<div class="status {colorClass}">{status}</div>';
        tpl +=     '</div>';
        tpl +=     '<div class="problem-desc">';
        tpl +=         '<div class="problem-item-title">问题描述：</div>';
        tpl +=         '<div class="desc">{problemDesc}</div>';
        tpl +=     '</div>';
        tpl +=     '<div class="problem-pic">';
        tpl +=         '<div class="problem-item-title">现场照片：</div>';
        tpl +=         '<div class="pic-content" class="pics problem-item-content">';
        if (picsLength > 0) {
            for (var i = 0; i < picsLength; i++) {
                var url = pics[i];
                var img = '<span class="pic-item"><img class="pic-add-btn problem-pic-item" src="' + ctrl.prefix + url + '" alt=""></span>';
                tpl += img;
            }
        } else {
            tpl += '无'
        }
        tpl +=         '</div>';
        tpl +=     '</div>';
        tpl += '</li>';

        tpl = tpl.replace("{index}", index)
                .replace("{colorClass}", colorClass)
                .replace("{problemDesc}", problemDesc)
                .replace("{status}", status);

        $("#problem-list-container").append(tpl);
    };

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

    // 巡检单中的配电室巡检状态改变 触发的事件处理
    ctrl.inspectionPrChanged = function(ret, err) {
        ctrl.initInspectContentTab();
    };

    /**
     * 获取巡检单详情
    */
    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.hasUnfinishedPr = false;
                    ctrl.renderInspectPrList(res.data);
                }
            }
        });
    };

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

            return;
        } else {
            // 更新配电室数量
            ctrl.prCountDom.text(data.total)
            ctrl.contentEmptyTips.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);
            }
        }

    };

    /**
     * 创建一个配电室DOM
    */
     ctrl.createPrDom = function(prItem) {
        var status = prItem.shiFouWanCheng;
        var statusDesc = prItem.shiFouWanCheng?  '已完成' : '未完成';
        var colorClass = prItem.shiFouWanCheng?  'color-green' : 'color-red';
        var id = prItem.id;
        var prId = prItem.prId;
        var prName = prItem.prName;

        var type = '例行巡检';
        switch (prItem.xunJianLeiXing - 0) {
            case 1:
                type = '例行巡检';
                break;
            case 2:
                type = '特殊巡检';
                break;
            case 3:
                type = '会诊巡检';
                break;
            case 4:
                type = '熄灯巡检';
                break;
        };

        if (!prItem.shiFouWanCheng) {
            ctrl.hasUnfinishedPr = true;
        };

        var template = ''

        template +='<div class="pr" data-id="{id}" data-prid="{prId}" data-prname="{prName}" data-status="{status}">'
        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 +=        '<span class="{colorClass}">{statusDesc}</span>'
        template +=    '</div>'
        template +='</div>'

        template = template.replace("{id}", id)
                            .replace("{prId}", prId)
                            .replace("{prName}", prName)
                            .replace("{status}", status)
                            .replace("{prName}", prName)
                            .replace("{type}", type)
                            .replace("{colorClass}", colorClass)
                            .replace("{statusDesc}", statusDesc);
        
        ctrl.prList.append(template);
    };

    // 开始巡检
    ctrl.startInspect = function () {
        api.showProgress();

        var url = '/test/xun-jian-dan/updateById';
        var data = {
            id: ctrl.inspectionId,
            shiFouWanCheng: 2
        };
        
        $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.status = 2;

                    api.hideProgress();
                    // 隐藏开始巡检 按钮
                    $('#start-inspect-btn').hide();

                    // 显示巡检完成 按钮
                    $('#finish-inspect-btn').show();
                }
            }
        });
    };

    // 全部巡检完成
    ctrl.finishInspect = function () {
        api.showProgress();

        var url = '/test/xun-jian-dan/updateById';
        var data = {
            id: ctrl.inspectionId,
            shiFouWanCheng: 3
        };
        
        $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 {
                    api.hideProgress();
                    // 隐藏开始巡检 按钮
                    $('#start-inspect-btn').hide();

                    // 隐藏巡检完成 按钮
                    $('#finish-inspect-btn').hide();

                    // 跳转到巡检任务页 并更新页面数据
                    api.sendEvent({
                        name: 'inspectionTaskChanged'
                    });

                    api.closeWin();
                }
            }
        });
    };

    ctrl.init();
}
