apiready = function() {
    var ctrl = {
        init: {},
        bind: {},
        getLog: {}, //获取抢修日志详情
        renderLog: {}, //渲染抢修日志详情
        toast: {}, //弹出提示框
        handleData: {}, //处理数据
        renderFilter: {}, //拦截接口返回数据，对体验模式下的数据进行过滤
        filter: {}, //数组筛选
    }

    ctrl.init = function() {
            // 适配安卓状态栏
            CommonModel.fitInStatusBar();
            ctrl.cus = $api.getStorage('cus');
            ctrl.bind();
            ctrl.getPr();
            ctrl.getLog();
        }
        // 弹出提示框
    ctrl.toast = function(msg) {
        api.toast({
            msg: msg,
            duration: 3000,
            locaiton: 'top'
        });
    }
    ctrl.bind = function() {
            //点击返回按钮
            $api.addEvt($api.dom("#back"), "touchend", function() {
                api.closeWin();
            })

            $('.bt-detail').on('touchend', function() {
                $(this).parent().parent().find('.item').toggle();
                $(this).find('img').toggleClass("close")
            })
        }
        //数组筛选  obj {type:2}
    ctrl.filter = function(ary, obj) {
            var result = [];
            for (var i = 0; i < ary.length; i++) {
                var currentObj = ary[i];
                for (var attr in obj) {
                    if (currentObj.hasOwnProperty(attr) && currentObj[attr] == obj[attr]) {
                        result.push(currentObj);
                    }
                }

            }
            return result;

        }
        // 获取抢修日志详情
    ctrl.getLog = function() {
        var url = '/ems/rest/qx/order';
        var id = api.pageParam.id;
        var messageId = api.pageParam.messageId;
        var data = {
            qxOrderId: id
        };
        $api.get(url, data, function(res, err) {
            if (err) {
                ctrl.toast("网络请求失败");
            } else {
                if (res.code == 200) {
                    ctrl.renderLog(res);
                } else if (res.code == 404) {
                    var msg = "";
                    if (messageId) {
                        msg = "日志不存在";
                        ctrl.toast(msg);
                        api.sendEvent({
                            name: 'removeMessage',
                            extra: {
                                messageId: messageId
                            }
                        });

                        window.setTimeout(function() {
                            api.closeWin();
                        }, 2000);
                    } else {
                        ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                    }


                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }

            }
        });
    }

    // 获取配电室详情
    ctrl.getPr = function() {
            var powerRoom = $api.getStorage('powerRoom');
            if (powerRoom) {
                ctrl.prName = powerRoom.prName;
            } else {
                return;
            }
        }
    ctrl.handleData = function() {
            var dateUtil = new DateUtils();
            if (!ctrl.log) {
                return;
            }
            if (ctrl.log.qxTasks) {
                // 查勘任务
                ctrl.surveyTasks = ctrl.filter(ctrl.log.qxTasks, {
                    "taskType": 1
                });
                // 抢修任务
                var repairTask = ctrl.filter(ctrl.log.qxTasks, {
                    "taskType": 2
                });
                ctrl.repairTask = (repairTask && repairTask.length > 0) ? repairTask[0] : null;
            }

            //查询报警时间
            if (ctrl.log.alarmTime) {
                dateUtil.setDate(ctrl.log.alarmTime);
                ctrl.alarmTime = dateUtil.getFormattedDate('yyyy-MM-dd hh:mm:ss');
            }
            //查询开始查勘时间
            if (ctrl.surveyTasks && ctrl.surveyTasks.length > 0) {
                var tasks = ctrl.surveyTasks.sort(function(a, b) {
                    return a.createTime - b.createTime;
                });
                dateUtil.setDate(tasks[0].createTime);
                ctrl.startSurveyTime = dateUtil.getFormattedDate('yyyy-MM-dd hh:mm:ss');
            } else {
                ctrl.startSurveyTime = "没有安排查勘";
            }

            //获取抢修时间和抢修结束时间
            if (ctrl.repairTask) {
                if (ctrl.repairTask.deleteFlag) {
                    ctrl.startRepairTime = "没有安排抢修";
                    ctrl.completeRepairTime = "没有安排抢修";
                } else {
                    dateUtil.setDate(ctrl.repairTask.createTime);
                    ctrl.startRepairTime = dateUtil.getFormattedDate('yyyy-MM-dd hh:mm:ss');
                    if (ctrl.repairTask.isComplete) {
                        dateUtil.setDate(ctrl.repairTask.completeTime);
                        ctrl.completeRepairTime = dateUtil.getFormattedDate('yyyy-MM-dd hh:mm:ss');
                    } else {
                        ctrl.completeRepairTime = '';
                    }

                }

            } else {
                ctrl.startRepairTime = "没有安排抢修";
                ctrl.completeRepairTime = "没有安排抢修";
            }

        }
        //查看图片
        //@param picContainner 图片放置的容器的id
        //@param tasks 后台获取到的任务列表
    ctrl.showPic = function(picContainner, tasks) {
        if (!tasks.picture) {
            return;
        }
        var pics = tasks.picture.length > 0 ? tasks.picture.split(",") : [];
        if (pics.length > 0) {
            $api.html($api.dom('#' + picContainner), '');
            var photoBrowser = api.require('photoBrowser');
            var imageList = [];
            var container = document.getElementById(picContainner);
            //点击图片  使用图片查看器查看
            container.addEventListener("touchend", function() {
                //初始化图片查看器
                photoBrowser.open({
                    images: imageList,
                    bgColor: '#000'
                }, function(ret, err) {
                    if (ret && ret.eventType == "click") {
                        photoBrowser.close();
                    }
                });
            })
            for (var i = 0; i < pics.length; i++) {
                (function() {
                    var container = document.getElementById(picContainner);
                    var image = new Image();
                    image.src = "../../../image/pre-pic.png";
                    container.appendChild(image);
                    api.imageCache({
                        url: ctrl.prefix+pics[i],
                        policy: "cache_else_network",
                        thumbnail: false
                    }, function(ret, err) {
                        if (ret.status) {
                            var container = document.getElementById(picContainner);
                            //  var image = new Image();
                            image.src = ret.url;
                            image.onload = function() {
                                container.appendChild(image);
                                photoBrowser.appendImage({
                                    images: [ret.url]
                                });
                                imageList.push(ret.url);
                            }
                        } else {
                            //  var image = new Image();
                            var container = document.getElementById(picContainner);
                            image.src = "../../../image/img-error.png";
                            image.onload = function() {
                                container.appendChild(image);
                                photoBrowser.appendImage({
                                    images: [image.src]
                                });

                                imageList.push(image.src);
                            }
                        }

                    })

                })()

            }

        } else {
            var dom = "没有图片";
            $('#' + picContainner).html(dom);
        }
    }

    ctrl.renderLog = function(res) {
        ctrl.log = res.body;
        ctrl.prefix = res.prefix;
        ctrl.handleData();
        var log = ctrl.log;
        if (!log) {
            return;
        }
        var isComplete = log.deleteFlag;
        $api.text($api.dom('#pr-name'), ctrl.prName);
        $api.text($api.dom('#malfunction-item'), log.orderDesc);
        if (ctrl.completeRepairTime == "没有安排抢修") {
            if (isComplete) {
                $api.text($api.dom('#complete-time'), ctrl.completeRepairTime);
            }
        } else {
            $api.text($api.dom('#complete-time'), ctrl.completeRepairTime.slice(10));
            $api.text($api.dom('#complete-date'), ctrl.completeRepairTime.slice(0, 10));
        }
        if (ctrl.startRepairTime == "没有安排抢修") {
            if (isComplete) {
                $api.text($api.dom('#repair-time'), ctrl.startRepairTime);
            }
        } else {
            $api.text($api.dom('#repair-time'), ctrl.startRepairTime.slice(10));
            $api.text($api.dom('#repair-date'), ctrl.startRepairTime.slice(0, 10));
        }
        if (ctrl.startSurveyTime == "没有安排查勘") {
            if (isComplete) {
                $api.text($api.dom('#survey-time'), ctrl.startSurveyTime);
            }
        } else {
            $api.text($api.dom('#survey-time'), ctrl.startSurveyTime.slice(10));
            $api.text($api.dom('#survey-date'), ctrl.startSurveyTime.slice(0, 10));
        }

        $api.text($api.dom('#alram-time'), ctrl.alarmTime.slice(10));
        $api.text($api.dom('#alram-date'), ctrl.alarmTime.slice(0, 10));
        if (ctrl.completeRepairTime != "没有安排抢修" && ctrl.completeRepairTime) {
            $api.addCls($api.dom('#complete-circle'), 'circle-green');
            $api.addCls($api.dom('#repair-circle'), 'circle');
            $api.addCls($api.dom('#survey-circle'), 'circle');
            $api.addCls($api.dom('#alram-circle'), 'circle');
        } else if (ctrl.startRepairTime != "没有安排抢修") {
            $api.addCls($api.dom('#complete-circle'), 'circle');
            $api.addCls($api.dom('#repair-circle'), 'circle-green');
            $api.addCls($api.dom('#survey-circle'), 'circle');
            $api.addCls($api.dom('#alram-circle'), 'circle');
        } else if (ctrl.startSurveyTime != "没有安排查勘") {
            $api.addCls($api.dom('#complete-circle'), 'circle');
            $api.addCls($api.dom('#repair-circle'), 'circle');
            $api.addCls($api.dom('#survey-circle'), 'circle-green');
            $api.addCls($api.dom('#alram-circle'), 'circle');
        } else {
            $api.addCls($api.dom('#complete-circle'), 'circle');
            $api.addCls($api.dom('#repair-circle'), 'circle');
            $api.addCls($api.dom('#survey-circle'), 'circle');
            $api.addCls($api.dom('#alram-circle'), 'circle-green');
        }

        //抢修方案
        if (ctrl.cus) {
            log.qxProgramme = log.qxProgramme?log.qxProgramme.replace($api.guestKeysPattern, $api.guestName): '';
        }
        $("#repair-programme").text(log.qxProgramme ? log.qxProgramme : "没有制定抢修方案");

        //查勘结果
        var surveyTasks = ctrl.surveyTasks;
        if (surveyTasks && surveyTasks.length) {
            var str = '<div>';
            for (var i = 0; i < surveyTasks.length; i++) {
                str += '<div>查勘记录' + (i + 1) + '</div>';
                if (surveyTasks[i].taskDesc) {
                    if (ctrl.cus) {
                        surveyTasks[i].taskDesc = surveyTasks[i].taskDesc.replace($api.guestKeysPattern, $api.guestName);
                    }
                    str += '<div class="survey-desc ">查勘描述:' + surveyTasks[i].taskDesc + '</div>';
                } else if (!surveyTasks[i].picture) {
                    str += '<div class="survey-desc ">该条查勘记录没有相关信息</div>';
                } else {
                    str += '<div class="survey-desc">没有查勘描述</div>';
                }
                str += '<div style="height:1rem;"></div>';
                if (surveyTasks[i].picture && surveyTasks[i].picture.length) {
                    var id = surveyTasks[i].taskId;
                    str += '<div class="survey-pic survey-pic-detail" id="' + id + '"></div>';
                    str += '</div>';
                    $('#survey-list-con').html(str);
                    //查勘图片处理
                    var tasks = surveyTasks[i];
                    var pics = tasks.picture.length > 0 ? tasks.picture.split(",") : [];

                    if (pics.length > 0) {
                        var photoBrowser = api.require('photoBrowser');
                        ctrl.imageList = [];

                        var container = document.getElementById(id);

                        $('#survey-list-con').on('touchend', '.survey-pic', function() {
                            //初始化图片查看器
                            photoBrowser.open({
                                images: ctrl.imageList,
                                bgColor: '#000'
                            }, function(ret, err) {
                                if (ret && ret.eventType == "click") {
                                    photoBrowser.close();
                                }
                            });
                        })

                        function addPic(index) {
                            for (var j = 0; j < pics.length; j++) {
                                (function() {
                                    var container = document.getElementById(index);
                                    var image = new Image();
                                    image.src = "../../../image/pre-pic.png";
                                    container.appendChild(image);
                                    api.imageCache({
                                        url: ctrl.prefix+pics[j],
                                        policy: "cache_else_network",
                                        thumbnail: false
                                    }, function(ret, err) {
                                        if (ret.status) {
                                            var container = document.getElementById(index);
                                            image.src = ret.url;
                                            image.onload = function() {
                                                container.appendChild(image);
                                                photoBrowser.appendImage({
                                                    images: [ret.url]
                                                });
                                                ctrl.imageList.push(ret.url);
                                            }
                                        } else {
                                            var container = document.getElementById(index);
                                            image.src = "../../../image/img-error.png";
                                            image.onload = function() {
                                                container.appendChild(image);
                                                photoBrowser.appendImage({
                                                    images: [image.src]
                                                });

                                                ctrl.imageList.push(image.src);
                                            }
                                        }

                                    })
                                })()


                            }
                        }
                        addPic(id);
                    }
                } else if (surveyTasks[i].taskDesc) {
                    //没有查勘图片
                    str += '<div>没有查勘图片</div>'
                    str += '</div>';
                    $('#survey-list-con').html(str);
                } else {
                    str += '</div>';
                    $('#survey-list-con').html(str);
                }



            }
        } else {
            //没有查勘结果
            $('#survey-list-con').html('没有查勘结果');
        };
        //抢修结果
        var repairTask = ctrl.repairTask;

        if (repairTask) {
            if (ctrl.cus) {
                repairTask.result = log.qxProgramme.replace($api.guestKeysPattern, $api.guestName);
            }
            $api.text($api.dom("#taskDesc"), repairTask.result);
            if (repairTask.picture && repairTask.picture.length) {

                ctrl.showPic('repair-pic', repairTask);
            }

        } else {
            var dom = "无抢修记录";
            $('#repair-result').html(dom);

        }
    }

    ctrl.init();
}
