var pageTypeDefault = "zh" ;
$(function () {
	if($("#articleId").length > 0){
		var articleId =  $("#articleId").val();
		
		//citation显示
		showCitation();
	    //关系图
	    //getRelationship();
	    loadCitedByInfo();
		//文章详情页跳转
	    
	    isZhJournalEnArticle();
	    
	    
	    var viewType = getUrlParam("viewType");
		if(viewType && "HTML" == viewType){
			getVisitInfo(articleId,1);
		}else{
			//摘要访问记录
		    getVisitInfo(articleId,0);
		}
	}
})
//中文期刊 英文文章时 中英文位置对调
function isZhJournalEnArticle(){
	var articleL=$("#articleL").val();
	var journalL=$("#journalL").val();
	if(journalL=="zh"&&articleL=="en"){
		//PC
		var citationEn=$("div.citationEn").html();
		var citationCn=$("div.citationCn").html();
		var articleEn=$("div.articleEn").html();
		var articleCn=$("div.articleCn").html();
		var abstractcn=$("div.abstract-cn").html();
		var abstracten=$("div.abstract-en").html();
		
		$("div.citationEn").html(citationCn);
		$("div.citationCn").html(citationEn);
		$("div.articleEn").html(articleCn);
		$("div.articleCn").html(articleEn);
		$("div.abstract-cn").html(abstracten);
		$("div.abstract-en").html(abstractcn);
		//APP
		var articleCn=$("section.articleCn").html();
		var articleEn=$("section.articleEn").html();
		
		$("section.articleEn").html(articleCn);
		$("section.articleCn").html(articleEn);
		$(".open-articleEn").html("<h3 class='mainColor'><span class='iconfont icon-jia'></span>中文摘要</h3>");
	}
}
function showCitation(){
	var articleId =  $("#articleId").val();
	if($("#language").val()=="en"){
		pageType = "en";
    }else{
    	pageType = "cn";
    }
	if(!isNull(articleId)){
    	$.ajax({
    		async:false,
    		type:'post',
    		url:local_host +"article/getCitationStr",
    		data:{'ids':articleId,
				'fileType':2,
				'pageType':pageType},
				success:function(dataMap){
					if(!isNull(dataMap.citationCn)){
						$(".copyCitationInfo-cn").html(dataMap.citationCn);
					}
					if(!isNull(dataMap.citationEn)){
						$(".copyCitationInfo-en").html(dataMap.citationEn);
					}
    		}
		})
    }
}

//下载pdf  ----中文的
function downloadpdf(articleId) {
    var url = local_host + "article/checkArticlePdf?id=" + articleId;
    $.ajax({
        type: "post",
        url: url,
        dataType: "json",
        success: function (data) {
            if (data.access == false) {
            	window.location.href = local_host + 'member/login';
                //alert(data.message);
            } else if (data.result == 'true') {

                var url = local_host + "article/exportPdf";
                var form = $("<form>");   //定义一个form表单
                form.attr('style', 'display:none');   //在form表单中添加查询参数
                form.attr('target', '');
                //form.attr('method', 'post');
                form.attr('action', url);

                var input1 = $('<input>');
                input1.attr('type', 'hidden');
                input1.attr('name', 'id');
                input1.attr('value', articleId);
                $('body').append(form);  //将表单放置在web中
                form.append(input1);   //将查询参数控件提交到表单上
                form.submit();

                //添加文章PDF访问记录
                getVisitInfo(articleId,2);
            } else if (data.result == 'false') {
                var url = window.location.href;
                var pageType = getUrlParam("pageType") || pageTypeDefault;
                if (url.indexOf("_en.htm") > 0 || pageType == "en") {
                    alert("PDF not found!")
                } else {
                    alert("该文章没有PDF");
                }
                //$(".icon-user").click();
            }
        },
        error: function () {
            alert("下载失败，请联系管理员！");
        }
    });
}

/**
 * ajax增加文章HTML浏览次数   ----中文的
 * @return
 */
function ajaxCountHtmlView(articleId) {
    getVisitInfo(articleId,1);
}

function articleVisitMonth(articleId) {
    //按照月份分组统计
    $.ajax({
        type: 'post',
        url: local_host + 'metric/visitMonth',
        data: {'articleId': articleId},
        cache: false,
        dataType: "json",
        success: function (data) {
            var abstractCount = $.map(data, function (n, i) {
                return n.abstractCount;
            });
            var fullTextCount = $.map(data, function (n, i) {
                return n.fullTextCount;
            });
            var pdfCount = $.map(data, function (n, i) {
                return n.pdfCount;
            });
            var createDate = $.map(data, function (n, i) {
                return n.createDate;
            });
            var monthChart = new Highcharts.chart('article_visit_count_column', {
            	credits:{enabled: false},
            	chart: {
                    type: 'column',
                    backgroundColor: 'transparent'
                    	
                },
                title: {
                    text: '近一年内文章摘要浏览量、全文浏览量、PDF下载量统计信息'
                },
                subtitle: {
                    text: ''
                },
                xAxis: {
                    categories: createDate,
                    crosshair: true
                },
                yAxis: {
                    min: 0,
                    title: {
                        text: '访问量'
                    }
                },
                tooltip: {
                    valueDecimals: 0,
                    shared: true,
                    useHTML: true
                },
                plotOptions: {
                    column: {
                        pointPadding: 0.2,
                        borderWidth: 0
                    }
                },
                series: [{
                    name: '摘要浏览量',
                    data: abstractCount
                }, {
                    name: '全文浏览量',
                    data: fullTextCount

                }, {
                    name: 'PDF下载量',
                    data: pdfCount
                }]
            });
        }
    })
}

function articleVisitType(articleId) {
    //按照访问类别分组统计
    $.ajax({
        type: 'post',
        url: local_host + 'metric/visitType',
        data: {'articleId': articleId},
        cache: false,
        dataType: "json",
        success: function (data) {
            var data = $.map(data, function (n, i) {
                return n;
            });
            var dataStr = JSON.stringify(data);
        	var articlelanguage = $("#articlelanguage").val();
        	if('zh' == articlelanguage){
        		dataStr = dataStr.replace("FULLTEXT", "HTML全文");
    			dataStr = dataStr.replace("META", "摘要");
        	}
			data=JSON.parse(dataStr);
        	var data = $.map(data, function (n, i) {
                return n;
            });
            var typeChart = new Highcharts.chart('article_visit_type_pie', {
            	credits:{enabled: false},
            	chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: 'pie',
                    backgroundColor: 'transparent'
                },
                title: {
                    text: '访问类别分布'
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                            style: {
                                color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                            },
                            connectorColor: 'silver'
                        },
                        showInLegend: true
                    }
                },
                series: [{
                    name: '访问量',
                    colorByPoint: true,
                    data: data
                }]
            });

        }
    });
}

function articleVisitArea(articleId) {
    //按照访问地区分组统计
    $.ajax({
        type: 'post',
        url: local_host + 'metric/visitArea',
        data: {'articleId': articleId},
        cache: false,
        dataType: "json",
        success: function (data) {
            var data = $.map(data, function (n, i) {
                return n;
            });
            console.log(data);
            var areaChart = new Highcharts.chart('article_visit_area_pie', {
            	credits:{enabled: false},
            	chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: 'pie',
                    backgroundColor: 'transparent'
                },
                title: {
                    text: '访问地区分布'
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                            style: {
                                color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                            },
                            connectorColor: 'silver'
                        },
                        showInLegend: true
                    }
                },
                series: [{
                    name: '访问量',
                    colorByPoint: true,
                    data: data
                }]
            });
        }
    });
}

/**
 * ajax增加文章HTML浏览次数
 * @return
 */
var currentState = 0;	//当前页面不刷新只记录一次
function ajaxCountHtmlView(articleId,callback) {
    //获取全文数据
    var contentHtml = cacheObj.get('htmlContent', articleId) || $.ajax({
        url: local_host + 'article/htmlContent?v',
        type: 'post',
        async: false,
        dataType: 'json',
        data: {'id': articleId},
        success: function (data) {
            if (data.access == false) {
            	window.location.href = local_host + 'member/login';
                //alert(data.message);
            } else {
            	var html='<h3 class="navTitle"><span class="sec-title">参考文献</span></h3>'+ $("#References").html(); 
            	if($('#reference:checked').length>0){
            		data.htmlContent && $('#htmlContent').html(data.htmlContent+html);
            	}else{
            		data.htmlContent && $('#htmlContent').html(data.htmlContent);
            	}
                cacheObj.set('htmlContent', articleId, true)
            }
            callback();
        }
    });
    $(".group4").colorbox({rel:'group4',width:'90%',height:"75%",opacity:'0.8',inline:true,
    	onComplete:function(){
    		removeTableBorder();
    		$("#cboxTitle").niceScroll({  
    	        cursorcolor:"transparent",  
    	        cursoropacitymax:1,  
    	        touchbehavior:false,  
    	        cursorwidth:"5px",  
    	        cursorborder:"0",  
    	        cursorborderradius:"5px"  
    	    });
    		//渲染数学公式
    	    MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
		}
    });
    //现在已显示真实表格，不需要生成SVG图
   // createTableSub();
  //重置图表中table是图片的路径
    setTableImg();
   //重置全文中的公式是图片的路径
    resetFormulaSrc();
}

/**
 * 单篇论文查询cnki被引信息
 * @return
 */
function loadCitedByInfo(){
	var id = $("#articleId").val();
	var ajaxArg={
		url: local_host +"article/getArticleCitedBy",
		data: {'articleIds':id},
		returnFun:outCitedByInfo
	};
	ajaxPost(ajaxArg);
}

/**
 * 输出列表中的文章citedBy引证文献信息
 * @param data
 * @param indexArray
 * @return
 */
function outCitedByInfo(data){
	if(typeof(data) != "undefined"){
		//console.log("aaa");
		data = jQuery.parseJSON(data);
		//console.log(data);
		$.each(data,function(i,e){
			if(e.citedCount > 0){
				var journalTitleCn = $("#journalTitleCn").val();
				var journalTitleEn = $("#journalTitleEn").val();
				var journalAbbr = $("#journalAbbr").val();
				$("#citedby-num").html("("+e.citedCount+")");
				$(".citedByCount").html(e.citedCount);
				//var htmltitle = "<h2 style=\"text-align: center;line-height: 30px;font-size: 130%;}\"><b>Cited By</b></h2>";
				var jnum = 0;
				var html = "<table class='cited-content' style='line-height:24px;text-align:left;'>";
				var _tempIndex = 1;
				$.each(e.citedByArticles,function(i,v){
					if(v.articleType == "journal"){
						var _citiationInfo = v.citiation.replace(/\[\d+\]/,"");
						var _aHtml = '';
						if(/.*[\u4e00-\u9fa5]+.*$/.test(_citiationInfo)){ //包含中文
							if(v.journal == journalTitleCn || v.journal == journalTitleEn){ //本刊查看
								try{
									var _hrefVal = local_host+"/article/"+journalAbbr+"/" + v.year + "/" + v.issue + "/" + v.fpage;
									_aHtml = " <a class='cited-location' target='_blank' href='"+_hrefVal+"'><img src='/style/web/images/public/search-cited.png' class='cited-search'/> 本站查看</a>";
								}catch(e){
									_aHtml = " <a class='cited-location' target='_blank' href='http://xueshu.baidu.com/s?wd="+encodeURI(_citiationInfo)+"'><img src='/style/web/images/public/search-cited.png' class='cited-search'/> 百度学术</a>";
								}
							}else{
								_aHtml = " <a class='cited-location' target='_blank' href='http://xueshu.baidu.com/s?wd="+encodeURI(_citiationInfo)+"'><img src='/style/web/images/public/search-cited.png' class='cited-search'/> 百度学术</a>";
							}
						}else{
							_aHtml = " <a class='cited-location' target='_blank' href='https://cn.bing.com/academic/search?q="+encodeURI(_citiationInfo)+"'><img src='/style/web/images/public/search-cited.png' class='cited-search'/> 必应学术</a>";
						}
						var _viewCitiation = _citiationInfo.replace(/\, /g,",").replace(/\,/g,", ").replace("[J].",".").replace(" :",": ");
						html = html + "<tr class=\"citedby-p\"><td class=\"cited-order-num\" valign=\"top\" width=\"20\">" + _tempIndex + ". </td><td class=\"cited-info\" style=\"padding-left:5px;\">"+ _viewCitiation + _aHtml +"<td></tr>";
						jnum ++;
						_tempIndex++;
					}
				})
				html += '</table>';
				var jhtmltitle = "<h3 style=\"line-height:30px;font-size: 110%;\"><b>期刊类型引用("+jnum+")</b></h3>";
				var qtnum = e.citedCount-jnum;
				var qthtmltitle = "<h3 style=\"line-height:30px;font-size: 110%;\"><b>其他类型引用("+qtnum+")</b></h3>";
				$("#citedby-info").html(jhtmltitle+html+qthtmltitle);	
			}
				
		})
	}
}

/**
 * 输出相关文章
 */
function loadRelativeArticles(){
	var id = $("#articleId").val();
	var ajaxArg={
		url: local_host +"article/getRelativeArticles",
		data: {'id':id,
				'language':'cn'},
		returnFun:outRelativeArticles
	};
	ajaxPost(ajaxArg);
}


function outRelativeArticles(data){
	if(typeof(data) != "undefined"){
//		console.log("aaa");
//		var type=$("#journalreferenceCodeType").val();
//		var html='';
//		$.each(data,function(x,y){
//			$.each(y,function(i,e){
//				html+='<table class="reference-tab">';
//				html+='<tr class="document-box">';
//				html+='<td valign="top" class="td1">['+(i+1)+']</td>';
//				html+='<td class="td2">';
//				if(type=='2'){
//					var size=e.authorCnList.length;
//					$.each(e.authorCnList,function(a,b){
//						if(a<size-1){
//							html+=b+', ';
//						}else{
//							html+=b+', ';
//						}
//					})
//					html+=e.year+': ';
//					if(!isNull(e.doi)){
//						html+='<a class="relative-title" target="_blank" href="'+local_host+'/cn/article/doi/'+e.doi+'"  class="mainColor">'+e.titleCn+',</a> '+e.journalTitleCn;
//					}else{
//						html+='<a class="relative-title" target="_blank" href="'+local_host+'/cn/article/id/'+e.id+'"  class="mainColor">'+e.titleCn+',</a> '+e.journalTitleCn;
//					}
//					if(!isNull(e.articleState)){
//						html+='.';
//					}else{
//						html+=', '+e.volume+', '+e.fpage+'-'+e.lpage+'.';
//					}
//				}else{
//					var size=e.authorCnList.length;
//					$.each(e.authorCnList,function(a,b){
//						if(a<size-1){
//							html+=b+', ';
//						}else{
//							html+=b+'. ';
//						}
//					})
//					if(!isNull(e.doi)){
//						html+='<a class="relative-title" target="_blank" href="'+local_host+'/cn/article/doi/'+e.doi+'"  class="mainColor">'+e.titleCn+',</a> '+e.journalTitleCn+'. ';
//					}else{
//						html+='<a class="relative-title" target="_blank" href="'+local_host+'/cn/article/id/'+e.id+'"  class="mainColor">'+e.titleCn+',</a> '+e.journalTitleCn+'. ';
//					}
//					if(isNull(e.articleState)){
//						html+=e.year+', '+e.volume+', '+e.fpage+'-'+e.lpage+'.';
//					}
//					
//						
//				}
//				if(!isNull(e.doi)){
//					html+='<b style="display:inline-block; font-weight:normal;">';
//					html+='doi: <a class="mainColor doi" target="_blank" href="'+local_host+'/cn/article/doi/'+e.doi+'">'+e.doi+'</a></b>';
//				}
//				html+='</td></tr></table>';
//			})
//		})
		$("#relative-article").html(data.list);	
		MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
		
		//2023-5-26 ham
		/*if($("#relative-article").css("display")=="none"){
        	$("#relative-article").show();
		}else{
			$("#relative-article").hide();
		}*/
	}
}