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, // 设备缺陷类型
    };

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

        ctrl.inspectionId = api.pageParam.inspectionid;
        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');

        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');
        });
    };

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

    // 初始化 设备缺陷 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="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();
    };

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

    /**
     * 获取巡检单详情
    */
    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.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.prName, prItem.prId, prItem.xunJianLeiXing, prItem.id);
            }
        }

    };

    /**
     * 创建一个配电室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}">'
        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>'

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

    ctrl.init();
}
