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

        firstLoadUsual: !$api.getStorage('usualIns') ? 'yes' : 'no', // yes：当前 日常检查项 页面是从异常巡检项填写页保存跳转来，no：当前页面是首次渲染
        firstLoadReview: !$api.getStorage('reviewIns') ? 'yes' : 'no', // yes：当前 复检检查项 页面是从异常巡检项填写页保存跳转来，no：当前页面是首次渲染
        firstLoadNew: !$api.getStorage('newIns') ? 'yes' : 'no', // yes：当前 新增检查项 页面是从异常巡检项填写页保存跳转来，no：当前页面是首次渲染

        // 当前展示的tab 页类型，1:日常检查项   2：突发项  3：复检项
        tabType: 1,
        date: '',

        prId: null,
        prName: '',
        taskId: null,

        problems: null, // 设备缺陷信息字符串
        problemsObj: null, // 设备缺陷信息对象

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

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

        serverPicUrls: [],

    }

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

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

        ctrl.prId = api.pageParam.id;
        ctrl.prName = api.pageParam.name;
        ctrl.taskId = api.pageParam.taskid;

        // 获取保存的设备缺陷信息
        if ($api.getStorage('problems')) {
            ctrl.problems = $api.getStorage('problems');
            ctrl.problemsObj = JSON.parse($api.getStorage('problems'))
        }

        var dateUtil = new DateUtils();
        ctrl.date = dateUtil.getFormattedDate('yyyy-MM-dd');

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

        ctrl.initUsualTab()
        ctrl.initReviewTab()
        ctrl.renderNewTasks()

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

        //点击  日常检查项  tab按钮
        $api.addEvt($api.dom("#usual-task-tab"), "touchend", function () {
            if (ctrl.tabType == 1) {
                return
            }

            if (ctrl.emptyType.usual) {
                $api.css($api.dom('#inspectionitem-empty-tips'), "display:block");
            } else {
                $api.css($api.dom('#inspectionitem-empty-tips'), "display:none");
            }

            $api.addCls(this, "active");
            $api.removeCls($api.dom("#review-task-tab"), "active");
            $api.removeCls($api.dom("#new-task-tab"), "active");
            $api.css($api.dom("#usual-task-panel"), 'display:block');
            $api.css($api.dom("#review-task-panel"), 'display:none');
            $api.css($api.dom("#new-task-panel"), 'display:none');

            ctrl.tabType = 1

            // ctrl.initPrMsgTab()
        }, false);

        //点击  复查检查项  tab按钮
        $api.addEvt($api.dom("#review-task-tab"), "touchend", function () {
            if (ctrl.tabType == 3) {
                return
            }

            if (ctrl.emptyType.review) {
                $api.css($api.dom('#inspectionitem-empty-tips'), "display:block");
            } else {
                $api.css($api.dom('#inspectionitem-empty-tips'), "display:none");
            }

            $api.addCls(this, "active");
            $api.removeCls($api.dom("#usual-task-tab"), "active");
            $api.removeCls($api.dom("#new-task-tab"), "active");
            $api.css($api.dom("#review-task-panel"), 'display:block');
            $api.css($api.dom("#usual-task-panel"), 'display:none');
            $api.css($api.dom("#new-task-panel"), 'display:none');

            ctrl.tabType = 3

            // 初始化复检检查项 tab
            // ctrl.initReviewTab()

        }, false);

        //点击  新增检查项  tab按钮
        $api.addEvt($api.dom("#new-task-tab"), "touchend", function () {
            if (ctrl.tabType == 2) {
                return
            }

            if (ctrl.emptyType.new) {
                $api.css($api.dom('#inspectionitem-empty-tips'), "display:block");
            } else {
                $api.css($api.dom('#inspectionitem-empty-tips'), "display:none");
            }

            $api.addCls(this, "active");
            $api.removeCls($api.dom("#review-task-tab"), "active");
            $api.removeCls($api.dom("#usual-task-tab"), "active");
            $api.css($api.dom("#new-task-panel"), 'display:block');
            $api.css($api.dom("#review-task-panel"), 'display:none');
            $api.css($api.dom("#usual-task-panel"), 'display:none');

            ctrl.tabType = 2

            // ctrl.getRepairLogs();

        }, false);

        // radio选择框改变事件
        

        /*
            ====================日常检查项 事件======================
        */
        // 点击任意地方，关闭task-item-status-ok弹框
        $api.addEvt($api.dom("body"), "touchend", function () {

            // var domLis = $('.task-item-status-ok.display')
            // // var domLis = $api.dom(".task-item-status-ok.display")
            // var length = domLis.length

            // for (var i = 0; i < length; i++) {
            //     $api.removeCls(domLis[i], 'display');
            // }

        }, false);


        /*
            ====================复查检查项 事件======================
        */

        /*
            ====================新增检查项 事件======================
        */
        // 新增突发检查项 按钮 点击事件
        $('#new-add-btn').on("touchend", function () {

            api.prompt({
                title: '巡检项描述:'
            }, function (ret, err) {
                var text = ret.text;

                if (ret.buttonIndex == 2) { // 点击确定按钮
                    ctrl.addNewInspItem(text);
                }
            })

        })

        /*
        *   =====================自动勾选、巡检完成===================
        */
        // 自动勾选剩余项按钮 点击事件
        $('#auto-checked-all').on("touchend", function () {
            api.showProgress({
                title: '处理中...',
                text: '请稍后',
                modal: true
            });

            // 1、将剩余未勾选的 √ 状态改为选中状态
            var domList = $(".task-item[data-status='']")
            var len = domList.length
            for (var i = 0; i < len; i++) {
                var dom = $($(domList[i]).find('.task-item-img-success')[0])
                
                if (!dom.hasClass('light')) {
                    dom.addClass('light')
                }
            }
            // 2、将剩余未选项的父元素 .task-item 上的 data-status 属性值填充为0，并更新localStorage
            var usualIns = $api.getStorage('usualIns');
            var reviewIns = $api.getStorage('reviewIns');
            var newIns = $api.getStorage('newIns');

            var usualInsObj = usualIns? JSON.parse(usualIns) : null;
            var reviewInsObj = reviewIns? JSON.parse(reviewIns) : null;
            var newInsObj = newIns? JSON.parse(newIns) : null;
            
            var taskItemDomList = $('.task-item')
            var length = taskItemDomList.length
            for (var j = 0; j < length; j++) {
                var dom = $(taskItemDomList[j])
                var status = dom.data('status')
                var itemId;
                if (status === '') {
                    dom.data('status', 0)

                    // 更新 localStorage
                    var id = $(dom.parents('.task-panel')[0]).attr('id')

                    switch (id) {
                        case 'usual-task-panel':
                            itemId = dom.data('itemid')
                            usualInsObj[itemId] = 0;
                            $api.rmStorage('usualIns');
                            $api.setStorage('usualIns', JSON.stringify(usualInsObj));
                            break;
                        case 'review-task-panel':
                            itemId = dom.data('itemid')
                            reviewInsObj[itemId] = 0;
                            $api.rmStorage('reviewIns');
                            $api.setStorage('reviewIns', JSON.stringify(reviewInsObj));
                            break;
                        case 'new-task-panel':
                            itemId = dom.data('index')
                            newInsObj[itemId]['s'] = 0;
                            $api.rmStorage('newIns');
                            $api.setStorage('newIns', JSON.stringify(newInsObj));
                            break;
                    }
                }
            }

            api.hideProgress();
        })

        // 巡检完成
        $('#inspection-finished').on("touchend", function () {
            //1、检查是否存在未勾选的巡检项
            var emptyItemList = $(".task-item[data-status='']");
            if (emptyItemList.length) {

                api.confirm({
                    title: '',
                    msg: '有未勾选的巡检项',
                    buttons: ['确定', '取消']
                }, function(ret, err) {
                    
                });

                return;
            }

            api.showProgress({
                title: '提交中...',
                text: '请稍后',
                modal: false
            });
            //2、从localStorage中获取设备缺陷信息（pics路径、desc描述）
            // 存在新增突发项时，提交新增突发项
            var newItemDoms = $('#new-task-panel .task-item')
            ctrl.newTflen = newItemDoms.length;
            if (ctrl.newTflen) {

                newItemDoms.forEach(function (newItemDom, newItemDomIndex) {
                    var checkItem = $($(newItemDom).find('.task-item-desc')[0]).text();
                    var status = $(newItemDom).data('status');

                    (function () {
                        ctrl.submitTfItem(checkItem, status, $(newItemDom), newItemDomIndex);
                    })()
                })

            } else {

                if (ctrl.problems) { // 没有突发项提交，但有设备缺陷
                    ctrl.handleUploadPic();

                } else { // 没有突发项提交，也没有设备缺陷

                    ctrl.comitUsual();
                    
                }

            }

            //3、先将每一条设备缺陷中的图片上传，再将当前设备缺陷提交；循环提交全部设备缺陷
            //4、调用巡检完成接口，完成当前配电室的巡检
            //5、将 localStorage 中保存的巡检项状态信息 和 设备缺陷信息清空


        })

    }

    /*
        日常检查项 tab 中的事件绑定
    */
    ctrl.usualBind = function () {
        // 点击设备分类，自动折叠当前分类的巡检项
        $("#usual-task-panel").on("touchend", ".category-name", function () {

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

        })

        // 点击√
        $("#usual-task-panel .task-item-img-success").on("touchend", "img", function (e) {
            e.stopPropagation();
            //切换√选中状态
            $api.addCls($(this).parent()[0], 'light');
            // 将同一项的x选中状态取消
            $api.removeCls($($(this).parents()[0]).siblings('.task-item-img-error')[0], 'light');
            // 切换弹框显示状态
            $api.toggleCls($(this).siblings('.task-item-status-ok')[0], 'display')
            // 更新 父元素 .task-item 上的 data-status 属性值
            // 1、获取 当前巡检项选择的状态值
            var val = $($(this).siblings('.task-item-status-ok')[0]).children("input:checked")[0].value
            // 2、将状态值 更新到父元素 .task-item 上的 data-status 属性
            var itemDom = $($(this).parents('.task-item')[0])
            itemDom.data('status', val)

            // 保存在 localStorage 中的设备缺陷，判断是否含有当前巡检项的问题，若有则删除，并更新设备缺陷 storage
            var itemId = itemDom.data('itemid')
            var problems = $api.getStorage('problems');
            if (!problems) {
                return
            }
            var problemsObj = JSON.parse(problems);
            var probArr = problemsObj.arr;
            var len = probArr.length;
            if (len) {
                var _probArr = problemsObj.arr;

                probArr.forEach(function (t, i) {
                    if (t.itemId == itemId) {
                        _probArr.splice(i, 1)
                    }
                })

                problemsObj.arr = _probArr;

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

        // 单选框 选中事件
        $('#usual-task-panel input[type=radio]').change(function () {

            // 将 value 值 更新到父元素 .task-item 上的 data-status 属性值
            var value = this.value

            $(this).parents('.task-item').data('status', value)

        })

        // 点击×，切换×选中状态
        $("#usual-task-panel .task-item-img-error").on("touchend", "img", function () {

            // 切换x选中状态
            // $api.addCls($(this).parent()[0], 'light');
            // 将同一项的√选中状态取消
            // $api.removeCls($($(this).parents()[0]).siblings('.task-item-img-success')[0], 'light');

            /**
             * 将当前item的勾选状态更新到localStorage中的 usualIns 中
             * */
            var usualInsObj = JSON.parse($api.getStorage('usualIns'))

            // 日常检查项domList
            var usualItems = $('#usual-task-panel li.task-item');

            usualItems.forEach(function (uItem, uI) {
                var itemId = $(uItem).attr('data-itemid')
                usualInsObj[itemId] = $(uItem).attr('data-status')
            })

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

            // 将状态值 更新到父元素 .task-item 上的 data-status 属性
            // $(this).parents('.task-item').data('status', 2);

            var itemId = $($(this).parents('.task-item')[0]).data('itemid');
            // 跳转到设备缺陷页
            api.openWin({
                name: 'inspectionProblem',
                url: './inspectionProblem.html',
                reload: true,
                pageParam: {
                    prid: ctrl.prId,
                    taskid: ctrl.taskId,
                    itemid: itemId,
                    source: ctrl.tabType,
                    prname: ctrl.prName,
                    tabtype: 'usual'
                }
            });

        })

    }

    /**
     *  复查检查项 tab 中的事件绑定
    */
    ctrl.reviewBind = function () {

        // 点击√
        $("#review-task-panel .task-item-img-success").on("touchend", "img", function (e) {
            e.stopPropagation();
            //切换√选中状态
            $api.addCls($(this).parent()[0], 'light');
            // 将同一项的x选中状态取消
            $api.removeCls($($(this).parents()[0]).siblings('.task-item-img-error')[0], 'light');
            // 切换弹框显示状态
            $api.toggleCls($(this).siblings('.task-item-status-ok')[0], 'display')
            // 更新 父元素 .task-item 上的 data-status 属性值
            // 1、获取 当前巡检项选择的状态值
            var val = $($(this).siblings('.task-item-status-ok')[0]).children("input:checked")[0].value
            // 2、将状态值 更新到父元素 .task-item 上的 data-status 属性
            var itemDom = $($(this).parents('.task-item')[0])
            itemDom.data('status', val)

            // 保存在 localStorage 中的设备缺陷，判断是否含有当前巡检项的问题，若有则删除，并更新设备缺陷 storage
            var itemId = itemDom.data('itemid')
            var problems = $api.getStorage('problems');
            if (!problems) {
                return
            }
            var problemsObj = JSON.parse(problems);
            var probArr = problemsObj.arr;
            var len = probArr.length;
            if (len) {
                var _probArr = problemsObj.arr;

                probArr.forEach(function (t, i) {
                    if (t.itemId == itemId) {
                        _probArr.splice(i, 1)
                    }
                })

                problemsObj.arr = _probArr;

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

        // 单选框 选中事件
        $('#review-task-panel input[type=radio]').change(function () {

            // 将 value 值 更新到父元素 .task-item 上的 data-status 属性值
            var value = this.value

            $(this).parents('.task-item').data('status', value)

        })

        // 点击×，切换×选中状态
        $("#review-task-panel .task-item-img-error").on("touchend", "img", function () {

            // 切换x选中状态
            // $api.addCls($(this).parent()[0], 'light');
            // 将同一项的√选中状态取消
            // $api.removeCls($($(this).parents()[0]).siblings('.task-item-img-success')[0], 'light');

            /**
             * 将当前item的勾选状态更新到localStorage中的 reviewIns 中
             * */
            var reviewInsObj = JSON.parse($api.getStorage('reviewIns'))

            // 日常检查项domList
            var reviewItems = $('#review-task-panel li.task-item');

            reviewItems.forEach(function (vItem, vI) {
                var itemId = $(vItem).attr('data-itemid')
                reviewInsObj[itemId] = $(vItem).attr('data-status')
            })

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

            // 将状态值 更新到父元素 .task-item 上的 data-status 属性
            // $(this).parents('.task-item').data('status', 2);

            var itemId = $($(this).parents('.task-item')[0]).data('itemid');
            // 跳转到设备缺陷页
            api.openWin({
                name: 'inspectionProblem',
                url: './inspectionProblem.html',
                reload: true,
                pageParam: {
                    prid: ctrl.prId,
                    taskid: ctrl.taskId,
                    itemid: itemId,
                    source: ctrl.tabType,
                    prname: ctrl.prName,
                    tabtype: 'review'
                }
            });

        })

    }

    /**
     *  新增检查项 tab 中的事件绑定
    */
    ctrl.newBind = function () {
        // 点击√
        $($("#new-task-panel .task-item-img-success").last()[0]).on("touchend", "img", function (e) {
            e.stopPropagation();
            //切换√选中状态
            $api.addCls($(this).parent()[0], 'light');
            // 将同一项的x选中状态取消
            $api.removeCls($($(this).parents()[0]).siblings('.task-item-img-error')[0], 'light');
            // 切换弹框显示状态
            $api.toggleCls($(this).siblings('.task-item-status-ok')[0], 'display')
            // 更新 父元素 .task-item 上的 data-status 属性值
            // 1、获取 当前巡检项选择的状态值
            var val = $($(this).siblings('.task-item-status-ok')[0]).children("input:checked")[0].value
            // 2、将状态值 更新到父元素 .task-item 上的 data-status 属性
            var itemDom = $($(this).parents('.task-item')[0])
            itemDom.data('status', val)

            // 保存在 localStorage 中的设备缺陷，判断是否含有当前巡检项的问题，若有则删除，并更新设备缺陷 storage
            var index = itemDom.data('index')
            var problems = $api.getStorage('problems');
            if (!problems) {
                return
            }
            var problemsObj = JSON.parse(problems);
            var newProbArr = problemsObj.newArr;
            var len = newProbArr.length;
            if (len) {
                var _newProbArr = problemsObj.newArr;

                newProbArr.forEach(function (t, i) {
                    if (t.index == index) {
                        _newProbArr.splice(i, 1)
                    }
                })

                problemsObj.newArr = _newProbArr;

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

        // 单选框 选中事件
        $('#new-task-panel input[type=radio]').change(function () {

            // 将 value 值 更新到父元素 .task-item 上的 data-status 属性值
            var value = this.value

            $(this).parents('.task-item').data('status', value)

        })

        // 点击×，切换×选中状态
        $($("#new-task-panel .task-item-img-error").last()[0]).on("touchend", "img", function () {

            // 切换x选中状态
            // $api.addCls($(this).parent()[0], 'light');
            // 将同一项的√选中状态取消
            // $api.removeCls($($(this).parents()[0]).siblings('.task-item-img-success')[0], 'light');

            /**
             * 将当前item的勾选状态更新到localStorage中的 newIns 中
             * */
            var newInsObj = JSON.parse($api.getStorage('newIns'))

            // 日常检查项domList
            var newItems = $('#new-task-panel li.task-item');

            newItems.forEach(function (vItem, vI) {
                var index = $(vItem).data('index')
                newInsObj[index]['s'] = $(vItem).data('status')
            })

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

            // 将状态值 更新到父元素 .task-item 上的 data-status 属性
            // $(this).parents('.task-item').data('status', 2);

            var index = $($(this).parents('.task-item')[0]).data('index');
            // 跳转到设备缺陷页
            api.openWin({
                name: 'inspectionProblem',
                url: './inspectionProblem.html',
                reload: true,
                pageParam: {
                    prid: ctrl.prId,
                    taskid: ctrl.taskId,
                    itemid: index,
                    source: ctrl.tabType,
                    prname: ctrl.prName,
                    tabtype: 'new'
                }
            });

        })

    }


    /**
     * 弹出提示框
     */

    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.initUsualTab = function () {
        ctrl.getUsualTasks()
    }
    // 获取日常检查项
    ctrl.getUsualTasks = function () {
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        var url = "/ems/rest/xj/routine/item/list";
        var data = {
            prId: ctrl.prId,
            xjDate: ctrl.date
        }
        $api.get(url, data, function (res, err) {
            api.hideProgress();

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

                        ctrl.usualBind()

                        ctrl.emptyType.usual = false;
                        $api.css($api.dom('#inspectionitem-empty-tips'), "display:none");
                    } else {
                        ctrl.emptyType.usual = true;
                        $api.css($api.dom('#inspectionitem-empty-tips'), "display:block");
                    }
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }
        })
    }

    // 渲染日常巡检项
    ctrl.renderUsualTasks = function (data) {
        /**
             * 将当前日常检查项的每项的勾选状态保存到localStorage中
             * 结构：
             * usualIns: {
             *      itemId: val // 勾选状态值
             * }
             * */
        var type = false;
        var usualInsObj;
        if (ctrl.firstLoadUsual == 'yes') { // 当前日常检查项DOM是首次渲染，不是从异常检查项页面中保存后跳转而来
            type = true;

            var usualIns = ''

            // 将日常检查项信息初始化到localStorage中
            $api.setStorage('usualIns', JSON.stringify(usualIns))
        } else { // 当前日常检查项页面是从异常检查项页面中保存后跳转而来
            // 获取 localStorage 中保存的巡检项状态信息
            var usualIns = $api.getStorage('usualIns');
            usualInsObj = JSON.parse(usualIns);
        }

        // 处理DOM
        $('#usual-task-panel>ul').empty();

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

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

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

            categoryDom += (function (i, itemList, type) {
                return getItemDom(i, itemList, type)
            })(i, itemList, type)

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

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

            tpl += dom
        }

        $api.html($api.dom('#usual-task-panel>ul'), tpl);

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

            if (type) {
                var s = JSON.parse($api.getStorage('usualIns'));
                var usualIns = s ? s : {};
            }

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

                var itemDom = ''
                itemDom +=   '<li class="task-item" data-status="{{status}}" data-itemid="{{itemId}}">'
                itemDom +=        '<div class="task-item-desc">'
                itemDom +=            '{{taskItemDesc}}'
                itemDom +=        '</div>'
                itemDom +=        '<div class="task-item-img">'
                itemDom +=            '<span class="task-item-status-box task-item-img-success {{successClass}}">'
                itemDom +=                '<span class="task-item-status-ok">'
                itemDom +=                    '<input {{checked0}} type="radio" name="task-item-status{{index}}" id="normal{{index}}" value="0">'
                itemDom +=                    '<label for="normal{{index}}">正常</label>'
                itemDom +=                    '&nbsp;&nbsp;&nbsp;'
                itemDom +=                    '<input {{checked1}} type="radio" name="task-item-status{{index}}" id="resolved{{index}}"  value="1">'
                itemDom +=                    '<label for="resolved{{index}}">异常已解决</label>'
                itemDom +=                '</span>'
                itemDom +=                '<img class="success-dark" src="../../image/success-dark.svg" alt="">'
                itemDom +=                '<img class="success-light" src="../../image/success-light.svg" alt="">'
                itemDom +=            '</span>'
                itemDom +=            '<span class="task-item-img-error {{errorClass}}">'
                itemDom +=                '<img class="error-dark" src="../../image/error-dark.svg" alt="">'
                itemDom +=                '<img class="error-light" src="../../image/error-light.svg" alt="">'
                itemDom +=            '</span>'
                itemDom +=        '</div>'
                itemDom +=    '</li>'

                var dom = itemDom.replace('{{itemId}}', item.itemId)
                    .replace('{{taskItemDesc}}', item.checkItem)
                    .replace(/{{index}}/g, index + '' + i);

                if (type) { // 首次渲染
                    dom = dom.replace('{{status}}', '')
                        .replace('{{checked0}}', 'checked')
                        .replace('{{checked1}}', '')
                        .replace('{{successClass}}', '')
                        .replace('{{errorClass}}', '')
                } else { // 不是首次渲染，是从设备缺陷页跳转而来
                    dom = dom.replace('{{status}}', usualInsObj[item.itemId])
                        .replace('{{checked0}}', (usualInsObj[item.itemId] == '0' || usualInsObj[item.itemId] == '' || usualInsObj[item.itemId] == '2') ? 'checked' : '')
                        .replace('{{checked1}}', usualInsObj[item.itemId] == '1' ? 'checked' : '')
                        .replace('{{successClass}}', (usualInsObj[item.itemId] == '0' || usualInsObj[item.itemId] == '1') ? 'light' : '')
                        .replace('{{errorClass}}', usualInsObj[item.itemId] == '2' ? 'light' : '')
                }


                tpl += dom

                if (type) {
                    usualIns[item.itemId] = ''
                }
            }

            if (type) {
                $api.rmStorage('usualIns');
                $api.setStorage('usualIns', JSON.stringify(usualIns))
            }

            return tpl;
        }
    }

    /*
        ====================复查检查项======================
    */
    // 初始化 日常检查项 tab
    ctrl.initReviewTab = function () {
        ctrl.getReviewTasks()
    }
    // 获取复查检查项
    ctrl.getReviewTasks = function () {
        api.showProgress({
            title: '载入中...',
            text: '请稍后',
            modal: false
        });

        var url = "/ems/rest/xj/fj/item/list";
        var data = {
            prId: ctrl.prId
        }
        $api.get(url, data, function (res, err) {
            api.hideProgress();

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

                        ctrl.reviewBind()

                        ctrl.emptyType.review = false;
                        $api.css($api.dom('#inspectionitem-empty-tips'), "display:block");
                    } else {
                        // 显示无数据提示
                        ctrl.emptyType.review = true;
                        $api.css($api.dom('#inspectionitem-empty-tips'), "display:none");
                    }
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }
        })
    }

    // 渲染复查检查项
    ctrl.renderReviewTasks = function (data) {

        /**
         * 将当前复查检查项的每项的勾选状态保存到localStorage中
         * 结构：
         * reviewIns: {
         *      itemId: val // 勾选状态值
         * }
         * */
        var type = false;
        var reviewInsObj;
        if (ctrl.firstLoadReview == 'yes') { // 当前检查项DOM是首次渲染，不是从异常检查项页面中保存后跳转而来
            type = true;

            reviewInsObj = {};

        } else { // 当前检查项页面是从异常检查项页面中保存后跳转而来
            // 获取 localStorage 中保存的巡检项状态信息
            var reviewIns = $api.getStorage('reviewIns');
            reviewInsObj = JSON.parse(reviewIns);
        }

        // 处理DOM
        $('#review-task-panel>ul').empty();

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

        for (var i = 0; i < len; i++) {
            var reviewItem = data[i]
            var reviewDom = ''

            reviewDom +=              '<li class="task-item" data-status="{{status}}" data-itemid="{{itemId}}">'
            reviewDom +=                    '<div class="task-item-desc">'
            reviewDom +=                        '{{checkItem}}'
            reviewDom +=                    '</div>'
            reviewDom +=                    '<div class="task-item-img">'
            reviewDom +=                        '<span class="task-item-status-box task-item-img-success {{successClass}}">'
            reviewDom +=                            '<span class="task-item-status-ok">'
            reviewDom +=                                '<input {{checked0}} type="radio" name="task-item-status{{index}}" id="normal{{index}}" value="0">'
            reviewDom +=                                '<label for="normal{{index}}">正常</label>'
            reviewDom +=                                '&nbsp;&nbsp;&nbsp;'
            reviewDom +=                                '<input {{checked1}} type="radio" name="task-item-status{{index}}" id="resolved{{index}}"  value="1">'
            reviewDom +=                                '<label for="resolved{{index}}">异常已解决</label>'
            reviewDom +=                            '</span>'
            reviewDom +=                            '<img class="success-dark" src="../../image/success-dark.svg" alt="">'
            reviewDom +=                            '<img class="success-light" src="../../image/success-light.svg" alt="">'
            reviewDom +=                        '</span>'
            reviewDom +=                        '<span class="task-item-img-error {{errorClass}}">'
            reviewDom +=                            '<img class="error-dark" src="../../image/error-dark.svg" alt="">'
            reviewDom +=                            '<img class="error-light" src="../../image/error-light.svg" alt="">'
            reviewDom +=                        '</span>'
            reviewDom +=                    '</div>'
            reviewDom +=                '</li>'

            var dom = reviewDom.replace('{{itemId}}', reviewItem.itemId)
                .replace('{{checkItem}}', reviewItem.checkItem)
                .replace(/{{index}}/g, i);

            if (type) { // 首次渲染
                dom = dom.replace('{{status}}', '')
                    .replace('{{checked0}}', 'checked')
                    .replace('{{checked1}}', '')
                    .replace('{{successClass}}', '')
                    .replace('{{errorClass}}', '')
            } else { // 不是首次渲染，是从设备缺陷页跳转而来
                dom = dom.replace('{{status}}', reviewInsObj[reviewItem.itemId])
                    .replace('{{checked0}}', (reviewInsObj[reviewItem.itemId] == '0' || reviewInsObj[reviewItem.itemId] == '' || reviewInsObj[reviewItem.itemId] == '2') ? 'checked' : '')
                    .replace('{{checked1}}', reviewInsObj[reviewItem.itemId] == '1' ? 'checked' : '')
                    .replace('{{successClass}}', (reviewInsObj[reviewItem.itemId] == '0' || reviewInsObj[reviewItem.itemId] == '1') ? 'light' : '')
                    .replace('{{errorClass}}', reviewInsObj[reviewItem.itemId] == '2' ? 'light' : '')
            }

            if (type) {
                reviewInsObj[reviewItem.itemId] = ''
            }

            tpl += dom
        }

        if (type) {
            $api.setStorage('reviewIns', JSON.stringify(reviewInsObj))
        }

        $api.html($api.dom('#review-task-panel>ul'), tpl);

    }

    /*
        ====================新增检查项======================
    */
    // 添加一项突发检查项
    ctrl.addNewInspItem = function (text) {
        var liList = $('#new-task-panel .category-item li')
        var index = liList ? liList.length : 0

        var newDom = ''

        newDom +=           '<li class="task-item" data-status="{{status}}" data-itemid="{{itemId}}" data-index="{{index}}">'
        newDom +=                '<div class="task-item-desc">'
        newDom +=                    '{{checkItem}}'
        newDom +=                '</div>'
        newDom +=                '<div class="task-item-img">'
        newDom +=                    '<span class="task-item-status-box task-item-img-success {{successClass}}">'
        newDom +=                        '<span class="task-item-status-ok">'
        newDom +=                            '<input {{checked0}} type="radio" name="task-item-status{{index}}" id="normal{{index}}" value="0">'
        newDom +=                            '<label for="normal{{index}}">正常</label>'
        newDom +=                            '&nbsp;&nbsp;&nbsp;'
        newDom +=                            '<input {{checked1}} type="radio" name="task-item-status{{index}}" id="resolved{{index}}"  value="1">'
        newDom +=                            '<label for="resolved{{index}}">异常已解决</label>'
        newDom +=                        '</span>'
        newDom +=                        '<img class="success-dark" src="../../image/success-dark.svg" alt="">'
        newDom +=                        '<img class="success-light" src="../../image/success-light.svg" alt="">'
        newDom +=                    '</span>'
        newDom +=                    '<span class="task-item-img-error {{errorClass}}">'
        newDom +=                        '<img class="error-dark" src="../../image/error-dark.svg" alt="">'
        newDom +=                        '<img class="error-light" src="../../image/error-light.svg" alt="">'
        newDom +=                    '</span>'
        newDom +=                '</div>'
        newDom +=            '</li>'

        var dom = newDom.replace('{{itemId}}', '')
            .replace('{{checkItem}}', text)
            .replace(/{{index}}/g, index + 1)
            .replace('{{status}}', '')
            .replace('{{checked0}}', 'checked')
            .replace('{{checked1}}', '')
            .replace('{{successClass}}', '')
            .replace('{{errorClass}}', '');

        $('#new-task-panel .category-item').append(dom);

        // 更新 localStorage
        var newIns = $api.getStorage('newIns');
        var type = newIns ? true : false;
        var newInsObj = type ? JSON.parse(newIns) : {};

        var item = {
            s: '',    // status 状态值
            c: text   // 检查项checkItem
        }

        newInsObj[index + 1] = item;

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

        ctrl.newBind();
        // if (index == 0) {
        // }

    }

    // 渲染新增检查项
    ctrl.renderNewTasks = function () {

        if (ctrl.firstLoadNew == 'yes') {
            return;
        }

        var newIns = $api.getStorage('newIns');
        var newInsObj = JSON.parse(newIns);

        var tpl = '';

        $('#new-task-panel ul').empty();

        for (var key in newInsObj) {
            if (newInsObj.hasOwnProperty(key)) {

                var val = newInsObj[key];

                var itemDom = ''

                itemDom +=           '<li class="task-item" data-status="{{status}}" data-itemid="{{itemId}}" data-index="{{index}}">'
                itemDom +=                '<div class="task-item-desc">'
                itemDom +=                    '{{checkItem}}'
                itemDom +=                '</div>'
                itemDom +=                '<div class="task-item-img">'
                itemDom +=                    '<span class="task-item-status-box task-item-img-success {{successClass}}">'
                itemDom +=                        '<span class="task-item-status-ok">'
                itemDom +=                            '<input {{checked0}} type="radio" name="task-item-status{{index}}" id="normal{{index}}" value="0">'
                itemDom +=                            '<label for="normal{{index}}">正常</label>'
                itemDom +=                            '&nbsp;&nbsp;&nbsp;'
                itemDom +=                            '<input {{checked1}} type="radio" name="task-item-status{{index}}" id="resolved{{index}}"  value="1">'
                itemDom +=                            '<label for="resolved{{index}}">异常已解决</label>'
                itemDom +=                        '</span>'
                itemDom +=                        '<img class="success-dark" src="../../image/success-dark.svg" alt="">'
                itemDom +=                        '<img class="success-light" src="../../image/success-light.svg" alt="">'
                itemDom +=                    '</span>'
                itemDom +=                    '<span class="task-item-img-error {{errorClass}}">'
                itemDom +=                        '<img class="error-dark" src="../../image/error-dark.svg" alt="">'
                itemDom +=                        '<img class="error-light" src="../../image/error-light.svg" alt="">'
                itemDom +=                    '</span>'
                itemDom +=                '</div>'
                itemDom +=            '</li>'

                var dom = itemDom.replace('{{itemId}}', '')
                    .replace('{{checkItem}}', val.c)
                    .replace(/{{index}}/g, key)
                    .replace('{{status}}', val.s)
                    .replace('{{checked0}}', (val.s == '0' || val.s == '' || val.s == '2') ? 'checked' : '')
                    .replace('{{checked1}}', val.s == '1' ? 'checked' : '')
                    .replace('{{successClass}}', (val.s == '0' || val.s == '1') ? 'light' : '')
                    .replace('{{errorClass}}', val.s == '2' ? 'light' : '');

                $api.append($api.dom('#new-task-panel ul'), dom);

                ctrl.newBind();

                // tpl += dom

            }

        }

        // $api.html($api.dom('#new-task-panel ul'), tpl);
    }

    /**
     * =========================其他========================
    */
    // 提交突发项
    ctrl.submitTfItem = function (checkItem, status, dom, i) {
        var url = '/ems/rest/xj/tf/item'
        var data = {
            taskId: ctrl.taskId,
            checkItem: checkItem,
            status: status
        }

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

            if (err) {
                api.hideProgress();
                ctrl.toast("网络请求失败,请稍后再试");
            } else {
                if (res.code == 200) {
                    var itemId = res.body;
                    
                    // 更新新增突发项dom 上的itemid
                    dom.data('itemid', itemId);

                    // 更新 localStorage 中 新增突发项的 问题信息 itemId
                    var index = dom.data('index');
                    var newArr = ctrl.problemsObj.newArr;
                    if (newArr.length) {
                        newArr.forEach(function (item, i) {
                            if (item.index == index) {
                                item.itemId = itemId
                            }
                        })

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

                    if (ctrl.newTflen == (i + 1)) {
                        // 突发检查项已经全部提交
                        // 判断是否有设备缺陷需要提交
                        if (ctrl.problems) {
                            ctrl.handleUploadPic();
                        } else {
                            // 如果没有设备缺陷，直接提交常规和复检巡检项日志
                            ctrl.comitUsual();
                        }
                    }
                } else {
                    api.hideProgress();
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }

        })
    }

    // 处理设备缺陷中的图片上传
    ctrl.handleUploadPic = function () {
        ctrl.probsArr = ctrl.problemsObj.arr.concat(ctrl.problemsObj.newArr);

        var len = ctrl.probsArr.length;
        if (len) {
            ctrl.probsArr.forEach(function (probsItem, probsIndex) {
                if (probsItem.picture) {
                    var pictureArr = probsItem.picture.split(',');
                    var pictureLen = pictureArr.length;

                    pictureArr.forEach(function (pictureItem, pictureIndex) {
                        (function () {
                            ctrl.uploadPic(pictureItem, probsIndex, pictureLen, pictureIndex)
                        })()
                    })
                } else {
                    ctrl.comitProblem(probsIndex);
                }
            })
        }
    }

    // 上传设备缺陷图片
    ctrl.uploadPic = function (file, probsIndex, pictureLen, pictureIndex) {
        var pictureIndex = pictureIndex;

        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)

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

        })
    }

    // 提交设备缺陷
    ctrl.comitProblem = function (probsIndex) {
        var picture = ctrl.serverPicUrls? ctrl.serverPicUrls.join(',') : '';
        var problemDesc = ctrl.probsArr[probsIndex]['problemDesc'];
        var itemId = ctrl.probsArr[probsIndex]['itemId'];
        var quesGrade = ctrl.probsArr[probsIndex]['quesGrade'];

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

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

            if (err) {
                ctrl.toast("网络请求失败,请稍后再试");
            } else {
                if (res.code == 200) {
                    ctrl.serverPicUrls = [];
                    if (probsIndex == (ctrl.probsArr.length-1)) {
                        // 调用巡检完成
                        ctrl.comitUsual();
                    }
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }

        })
    }

    // 提交常规检查项巡检结果
    ctrl.comitUsual = function () {
        var routineLogs = [];
        var usualItemDoms = $('#usual-task-panel .task-item');

        usualItemDoms.forEach(function (item, index) {
            var itemid = $(item).data('itemid');
            var status = $(item).data('status');
            routineLogs.push({
                itemId: itemid,
                status: status
            })
        })

        var url = '/ems/rest/xj/routine/log'
        var data = {
            taskId: ctrl.taskId,
            routineLogs: routineLogs
        }

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

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

        })
    }
    // 提交复检检查项巡检结果
    ctrl.comitReview = function () {
        var fjLogs = [];
        var reviewItemDoms = $('#review-task-panel .task-item');
        var len = reviewItemDoms.length;

        if (!len) {
            // 调用巡检完成接口
            ctrl.finished();

            return;
        }

        reviewItemDoms.forEach(function (item, index) {
            var itemid = $(item).data('itemid');
            var status = $(item).data('status');
            fjLogs.push({
                itemId: itemid,
                status: status
            })
        })

        var url = '/ems/rest/xj/fj/log'
        var data = {
            taskId: ctrl.taskId,
            fjLogs: fjLogs
        }

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

            if (err) {
                ctrl.toast("网络请求失败,请稍后再试");
            } else {
                if (res.code == 200) {
                    // 调用巡检完成接口
                    ctrl.finished();
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }

        })
    }

    // 巡检完成
    ctrl.finished = function () {
        var url = "/ems/rest/xj/task/complete";
        var data = {
            taskId: ctrl.taskId,
        }
        $api.put(url, data, function (res, err) {
            api.hideProgress();
            
            if (err) {
                ctrl.toast("网络请求失败,请稍后再试");
            } else {
                if (res.code == 200) {
                    if (!$api.getStorage('canUploadFlag')) {
                        $api.setStorage('canUploadFlag', 'true')
                    }

                    // 清除 localStorage 中保存的内容
                    $api.rmStorage('usualIns')
                    $api.rmStorage('reviewIns')
                    $api.rmStorage('newIns')
                    $api.rmStorage('problems')

                    api.openWin({
                        name: 'inspectionFrame',
                        url: '../index/inspectionFrame.html',
                        reload: true,
                        pageParam: {}
                    });
                } else {
                    ctrl.toast("服务器响应错误" + (res.code ? ("，错误码：" + res.code) : ""));
                }
            }
        })
    }

    ctrl.init();

}
