import moment from 'moment';
import tool from '@/utils/tool';

let Time = {
	getFormateTime: function (date) {
		let timestamp = date.includes("T") && date.includes("Z") && moment(date, "YYYY-MM-DDTHH:mm:ss[Z]").valueOf() || moment(date).valueOf();
		let now = moment().valueOf();
		let today = moment().startOf('day').valueOf();

		let timer = (now - timestamp) / 1000;
		let tip = '';

		if (timer <= 0) {
			tip = '刚刚';
		} else if (Math.floor(timer / 60) <= 0) {
			tip = '刚刚';
		} else if (timer < 3600) {
			tip = Math.floor(timer / 60) + '分钟前';
		} else if (timer >= 3600 && (timestamp - today >= 0)) {
			tip = Math.floor(timer / 3600) + '小时前';
		} else if (timer / 86400 <= 31) {
			tip = Math.ceil(timer / 86400) + '天前';
		} else {
			tip = tool.dateFormat(date, "YYYY-MM-DD");
		}
		return tip;
	}
}

export default (el, binding) => {
	let { value, modifiers } = binding
	if (!value) {
		return false
	}

	if (modifiers.tip) {
		el.innerHTML = Time.getFormateTime(value)
		el.__timeout__ = setInterval(() => {
			el.innerHTML = Time.getFormateTime(value)
		}, 60000)
	} else {
		const format = el.getAttribute('format') || undefined
		el.innerHTML = tool.dateFormat(value, format)
	}
}
