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

        prId: null,
        taskId: null,
        itemId: null,

        baseUrl: '',

        pics: [], // 现场照片本地url和base64数据

        serverPicUrls: [], // 上传图片 服务器返回的路径

        uploadPicNum: 0, // 上传图片 请求完成次数

        quesGrade: '0', // 问题类型：0一般，1严重，2危急

        flag: 0, // 当前设备缺陷是否已经成功提交，0：未提交，1：已提交
        
        tabType: '', // 设备缺陷页是从日常、复查、新增三个tab 中的哪个跳转而来

    }

    ctrl.init = function () {
        // 适配安卓状态栏
        CommonModel.fitInStatusBar();
        
        ctrl.prId = api.pageParam.prid;
        ctrl.prName = api.pageParam.prname;
        ctrl.taskId = api.pageParam.taskid;
        ctrl.itemId = api.pageParam.itemid;
        ctrl.source = api.pageParam.source;
        
        ctrl.tabType = api.pageParam.tabtype;
        
        ctrl.bind();
    }

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

        // 添加图片按钮
        $api.addEvt($api.dom("#pic-add-btn"), "touchend", function () {
            var params = {
                sourceType: 'camera',
                destinationType: 'base64'
            }
            api.getPicture(params, function(ret, err){
                if (ret && ret.data) {
                    // 创建图片预览dom
                    var picItemDom = '<span class="pic-item"><i></i><img src="{{url}}" alt=""></span>'
                    var dom = picItemDom.replace('{{url}}', ret.data)
                    $('#pic-content').prepend(dom)

                    // 保存 图片 base64 和 url
                    ctrl.pics.push({
                        base64Data: ret.base64Data,
                        url: ret.data
                    })

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

                } else {
                    ctrl.toast(JSON.stringify(err));
                }
            })
        })

        // 图片 删除按钮
        $("#pic-content").on("touchend", "i", function (e) {
            e.stopPropagation();

            var url = $($(this).siblings('img')[0]).attr('src')

            $(this).parent('.pic-item').remove()

            // 从 ctrl.pics 中删除对应url
            ctrl.pics = ctrl.pics.filter(function (item) {
                return item.url != url
            })
        })
        
        // 点击预览图片 关闭预览
        $('#pic-review').on("touchend", function () {
            $(this).css('display', 'none')
        })

        // 点击语音按钮 开始录音
        // $api.addEvt($api.dom("#audio-add-btn"), "touchstart", function () {

        //     var recordForMP3 = api.require('recordForMP3');

        //     recordForMP3.startRecord(function (ret, err) {
        //         console.log(3333)
        //         if (ret) {
        //             console.log(ret.status)
        //         } else {
        //             console.log('err')
        //         }
                
        //     })

        // })

        // 松开录音按钮 停止录音
        // $api.addEvt($api.dom("#audio-add-btn"), "touchend", function () {
        //     alert(222)
        // })

        // 保存 按钮
        $('#problem-submit-btn').on("touchend", function () {
            api.showProgress({
                title: '保存中...',
                text: '请稍后',
                modal: false
            });
            // 1、获取localStorage中已保存的设备缺陷信息
            // 2、将当前设备缺陷信息保存到localStorage中
            // 3、跳转到巡检项页面
            var problems;
            var storage = $api.getStorage('problems');

            if (!storage) {
                problems = {
                    taskId: ctrl.taskId,
                    source: ctrl.source,
                    record: '',
                    prId: ctrl.prId,
                    arr: [], // 
                    newArr: []
                }
            } else {
                problems = JSON.parse(storage)
            }

            var pictureArr = [];
            ctrl.pics.forEach(function (item, index) {
                pictureArr.push(item.url)
            })
            var picture = pictureArr.join(',');
            var problemDesc = $('#problem-desc').val().trim()
            var item;

            if (ctrl.tabType == 'new') {
                item = {
                    itemId: '',
                    index: ctrl.itemId,
                    problemDesc: problemDesc,
                    picture: picture,
                    quesGrade: ctrl.quesGrade
                };

                problems.newArr.push(item);

            } else {
                item = {
                    itemId: ctrl.itemId,
                    problemDesc: problemDesc,
                    picture: picture,
                    quesGrade: ctrl.quesGrade
                };

                problems.arr.push(item);
            }

            $api.rmStorage('problems');
            $api.setStorage('problems', JSON.stringify(problems));

            /**
             * 更新 localStorage 中保存的巡检项状态信息
             * 
             * */
            var inspectMsg;
            switch (ctrl.tabType) {
                case 'usual':
                    inspectMsg = $api.getStorage('usualIns');
                    break;
                case 'review':
                    inspectMsg = $api.getStorage('reviewIns');
                    break;
                case 'new':
                    inspectMsg = $api.getStorage('newIns');
                    break;
            }

            var inspectMsgObj = JSON.parse(inspectMsg);
            
            switch (ctrl.tabType) {
                case 'usual':
                    inspectMsgObj[ctrl.itemId] = 2;
                    $api.rmStorage('usualIns');
                    $api.setStorage('usualIns', JSON.stringify(inspectMsgObj));
                    break;
                case 'review':
                    inspectMsgObj[ctrl.itemId] = 2;
                    $api.rmStorage('reviewIns');
                    $api.setStorage('reviewIns', JSON.stringify(inspectMsgObj));
                    break;
                case 'new':
                    inspectMsgObj[ctrl.itemId]['s'] = 2;
                    $api.rmStorage('newIns');
                    $api.setStorage('newIns', JSON.stringify(inspectMsgObj));
                    break;
            }

            api.hideProgress();

            api.toast({
                msg: '保存成功'
            })

            api.openWin({
                name: 'inspectionItem',
                url: './inspectionItem.html',
                reload: true,
                pageParam: {
                    id: ctrl.prId,
                    name: ctrl.prName,
                    taskid: ctrl.taskId
                }
            });

            // 1、上传照片
            // 2、调用提交设备缺陷接口
            // var pics = ctrl.pics
            // var length = pics.length

            // for (var i = 0; i < length; i++) {
            //     var url = pics[i]['url']
            //     ctrl.uploadPic(url)
            // }

        })

        // 问题类型单选框 选中事件
        $('input[type=radio]').change(function() {

            var value = this.value

            ctrl.quesGrade = value

        })

    }
    /**
     * 上传图片
     * @param {*} msg 
     */
    ctrl.uploadPic = function (file) {

        var url = "/ems/rest/common/file/pad_upload";
        var data = file

        $api.uploadFile(url, data, function (res, err) {

            if (err) {
                ctrl.toast("网络请求失败,请稍后再试");
            } else {
                if (res.code == 200) {
                    // 将返回的图片路径保存
                    if (res.body && res.body.fileUrl) {
                        ctrl.serverPicUrls.push(res.body.fileUrl)

                        ctrl.uploadPicNum++

                        if (ctrl.uploadPicNum == ctrl.pics.length) {// 代表全部图片上传完成
                            // 2、调用提交 设备缺陷接口
                            ctrl.comitProblem()
                        }
                    } else {
                        ctrl.toast("服务器错误，未返回数据");
                    }
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }

        })
    }

    /**
     * 提交设备缺陷
     * @param {*} msg 
     */
    ctrl.comitProblem = function () {
        var picture = ctrl.serverPicUrls.join(',')
        var problemDesc = $('#problem-desc').val()

        var url = '/ems/rest/xj/problem'
        var data = {
            taskId: ctrl.taskId,
            itemId: ctrl.itemId,
            source: ctrl.source,
            problemDesc: problemDesc,
            picture: picture,
            record: '',
            quesGrade: ctrl.quesGrade,
            prId: ctrl.prId
        }

        $api.post(url, data, function (res, err) {
            api.hideProgress();

            if (err) {
                ctrl.toast("网络请求失败,请稍后再试");
            } else {
                if (res.code == 200) {
                    ctrl.flag = 1
                    // 跳转到巡检内容页
                    api.openWin({
                        name: 'inspectionItem',
                        url: './inspectionItem.html',
                        pageParam: {
                            id: ctrl.prId,
                            name: ctrl.prName,
                            taskid: ctrl.taskId
                        }
                    });
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }

        })
    }

    /**
     * 弹出提示框
     */

    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({});
    }

    //上拉加载
    api.addEventListener({
        name: 'scrolltobottom'
    }, function (ret, err) {
        

    });

    //下拉刷新
    api.setRefreshHeaderInfo({
        loadingImg: 'widget://image/refresh.png',
        bgColor: '#ccc',
        textColor: '#fff',
        textDown: '下拉刷新...',
        textUp: '松开刷新...'
    }, function (ret, err) {
        

        api.refreshHeaderLoadDone();
    });

    ctrl.init();

}
