//触摸或点击添加类名，
//参数1为需要添加类名的li标签的类名，参数类型为字符串
//参数2为动态添加的类名，参数类型为字符串
//参数3为切换的类型
function increaseClass(name,selectedClassName,switchType) {
	$('.'+name).each(function () {
		if (switchType == "click") {
			$(this).click(function () {
				$(this).siblings().removeClass(selectedClassName);
				$(this).addClass(selectedClassName);
			})
		} 
		if (switchType == "mouseenter") {
			$(this).mouseenter(function () {
				$(this).siblings().removeClass(selectedClassName);
				$(this).addClass(selectedClassName);
			})
		} 
	})
}

//通过子元素为父元素添加类名,实现开合栏目列表
function increaseParentClass(name,focusName) {
	$('.'+name).each(function () {
		$(this).click(function () {
			var currentType = $(this).parent().attr("class").includes(focusName);
			if (currentType) {
				$(this).parent().removeClass(focusName);
				$(this).siblings(".sub_list").slideToggle(300);
			} else {
				$(this).parent().addClass(focusName)
				$(this).siblings(".sub_list").slideToggle(300);
			}
		})
	})
}

//对已选中的元素再次增减类名
function switchSortType(name,selectedClassName,typeSecond,typeThird) {
	$('.'+name).each(function () {
		$(this).click(function () {
			var selectType = $(this).attr("class").includes(selectedClassName);
			var sortType = $(this).attr("class").includes(typeSecond);
			if (selectType) {
				if (sortType) {
					$(this).removeClass(typeSecond);
					$(this).addClass(typeThird);
				} else {
					$(this).removeClass(typeThird);
					$(this).addClass(typeSecond);
				}
			} else {
				$("." + selectedClassName).removeClass(selectedClassName);
				$("." + typeSecond).removeClass(typeSecond);
				$(name).addClass(typeThird);
				$(this).addClass(selectedClassName);
			}
		})
	})
}

//替换子栏目文章的more图标,参数为要替换的内容，参数类型为字符串
function replaceMoreText(con) {
	var more = document.getElementsByClassName('moretext')
	for (const i of more) {
		i.innerHTML = con;
	}
}
//替换tab切换的more图标,参数为要替换的内容，参数类型为字符串
function replaceTabMore(con) {
	var more = $('.post33 .moretext');
	more.find('img').remove();
	more.each(function(){
		$(this).text(con);
	})
}
/*获取元素到页面顶部的距离 */
function getElementToPageTop(el) {
	//参数为需要获取到页面顶部高度的html元素
	if(el.offsetParent) {
		return getElementToPageTop(el.offsetParent) + el.offsetTop
	}
	return el.offsetTop
}
/*根据滚动条高度设置类名 */
// 第一个参数为操作的节点的类名，第二个参数为增减的类名,第三个为获取高度的元素，参数类型为字符
function setNameByHeight(operateName,dynamicName,heightName) {
	var windowNode = document.getElementsByClassName(operateName)[0];
	var heightNode = document.getElementsByClassName(heightName)[0];
	var elHeight = getElementToPageTop(heightNode);
	window.onscroll = function () {  //鼠标滚轮滚动时调用方法
		//获取滚动条到页面顶部的高度
		var st = document.documentElement.scrollTop || document.body.scrollTop;
		//判断高度,添加或移除类名
		if (st > elHeight) {
			windowNode.classList.add(dynamicName)
		} else {
			windowNode.classList.remove(dynamicName)
		}
	}
}

//锚点平滑过渡
function smooth(operateName){
	$('.' + operateName).click(function () {
		$("html,body").animate(
			{ scrollTop: $($(this).attr("href")).offset().top },
			{ duration: 500, easing: "swing" });
		return false;
	});
}
// iframe宽高自适应
function adjustIframe(){
	var ifm= document.getElementById("bi_iframe");
	ifm.height=document.documentElement.clientHeight;
	ifm.width=document.documentElement.clientWidth;
}
//单篇文档预览
function docPreview(){
	if($('.entry').find('a').length == 1){
		var url = $('.entry').find('a').attr('href');
		var html = `<iframe id="bi_iframe" frameborder="0" scrolling="auto" onload="adjustIframe()" src="${url}#toolbar=0"></iframe>`;
		$('.entry').prepend(html);
		$('#bi_iframe').css('width','100%');
	}
}
//冒泡排序算法
//交换函数
function swap(arr, i, j) {
	var temp = arr[j]
	arr[j] = arr[i]
	arr[i] = temp
}

//冒泡排序
function bubbleSort(arr, key) {
	var len = arr.length,
		time = 0  //交换次数
	for (let i = 0; i < len; i++) {
		var flagSort = false //是否进行交换
		console.log("这是第" + i + "趟");
		
		for (let j = 0; j < len - i; j++) {
			console.log(arr[j]);
			console.log(arr[j][key]);
			if (parseInt(arr[j][key]) > parseInt(arr[j + 1][key])) {
				flagSort = true
				time++
				swap(arr, j, j + 1)
			}
		}

		console.log('交换次数：', time)
		
		if (!flagSort) {
			return arr
		}
	}
	return arr
}
//图片懒加载
function interOberver() {
	const ob = new IntersectionObserver((entries) => {
		for (const entry of entries) {
			if (entry.isIntersecting) {
				const img = entry.target;
				if(img.dataset.src){
					img.src = img.dataset.src;
				}
				ob.unobserve(img); //取消监听
			}
		}
	}, {
		root: null, //与其交叉的元素 null表示与视口交叉
		rootMargin: '0px', //对交叉范围进行收缩或扩张
		threshold:0, //交叉的阈值 0为接触即触发回调 1为完全交叉时触发回调
	})

	const imgs = document.querySelectorAll('img[data-src]');
	imgs.forEach(img => {
		ob.observe(img);
	})
}
function interOberverAos(div){
	const ob = new IntersectionObserver((entries) => {
		for (const entry of entries) {
			if (entry.isIntersecting) {
				div.classList.add('showDiv');
				// ob.unobserve(div); //取消监听
			} else{
				div.classList.remove('showDiv');
			}
		}
	}, {
		root: null, //与其交叉的元素 null表示与视口交叉
		rootMargin: '0px', //对交叉范围进行收缩或扩张
		threshold:0.15, //交叉的阈值 0为接触即触发回调 1为完全交叉时触发回调
	})
	ob.observe(div);
}
//使用消息通道实现深拷贝
async function deepCopy(obj) {
	const e = await new Promise((resolve) => {
		const { port1, port2 } = new MessageChannel();
		port1.postMessage(obj);
		port2.onmessage = (msg) => {
			resolve(msg.data);
		};
	});
	var newData = e;
	console.log(newData);
}
//函数节流
function throttle(fn,delay=500){
	let timer = null;
    return function(){
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(()=>{
            fn.apply(this,arguments);
            timer = null;
        },delay);
    }
}
//函数防抖
function debounce(fn, delay = 500) {
	// timer 是在闭包中的
	let timer = null;

	return function () {
		if (timer) {
			clearTimeout(timer)
		}
		timer = setTimeout(() => {
			fn.apply(this, arguments)
			timer = null
		}, delay)
	}
}
//滚动条自动滚动，触摸停止
function autoScroll(name) {
	window.timer2 = setInterval(() => {
		$(name)[0].scrollBy(0, 1);
	}, 30);

	$(name).mouseenter(function () {
		clearTimeout(timer2)
	})
	$(name).mouseleave(function () {
		window.timer2 = setInterval(() => {
			$(name)[0].scrollBy(0, 1);
		}, 30);
	})
}
//滚动条滚动到底部自动返回顶部
function autoTotop(name){
	$(name).scroll(function () {
		var scrollTop = $(this).scrollTop(); //滚动条滚动距离
		var scrollHeight = $(this).height(); //当前元素可视高度
		var sumHeight = $(this).prop('scrollHeight'); //当前元素总高度
		if (scrollTop + scrollHeight == sumHeight) {
			$(this).scrollTop(0);
		}
	});
}
//年月日转星期
function weekNum(name) {
	let datelist = ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'];
	$(name).each(function(){
		var now = datelist[new Date($(this).text()).getDay()]
		$(this).text(now);
	})
}
// 月份转汉字
function monthNum(name){
	let list1 = ['01','02','03','04','05','06','07','08','09','10','11','12'];
	let list2 = ['一','二','三','四','五','六','七','八','九','十','十一','十二'];
	$(name).each(function(){
		for (let index = 0; index < 12; index++) {
			if($(this).text() == list1[index]){
				$(this).text(list2[index]);
				break;
			}
		}
	})
}
// 月份转英文
function monthEn(name){
	let list1 = ['01','02','03','04','05','06','07','08','09','10','11','12'];
	let list2 = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
	$(name).each(function(){
		for (let index = 0; index < 12; index++) {
			if($(this).text() == list1[index]){
				$(this).text(list2[index]);
				break;
			}
		}
	})
}
//tab切换
// function select(a) {
// 	var titleList = document.getElementsByClassName('title-item');
// 	var cardList = document.getElementsByClassName('con-item');
// 	var moreList = document.getElementsByClassName('more-item');
// 	for (let index = 0; index < titleList.length; index++) {
// 		titleList[index].classList.remove('selected');
// 		cardList[index].classList.remove('selected');
// 		moreList[index].classList.remove('selected');
// 	}
// 	titleList[a].classList.add('selected');
// 	cardList[a].classList.add('selected');
// 	moreList[a].classList.add('selected');
// }
function myTab(parent){
	$(parent).find('.title-item').each(function(e){
		$(this).mouseenter(function(){
			$(this).siblings().removeClass('selected');
			$(this).addClass('selected');

			$(parent).find('.con-item').removeClass('selected');
			$(parent).find('.more-item').removeClass('selected');

			$(parent).find('.con-item').eq(e).addClass('selected');
			$(parent).find('.more-item').eq(e).addClass('selected');
		})
	})
}
// 导航栏选中当前栏目
function linkOn(){
	var link = $(".header li");
    var links = $(".header li a");
    link.each(function() {
        $(this).click(function() {
            $(this).addClass('on');
            $(this).siblings().removeClass('on');
            //防止页面跳转
        });
    });
    //当前页或者跳转后页面的导航栏添加选中后样式
    $(".header li a").each(function() {
        $this = $(this);
        if ($this[0].href == String(window.location)) { //String 对象用于处理文本（字符串）
            $this.parent().addClass("on");
        }

    });
}
// 日期选择框时间切割
function cutTime(name){
	var str_time = $(this).find(name)[0].innerText;
	var finalist = [];
	var list1 = str_time.split('-');
	for(let i of list1){
		var list2 = i.split(' ');
		var finalist = [...finalist,...list2];
	}
	return finalist;
}
//获得鼠标移入移出的方向
//返回参数为一个数组，第一项表示鼠标进入还是离开，第二项表示移动的方向
function getDirection(name){
	$(name).on("mouseenter mouseleave", function (e) {
		var w = $(this).width(); // 得到盒子宽度
		var h = $(this).height();// 得到盒子高度
		var x = (e.pageX - this.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1);
		// 获取x值
		var y = (e.pageY - this.offsetTop - (h / 2)) * (h > w ? (w / h) : 1);
		// 获取y值
		var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
		//direction的值为“0,1,2,3”分别对应着“上，右，下，左”
		// 将点的坐标对应的弧度值换算成角度度数值
		var dirName = new Array('上方', '右侧', '下方', '左侧');
		var mousetype;
		var list = [];
		if (e.type == 'mouseenter') {
			// console.log(dirName[direction] + '进入');
			mousetype = 0;
			return list[mousetype,direction];
		} else {
			// console.log(dirName[direction] + '离开');
			mousetype = 1;
			return list[mousetype,direction];
		}
	});
}

$(function () {
})