var firstLevelId,
    secondLevelId = '',
    selectedTab = 0, //顶部tab选中的index 
    page = [],
    pageSize = 10,
    loaded = [],
    patient, 
    patientName,
    teamCode,
    pCodes, //从慢病管理页面中跳转过来的多个居民的code
    referrer;
var isAdmin; //判断是否是管理员
var docInfo;
    
var scrollers = [];
mui.init();
mui.plusReady(function(){
    var self = plus.webview.currentWebview();
    firstLevelId = self.firstLevelId;
    isAdmin = self.isAdmin;
    patient = self.patient; 
    patientName = self.patientName;
    teamCode = self.teamCode;
    pCodes = self.pCodes;
    referrer = self.referrer;
    
    if(!isAdmin){
        $(".xuanfu").show();
    }
    
    docInfo = JSON.parse(plus.storage.getItem("docInfo"));
    getSecondLevelCategory();
    bindEvents();
});
function getSecondLevelCategory(){
    var url = "/third/jkEdu/Article/getCategoryList",
        params = {
            categoryLevel: 2,
            firstlevelId: firstLevelId
        };
    sendGet(url, params, null, function(res){
        if(res.status == 200){
            var html = template("tab-tmp", {list: res.data});
//          $("#tabPanel").empty().append(html);
            var controlPanelHtml = template("control-panel-tmp", {list: res.data});
//          $(".mui-slider-group").empty().append(controlPanelHtml);
            
            $(".mui-content").append(html + controlPanelHtml);
            var gallery = mui('.mui-slider');
            gallery.slider();
            initTabScroller();
            initScroller();
            
//          secondLevelId = res.data[0].categoryid;
            getArticleList(true);
            loaded[0] = "true";
            document.querySelector('.mui-slider').addEventListener('slide', function(event) {
                selectedTab = event.detail.slideNumber;
                var $item = $("#tabPanel a").eq(selectedTab);
                secondLevelId = $item.attr("data-id");
                if(loaded[selectedTab] == "false"){
                    getArticleList(true);
                    loaded[selectedTab] = "true";
                }
            });
        }else{
            mui.toast(res.msg);
        }
    },true);
}
function getArticleList(isInit){
    if(isInit){
        page[selectedTab] = 0;
    }
    var url = "/doctor/jkEdu/article/PC/queryArticlePcList",
        params = {
            firstLevelCategoryId: firstLevelId,
            secondLevelCategoryId: secondLevelId,
            currentUserRole: docInfo.hospital,
            currentUserRoleLevel: 4,
            iDisplayStart: page[selectedTab] * pageSize,
            iDisplayLength: pageSize,
            isAuthentication: 1, //已认证过的文章
            roleType: 1 //1、普通医生,2、管理员
        };
    if(patient){
        params.patient = patient;
    }
    if(isAdmin){
        var selectedRole = JSON.parse(plus.storage.getItem("selectedRole"));
        params.currentUserRole = selectedRole.code;
        params.currentUserRoleLevel = selectedRole.level;
        params.roleType = 2;
    }
    sendGet(url, params, null, function(res){
        if(res.status == 200){
            if(isInit){
                if(res.data.aaData.length == 0){
                    $("#item"+(selectedTab)+" .mui-table-view").hide();
                    $("#item"+(selectedTab)+" .no-result").show();
                }else{
                    loaded[selectedTab] = "true";
                    var html = template("articleimgLi", {list: res.data.aaData});
                    $("#item"+(selectedTab)+" .mui-table-view").empty().append(html);
                }
            }else{
                var html = template("articleimgLi", {list: res.data.aaData});
                $("#item"+(selectedTab)+" .mui-table-view").append(html);
            }
            
            if(res.data.aaData.length < pageSize){
//              scrollers[selectedTab].disablePullupToRefresh();
                scrollers[selectedTab].endPullupToRefresh(true);
            }else{
                page[selectedTab] ++ ;
                scrollers[selectedTab].endPullupToRefresh();
//              scrollers[selectedTab].enablePullupToRefresh();
            }
        }else{
            mui.toast(res.msg);
        }
    }, true);
}
/*
 * 收藏文章
 */
function collectionArticle(code,$this){
    plus.nativeUI.showWaiting();
    var params = {};
    params.articleId = code;
    params.userType = 1; //1医生,2居民
    sendPost("/third/jkEdu/Article/saveArticleCollection",params,function(res){
        plus.nativeUI.closeWaiting();
        if(res.msg){            
            plus.nativeUI.toast(res.msg);
        }else{
            plus.nativeUI.toast("收藏失败!");
        }   
    },function(res){
        plus.nativeUI.closeWaiting();
        if(res.status==200){
            $this.attr("data-status", 1);
            $this.find("img").attr("src", "../images/shoucang_pre.png");
            var span  = $this.find("span");
            var collectNum = parseInt(span.html());
            span.html(collectNum+1);
            plus.nativeUI.toast("收藏成功");
        }else{
            if(res.msg){
                plus.nativeUI.toast(res.msg);
            }else{
                plus.nativeUI.toast("收藏失败!");
            }   
        }
        
    })
    
}
/*
 * 取消收藏文章
 */
function unCollectionArticle(code,$this){
    plus.nativeUI.showWaiting();
    var params = {};
    params.articleId=code;
    params.userType = 1; //1医生,2居民
    sendPost("/third/jkEdu/Article/cancelArticleCollection",params,function(res){
        plus.nativeUI.closeWaiting();
        if(res.msg){            
            plus.nativeUI.toast(res.msg);
        }else{
            plus.nativeUI.toast("取消收藏失败!");
        }   
    },function(res){
        plus.nativeUI.closeWaiting();
        if(res.status==200){
            $this.attr("data-status", 0);
            $this.find("img").attr("src", "../images/shoucang_button.png");
            var span  = $this.find("span");
            var collectNum = parseInt(span.html());
            span.html(collectNum-1);
            plus.nativeUI.toast("取消收藏成功");
        }else{
            if(res.msg){
                plus.nativeUI.toast(res.msg);
            }else{
                plus.nativeUI.toast("取消收藏失败!");
            }   
        }
        
    })
}
//弹框提示是否发送给居民
function showDialog(article,title,patientName) {
    dialog({
        title: '
',
        content: '',
        okValue: '立即发送',
        cancelValue: '我再看看',
        cancel: function () {
            return;
        },
        ok: function() {
            send(article);
        }
    }).showModal();
}
//发送文章给患者
function send(article){
    var url = "/doctor/jkEdu/article/doctorSendArticleToPatients",
        params = {
            articleId: article,
            patientCode: patient,
            patient: patient,
//          teamCode: teamCode,
            leaveWords: $.trim($('#messageInput').val())
        };
    if(pCodes){
        params.patient = pCodes.join(",");
    }
    var docInfo = JSON.parse(plus.storage.getItem('docInfo'));
    params.currentUserRole = docInfo.hospital;
    params.currentUserRoleLevel = 4;
    
    plus.nativeUI.showWaiting();
    sendPost(url, params, null, function(res){
        if(res.status == 10000){
            mui.toast("发送成功!");
            var $this = $(".share[data-code="+article+"]");
            if(!pCodes){
                $this.after('已发送
');
            }
            var num = $this.find(".send_count").text();
            $this.find(".send_count").text(parseInt(num)+1);
            if(referrer == "manbing"){
                var self = plus.webview.currentWebview(),
                    selfId = self.id;
                backToManbingPage(self, selfId);
            }else if(referrer){
                var self = plus.webview.currentWebview();
                backToPage(self, referrer);
            }
            
        }else{
            if(res.msg){
                mui.toast(res.msg);
            }else{
                mui.toast("发送失败!");
            }  
        }
        plus.nativeUI.closeWaiting();
    });
}
function bindEvents(){
    $("body").on('tap', '#tabPanel a', function(){
        if($(this).hasClass("mui-active")){
            return false;
        }
        selectedTab = $(this).index();
        secondLevelId = $(this).attr("data-id");
        if(loaded[selectedTab] == "false"){
            getArticleList(true);
            loaded[selectedTab] = "true";
        }
    });
    
    $(".xuanfu").on('click', function(){
        $(this).hide();
        $(".div-dialog-content").show();
        $(".modal-overlay").addClass("modal-overlay-visible");
    });
    
    //点击遮罩事件
    $(".modal-overlay").on("click", function(){
        $(".modal-overlay").removeClass("modal-overlay-visible");
        $(".div-dialog-content").hide();
        $(".xuanfu").show();
    });
    
    $(".my-article-icon").on('click', function(){
        $(".modal-overlay").removeClass("modal-overlay-visible");
        $(".div-dialog-content").hide();
        $(".xuanfu").show();
        openWebview("myArticle.html", {
            patient: patient, 
            patientName: patientName,
            pCodes: pCodes,
            referrer: referrer
        });
    });
    
    $(".new-article-icon").on('click', function(){
        $(".modal-overlay").removeClass("modal-overlay-visible");
        $(".div-dialog-content").hide();
        $(".xuanfu").show();
        openWebview("addArticle.html", {hospitalName:docInfo.hospitalName,currentUserRole:docInfo.hospital});
    });
    
    $(".cancel-icon").on('click', function(){
        $(".modal-overlay").removeClass("modal-overlay-visible");
        $(".div-dialog-content").hide();
        $(".xuanfu").show();
    })
    
    $("body").on('tap', ".article-info", function(){
        var code = $(this).attr("data-article-code");
        var title = $(this).attr('data-title');
        if(isAdmin){
            openWebviewExtras("../../home/html/jianjiaotuisong-xiangqing.html",{articleId:code});
        }else{
            openWebview("article-info.html", {
                articleId: code,
                patient: patient, 
                patientName: patientName,
                pCodes: pCodes,
                showHandleBar: true,
                referrer: referrer
            });
        }
        return false;
    }).on('tap','div.collect', function(){
        var $this = $(this);
        var status = $this.attr("data-status");
        var code = $this.attr("data-code");
        if(status == 0){
            collectionArticle(code,$this);
        }else{
            unCollectionArticle(code,$this);
        }
    }).on('tap','div.share', function(){
        var $this = $(this);
        var code = $this.attr("data-code");
        var title = $this.attr("data-title");
        if(isAdmin){
            openWebviewExtras("../../home/html/tuisong_duixiang.html",{articleId:code});
        }else{
            if(!patient){
                if(pCodes){
                    dialog({
                        title: '',
                        content: '',
                        okValue: '立即发送',
                        cancelValue: '我再看看',
                        cancel: function () {
                            return;
                        },
                        ok: function() {
                            send(code);
                        }
                    }).showModal();
                    return false;
                }else{
                    openWebview("xuanzejumin_more.html", {
                        article: code,
                        articleTitle: title,
                        origin: 'jiaoyu'
                    });
                }
            }else{
                showDialog(code,title,patientName);
            }
        }
    });
    
    template.helper("setContent", function(str){
        var reg=/<[^<>]+>/g;
        str = str.replace(reg, '');
        return str;
    });
    
    template.helper("getArticleImage", function(str){
        if(str){
            if(str.indexOf("../") > -1){
                return ""; //原福州代码中返回的相对路径
            }
            var url = getImgUrl(str);
            return "
";
        }
        return "";
    });
    
    template.helper("formatDate", function(str){
        if(str){
            return str.substr(0,19)
        }else{
            return "";
        }
    });
    
    window.addEventListener('reload', function(){
        getArticleList(true);
    })
}
function initTabScroller(){
    //阻尼系数
    var deceleration = mui.os.ios?0.003:0.0009;
    mui('.mui-scroll-wrapper').scroll({
        bounce: false,
        indicators: true, //是否显示滚动条
        deceleration:deceleration
    });
}
function initScroller(){
    if(scrollers.length == 0) {
        $.each(document.querySelectorAll('.mui-slider-group .mui-scroll-wrapper'), function(index, pullRefreshEl) {
            page.push(0);
            loaded.push("false");
            var pullRefresh = mui(pullRefreshEl).pullRefresh({
                down: {
                    callback: function(){
                        getArticleList(true);
                        this.endPulldownToRefresh();
                    }
                },
                up: {
                    callback: function(){
                        var self = this;
                        setTimeout(function(){
                            getArticleList(false);
//                          self.endPullupToRefresh();
                        }, 500);
                    }
                }
            });
            
            scrollers.push(pullRefresh);
        })
    }
}
function backToManbingPage(wv, selfId){
    var targetId = "zhongdiangenzong";
    if(wv.id == targetId){
        setTimeout(function(){
            plus.webview.getWebviewById(selfId).close();
        }, 300);
    }else{
        var opener = wv.opener();
        if(wv.id != selfId){
            wv.close();
        }
        backToManbingPage(opener, selfId);
    }
}
var closeList = [];
function backToPage(wv, wvId){
    if(wv.id == wvId){
        var self = plus.webview.currentWebview();
        if(wvId == "p2dzixun"){
            setTimeout(function(){
                mui.fire(wv, "update");
                wv.show();
                for(i=0; i