apiready = function () {
    var ctrl = {
        init: {},
        bind: {},
        backCallback: {},

        // 当前展示的tab 页类型，msg:配电室资料   detail：任务详情
        tabType: 'detail',
        baseUrl: '',

        prid: null,
        taskId: null,
        qxorderid: null,
        prefix: '', // 服务器图片基础路径

        qxAccept: '0', // 当前抢修任务是否已经接单 0:否，1：是
    }

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

        ctrl.bind();

        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        ctrl.qxorderid = api.pageParam.qxorderid;
        ctrl.prid = api.pageParam.prid;
        ctrl.qxAccept = $api.getStorage('qxAccept' + ctrl.qxorderid);

        ctrl.getQxOrderDetail()

    }

    ctrl.bind = function () {

        var height = $(window).height() - $("header").height() - $(".tabs").height();
        $(".content-container").css("height", height);
        //绑定返回按钮
        $api.addEvt($api.dom("#back"), "touchend", function () {
            ctrl.backCallback();
        })

        //点击系统返回按钮
        api.addEventListener({
            name: 'keyback'
        }, function (ret, err) {
            ctrl.backCallback();
        });

        //点击任务详情tab
        $api.addEvt($api.dom("#order-detail-tab"), "touchend", function () {
            if (ctrl.tabType == 'detail') {
                return
            }

            $api.addCls(this, "active");
            $api.removeCls($api.dom("#pr-msg-tab"), "active");
            $api.removeCls($api.dom("#task-log-tab"), "active");
            $api.css($api.dom("#order-detail-panel"), 'display:block');
            $api.css($api.dom("#pr-msg-panel"), 'display:none');
            $api.css($api.dom("#task-log-panel"), 'display:none');

            ctrl.tabType = 'detail'

            // 初始化任务详情 tab
            ctrl.getQxOrderDetail();

        }, false);

        //点击配电室资料tab按钮
        $api.addEvt($api.dom("#pr-msg-tab"), "touchend", function () {
            if (ctrl.tabType == 'msg') {
                return
            }

            $api.addCls(this, "active");
            $api.removeCls($api.dom("#order-detail-tab"), "active");
            $api.removeCls($api.dom("#task-log-tab"), "active");
            $api.css($api.dom("#pr-msg-panel"), 'display:block');
            $api.css($api.dom("#order-detail-panel"), 'display:none');
            $api.css($api.dom("#task-log-panel"), 'display:none');

            ctrl.tabType = 'msg'

            ctrl.initPrMsgTab()
        }, false);

        /*
            ====================任务详情 tab 中相关事件====================
        */

        // 点击预览图片 关闭预览
        $('#pic-review').on("touchend", function () {
            $(this).css('display', 'none')
        })

        /*
            ====================配电室资料  tab 相关事件====================
        */
        // 点击配电室资料列表 ，在线浏览 pdf
        $("#pr-msg-list").on("touchend", ".pr-msg-list-item", function () {

            var url = ctrl.baseUrl + $(this).data("url");

            api.download({
                url: url,  // 填写要下载文档的url
                report: true,
                cache: true,
                allowResume: true
            }, function (ret, err) {
                if (ret.state == 1) {					//下载成功

                    var superFile = api.require('superFile');
                    superFile.open({
                        path: ret.savePath,
                    })

                }
            });

        })


        //点击开始抢修按钮
        $api.addEvt($api.dom("#start-repair-btn"), "touchend", function () {
            // 判断当前抢修单时候已经接单
            if (ctrl.qxAccept == '1') { // 已经被接单
                // 跳转到抢修详情内容页
                api.openWin({
                    name: 'repairProblem',
                    url: './repairProblem.html',
                    pageParam: {
                        prid: ctrl.prid,
                        taskid: ctrl.taskId,
                        qxorderid: ctrl.qxorderid
                    }
                });

                return;
            }
            ctrl.handleStartRepair()
        })

    }
    /**
     * 弹出提示框
     */

    ctrl.toast = function (msg) {
        api.toast({
            msg: msg,
            duration: 3000,
            locaiton: 'top'
        });
    }

    ctrl.backCallback = function () {
        //关闭首页正在加载的提示框
        api.execScript({
            name: 'index',
            frameName: 'featureFrame',
            script: "api.hideProgress();"
        });
        api.setScreenOrientation({
            orientation: 'auto_portrait'
        });
        api.setFullScreen({
            fullScreen: false
        });
        api.closeWin({});
    }

    /*
        ===================任务详情 tab 相关==============
    */
    //获取抢修任务详情
    ctrl.getQxOrderDetail = function () {
        //显示载入动画
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        var url = '/ems/rest/qx/order';
        var data = {
            "qxOrderId": ctrl.qxorderid,
        };

        $api.get(url, data, function (res, err) {
            //隐藏载入动画
            api.hideProgress();
            if (err) {
                ctrl.toast("网络请求失败");
            } else {
                if (!res.code || res.code != 200) {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                } else {
                    ctrl.taskId = res.body.qxTasks[0]['taskId'];
                    ctrl.prefix = res.prefix;
                    // 当前抢修任务已经被接单
                    if (res.body.qxTasks && res.body.qxTasks[0]['acceptTime']) {
                        ctrl.qxAccept = '1';
                        $api.getStorage('qxAccept' + ctrl.qxorderid)? null : $api.setStorage('qxAccept' + ctrl.qxorderid, '1');

                        if (res.body.qxTasks[0]['completeTime']) { // 若当前抢修单已经完成，隐藏“开始抢修”按钮
                            $('#start-repair-btn').css('display', 'none');
                        }
                    }

                    ctrl.renderQxOrderDetail(res.body);
                }

            }
        });

    }

    // 渲染任务详情
    ctrl.renderQxOrderDetail = function (data) {
        // 抢修方案
        $('#qx-programme .content').text(data.qxProgramme || '没有抢修方案');

        // 问题描述
        $('#qx-desc .content').text(data.orderDesc);

        // 现场照片
        var pics = data.xjPicture ? data.xjPicture.split(',') : [];
        var pciCount = pics.length;
        $('#pic-count').text(pciCount);

        var picDom = '';
        pics.forEach(function (item, index) {
            var tpl = '<span class="pic-item"><i></i><img src="{{src}}" alt=""></span>';
            tpl.replace('{{src}}', ctrl.prefix + item);
            picDom += tpl;
        })

        // 点击图片预览
        $("#pic-content .pic-item").on("touchend", "img", function (e) {
            e.stopPropagation();
            var src = $(this).attr('src')
            
            $('#pic-review img').attr('src', src)
            $('#pic-review').css('display', 'block')
        })

        $('#pic-content').prepend(picDom);
    }

    /*
        ====================配电室资料 tab 相关===================
    */
    // 初始化 配电室资料 tab
    ctrl.initPrMsgTab = function () {
        ctrl.getPrMsg()
        ctrl.getPrMsgList()
    }

    // 获取配电室信息
    ctrl.getPrMsg = function () {
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        var url = "/ems/rest/power/room/detail";
        var data = {
            prId: ctrl.prid,
        }
        $api.get(url, data, function (res, err) {
            api.hideProgress();

            if (err) {
                ctrl.toast("网络请求失败");
            } else {
                if (res.code == 200) {
                    ctrl.renderPrMsg(res.body);
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }
        })
    }

    // 渲染配电室信息panel
    ctrl.renderPrMsg = function (data) {

        $('#pr-msg').empty();

        var tpl = '';
        tpl += '<p>配电室联系人：{{people}}</p>';
        tpl += '<p>联系人电话：{{tel}}</p>';
        tpl += '<p>配电室位置：{{province}} {{city}} {{address}}</p>';

        var dom = tpl.replace('{{people}}', data.lxr1)
            .replace('{{tel}}', data.lxr1Mobile)
            .replace('{{province}}', data.province)
            .replace('{{city}}', data.city)
            .replace('{{address}}', data.address)

        $api.html($api.dom('#pr-msg'), dom);
    }

    // 获取配电室资料列表
    ctrl.getPrMsgList = function () {
        var url = "/ems/rest/pr/file/list";
        var data = {
            prId: ctrl.prid,
        }
        $api.get(url, data, function (res, err) {

            if (err) {
                ctrl.toast("网络请求失败");
            } else {
                if (res.code == 200 && res.body) {
                    var length = res.body.length;

                    ctrl.baseUrl = res.prefix;

                    $('#pr-msg-list').empty();

                    for (var i = 0; i < length; i++) {
                        var listItem = res.body[i]
                        $api.append($api.dom('#pr-msg-list'), ctrl.getPrMsgListDOM(listItem));
                    }
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }
        })
    }

    // 渲染配电室信息列表
    ctrl.getPrMsgListDOM = function (listItem) {

        var tpl = '';

        tpl += '<div class="item bg-touch pr-msg-list-item" data-url="{{url}}">'
        tpl += '<div class="nav">'
        tpl += '<span class="pr-name">{{name}}</span>'
        tpl += '<span class="date-time color-title">详情</span>'
        tpl += '</div>'
        tpl += '</div>'

        var dom = tpl.replace('{{url}}', listItem.fileUrl)
            .replace('{{name}}', listItem.fileName)

        return dom;
    }

    // 开始抢修
    ctrl.handleStartRepair = function () {

        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        var url = "/ems/rest/qx/task";
        var data = {
            taskId: ctrl.taskId,
            acceptTime: new Date().getTime(),
            isAccept: true
        }
        $api.put(url, data, function (res, err) {
            api.hideProgress();

            if (err) {
                ctrl.toast("网络请求失败,请稍后再试");
            } else {
                if (res.code == 200) {
                    // 将抢修接单信息保存到 localStorage 中
                    ctrl.qxAccept = '1'
                    $api.setStorage('qxAccept' + ctrl.qxorderid, '1');

                    // 跳转到抢修详情内容页
                    api.openWin({
                        name: 'repairProblem',
                        url: './repairProblem.html',
                        pageParam: {
                            prid: ctrl.prid,
                            taskid: ctrl.taskId,
                            qxorderid: ctrl.qxorderid
                        }
                    });
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }
        })
    }

    ctrl.init();

}
