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

        // 当前展示的tab 页类型
        tabType: 'guide',

        id: null, // 当前巡检配电室 数据id
        prId: null,
        prName: '',

        problemsObj: null, // 设备缺陷信息对象

        emptyType: {    // 对应的tab是否需要展示无数据提示
            usual: false,
            review: false,
            new: false
        },

        newTflen: 0, // 新增突发项个数

        problemData: {
            status: true, // true:完成了初始化，false:当前存在未提交设备缺陷
            desc: '', // 设备缺陷 文字描述
            pics: [], // 设备缺陷 图片信息
            serverPicUrls: [], // 上传完成，返回的图片 url
            uploadPicNum: 0, // 已经上传完成的图片的数量
            activeProblemItemDom: null, // 当前正在编辑的设备缺陷 DOM
        },

    }

    ctrl.init = function () {
        // 适配安卓状态栏
        CommonModel.fitInStatusBar();
        var tabsTop = $('#heightHeader').height();
        $('#searcher').css('top',tabsTop);

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

        ctrl.employeeId = $api.getStorage('employeeId');
        ctrl.id = api.pageParam.id;
        ctrl.prId = api.pageParam.prid;
        ctrl.prName = api.pageParam.prname;

        ctrl.bind();
        
        // 将title改成配电室名
        $api.html($api.dom('#title-prname'), ctrl.prName);
        
        ctrl.initGuideTab();
    }

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

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

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

            ctrl.tabType = 'guide'

            // 初始化 巡检指导书 tab
            // ctrl.initGuideTab();

        }, false);

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

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

            ctrl.tabType = 'problem';

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

        }, false);
        
        // 点击设备分类，自动折叠当前分类的巡检项
        $("#guide-panel").on("touchend", ".category-name", function () {

            // 隐藏 当前分类的巡检项
            $api.toggleCls($(this).next()[0], 'hide');
            // 分类名前的箭头旋转90度
            $api.toggleCls($api.dom(this, 'img'), 'transform');

        });

        // 点击 巡检完成
        $('#inspect-finish-btn').on("touchend", function () {
            api.confirm({
                title: '',
                msg: '确定完成巡检吗',
                buttons: ['确定', '取消']
            }, function(ret, err) {
                var index = ret.buttonIndex;
                if (index == 1) { // 确定
                    // 判断是否存在未提交的设备缺陷
                    if (!ctrl.problemData.status) {
                        ctrl.toast('存在未提交的设备缺陷!')
                    } else {
                        ctrl.finishInspect();
                    };
                }
            });
        });

        // 点击 新增设备缺陷
        $('#new-add-btn').on("touchend", function () {
            // 判断是否有未提交的设备缺陷
            if (ctrl.problemData.status) {
                // 页面中添加一个 问题 li DOM
                ctrl.addProblemItemDom();

                ctrl.problemData.status = false;
            } else {
                ctrl.toast('存在未提交的设备缺陷!')
            };
        });

        // 点击 相册选择 添加 设备缺陷图片
        $("#problem-list-container").on("touchend", ".pic-add-btn", function () {
            var picContentDom = $($(this).parents('.pic-content')[0]);
            var params = {
                sourceType: 'library',
                // sourceType: 'camera',
                // sourceType: 'album',
                destinationType: 'base64'
            }
            api.getPicture(params, function(ret, err){
                if (ret && ret.data) {
                    // 创建图片预览dom
                    var picItemDom = '<span class="pic-item"><i></i><img class="problem-pic-item" src="{{url}}" alt=""></span>'
                    var dom = picItemDom.replace('{{url}}', ret.data)
                    picContentDom.prepend(dom)

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

                }
            })
        });

        // 点击 拍照 添加 设备缺陷图片
        $("#problem-list-container").on("touchend", ".camera-btn", function () {
            var picContentDom = $($(this).parents('.pic-content')[0]);
            var params = {
                // sourceType: 'library',
                sourceType: 'camera',
                // sourceType: 'album',
                destinationType: 'base64'
            }
            api.getPicture(params, function(ret, err){
                if (ret && ret.data) {
                    // 创建图片预览dom
                    var picItemDom = '<span class="pic-item"><i></i><img class="problem-pic-item" src="{{url}}" alt=""></span>'
                    var dom = picItemDom.replace('{{url}}', ret.data)
                    picContentDom.prepend(dom)

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

                }
            })
        });

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

        // 图片 “删除”
        $("#problem-list-container").on("touchend", "i", function (e) {
            e.stopPropagation();

            var _this = this;

            api.confirm({
                title: '',
                msg: '确定要删除吗',
                buttons: ['确定', '取消']
            }, function(ret, err) {
                var index = ret.buttonIndex;
                if (index == 1) { // 确定
                    var url = $($(_this).siblings('img')[0]).attr('src');
        
                    $(_this).parent('.pic-item').remove();
        
                    // 从 ctrl.problemData.pics 中删除对应url
                    ctrl.problemData.pics = ctrl.problemData.pics.filter(function (item) {
                        return item.url != url;
                    });
                }
            });

        });

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

        // 点击 “删除” 设备缺陷
        $('#problem-list-container').on("touchend", ".delete-btn", function () {
            var _this = this;
            api.confirm({
                title: '',
                msg: '确定要删除吗',
                buttons: ['确定', '取消']
            }, function(ret, err) {
                ctrl.problemData.activeProblemItemDom = $(_this).parents('.problem-item');
            
                var index = ret.buttonIndex;
                if (index == 1) { // 确定
                    ctrl.handleDelete();
                }
            });
        });

        // 点击 “提交” 设备缺陷
        $('#problem-list-container').on("touchend", ".submit-btn", function () {
            ctrl.problemData.activeProblemItemDom = $(this).parents('.problem-item');

            ctrl.problemData.desc = ctrl.problemData.activeProblemItemDom.find('.desc').val().trim();

            api.confirm({
                title: '',
                msg: '确定要提交吗',
                buttons: ['确定', '取消']
            }, function(ret, err) {
                var index = ret.buttonIndex;
                if (index == 1) { // 确定
                    if (!ctrl.problemData.desc.trim()) {
                        ctrl.toast('问题描述不能为空！');
                    } else {
                        ctrl.handleSubmit();
                    };
                }
            });
        });

    };

    // 添加一个 问题 dom
    ctrl.addProblemItemDom = function() {
        var index = $('#problem-list-container li').length + 1;

        var itemDom = '';
        itemDom += '<li class="problem-item">';
        itemDom +=     '<div class="problem-index">';
        itemDom +=         '<div class="problem-item-title">问题<span>{index}</span></div>';
        itemDom +=          '<div class="btns">'
		itemDom +=				'<div class="delete-btn">'
		itemDom +=					'删除'
        itemDom +=				'</div>'
        itemDom +=              '<div class="submit-btn">';
        itemDom +=                  '提交';
        itemDom +=              '</div>';
        itemDom +=          '</div>'
		itemDom +=			'<div class="finished">已提交</div>'
        itemDom +=     '</div>';
        itemDom +=     '<div class="problem-desc">';
        itemDom +=         '<div class="problem-item-title"><b>*</b>问题描述：</div>';
        itemDom +=         '<div>';
        itemDom +=             '<textarea class="desc" name="" id="" cols="30" rows="10" placeholder="请输入问题描述..."></textarea>';
        itemDom +=         '</div>';
        itemDom +=     '</div>';
        itemDom +=     '<div class="problem-pic">';
        itemDom +=         '<div class="problem-item-title">现场照片：</div>';
        itemDom +=         '<div class="pic-content" class="pics problem-item-content">';
        // itemDom +=             '<img class="pic-add-btn" src="../../image/add.png" alt="">';
        itemDom +=             '<span class="pic-item">'
        itemDom +=                 '<img class="camera-btn" src="../../image/camera.png" alt="">'
        itemDom +=             '</span>'
        // itemDom +=             '<span class="pic-item">'
        // itemDom +=                 '<img class="pic-add-btn" src="../../image/album.png" alt="">'
        // itemDom +=             '</span>'
        itemDom +=         '</div>';
        itemDom +=     '</div>';
        itemDom += '</li>';

        itemDom = itemDom.replace('{index}', index);

        $('#problem-list-container').append(itemDom);
    };

    // 处理 删除 事件
    ctrl.handleDelete = function () {
        ctrl.problemData.activeProblemItemDom.remove();
        ctrl.resetProblemData();
    };

    // 处理 提交 事件
    ctrl.handleSubmit = function() {
        api.showProgress();

        var pics = ctrl.problemData.pics;
        var length = pics.length;
        if (length > 0) { // 有图片
            // 上传 图片
            for (var i = 0; i < length; i++) {
                var url = pics[i]['url']
                ctrl.uploadPic(url)
            }
        } else { // 没图片
            ctrl.submitProblem();
        };
    };

    // 重置 设备缺陷 数据表单
    ctrl.resetProblemData = function () {
        ctrl.problemData.status = true;
        ctrl.problemData.desc = '';
        ctrl.problemData.pics = [];
        ctrl.problemData.serverPicUrls = [];
        ctrl.problemData.uploadPicNum = 0;
        ctrl.problemData.activeProblemItemDom = null;
    };

    // 上传图片
    ctrl.uploadPic = function (file) {

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

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

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

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

        })
    };

    // 提交 设备缺陷
    ctrl.submitProblem = function() {
        api.showProgress();

        var zhaoPian = ctrl.problemData.serverPicUrls.join(',');
        var url = '/test/gong-dan/insert';
        var data = {
            tiJiaoRenId: ctrl.employeeId,
            xunJianPrId: ctrl.id,
            prId: ctrl.prId,
            miaoShu: ctrl.problemData.desc,
            isXjProblem: 1
        };

        if (zhaoPian) {
            data.zhaoPian = zhaoPian;
        };

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

            if (err) {
                api.hideProgress();
                ctrl.toast("提交设备缺陷失败,请稍后再试");
            } else {
                if (res.code == 200) {
                    // 隐藏当前设备缺陷的 删除 和 提交 按钮，隐藏 添加图片 删除图片 按钮
                    ctrl.problemData.activeProblemItemDom.find('.btns').css('display', 'none');
                    ctrl.problemData.activeProblemItemDom.find('.finished').css('display', 'block');
                    ctrl.problemData.activeProblemItemDom.find('.pic-add-btn').css('display', 'none');
                    ctrl.problemData.activeProblemItemDom.find('.pic-item i').css('display', 'none');
                    ctrl.problemData.activeProblemItemDom.find('.desc').attr('disabled', 'disabled');

                    // 初始化 problemData
                    ctrl.resetProblemData();

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

        });
    };

    // 初始化 “巡检指导书” tab
    ctrl.initGuideTab = function () {
        ctrl.getInspectItem();
    };

    // 获取 “巡检指导书” 内容
    ctrl.getInspectItem = function() {
        api.showProgress();

        var url = '/test/xun-jian-ri-zhi/queryXunJianXiang/111';
        
        $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.renderInspectItem(res.data);
                }
            }
        });
    };

    // 渲染巡检项
    ctrl.renderInspectItem = function (data) {
        $('#guide-panel>ul').empty();

        var tpl = '';
        var len = data.length;

        for (var i = 0; i < len; i++) {
            var categoryItem = data[i];
            var itemList = categoryItem.xjTplContents;
            var categoryDom = '';

            categoryDom += '<li class="category-item">'
            categoryDom +=      '<div class="category-name">'
            categoryDom +=           '<img class="transform" src="../../image/arrow-bottom.png" />'
            categoryDom +=                 '<span>{{categoryName}}</span>'
            categoryDom +=       '</div>'
            categoryDom +=       '<ul class="hide">'

            categoryDom += getItemDom(itemList)

            categoryDom +=        '</ul>'
            categoryDom += '</li>'

            var dom = categoryDom.replace('{{categoryName}}', categoryItem.tplName);

            tpl += dom;
        }

        $api.html($api.dom('#guide-panel .inspect-item-box'), tpl);

        api.hideProgress();

        // 获取 巡检项 dom
        function getItemDom(itemList) {
            var tpl = ''
            var len = itemList.length

            for (var i = 0; i < len; i++) {
                var item = itemList[i]

                var itemDom = ''
                itemDom +=   '<li class="task-item">'
                itemDom +=        '<div class="task-item-desc">'
                itemDom +=            '{{taskItemDesc}}'
                itemDom +=        '</div>'
                itemDom +=    '</li>'

                var dom = itemDom.replace('{{taskItemDesc}}', item.checkItem);

                tpl += dom

            }

            return tpl;
        }
    };

    // 巡检完成
    ctrl.finishInspect = function() {
        var weather = "晴";
        var qing = $('#weather .qing')[0].checked;
        var yin = $('#weather .yin')[0].checked;
        var yu = $('#weather .yu')[0].checked;
        var xue = $('#weather .xue')[0].checked;
        
        if (qing) {
            weather = '晴';
        } else if (yin) {
            weather = '阴';
        } else if (yu) {
            weather = '雨';
        } else if (xue) {
            weather = '雪';
        };
        
        var remark = $('#remark').val().trim();

        if (!remark) {
            ctrl.toast("请填写巡检备注");
            return;
        };

        api.showProgress();
        
        var url = '/test/xun-jian-pr/updateById';
        var data = {
            id: ctrl.id,
            shiFouWanCheng: 2,
            tianQi: weather,
            beiZhu: remark
        };
        
        $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();
                    // 隐藏巡检完成 按钮
                    $('#inspect-finish-btn').hide();

                    // 返回巡检单详情页 并触发巡检单详情页面定义的 inspectionPrChanged 事件
                    api.sendEvent({
                        name: 'inspectionPrChanged'
                    });

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

    /**
     * 弹出提示框
     */
    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({});
    };

    ctrl.init();

}
