import Moment from "moment";

/* 常用时间处理 */
function dateFormat(val: any, indef = "YYYYMMDDHHmmss", outdef = "MM-DD HH:mm:ss") {
	if (val) {
		return Moment(val, indef).format(outdef);
	}
	else {
		return "";
	}
}

function dateFormatYMDHm(val: any, indef = "YYYYMMDDHHmmss", outdef = "MM-DD HH:mm") {
	if (val) {
		return Moment(val, indef).format(outdef);
	}
	else {
		return "";
	}
}

function dateFormatNoSec(val: any, indef = "YYYY-MM-DD HH:mm:ss", outdef = "YYYY-MM-DD HH:mm") {
	if (val) {
		return Moment(val, indef).format(outdef);
	}
	else {
		return "";
	}
}

/* 常用百分比处理 */
const formatPercent = (data: any) => {
	if (data) {
		return data + "%";
	}
	else {
		return "";
	}
};

/**
 * 添加水印
 * @param str  水印的内容
 * @param parentNode  父节点
 * @param font 水印文字大小
 * @param textColor 水印颜色
 * @param rowLength 一个水印的宽度是多少
 * @param colLength 一个水印的长度是多少
 */


function addWaterMarker(str: string, parentNode: HTMLDivElement, font: string, textColor: string, rowLength: number, colLength: number) {// 水印文字，父元素，字体，文字颜色

	let can = document.createElement('canvas');
	parentNode.appendChild(can);
	can.width = parentNode.offsetWidth;
	can.height = parentNode.offsetHeight;
	can.style.display = 'none';
	let cans = can.getContext('2d');
	cans?.rotate(-10 * Math.PI / 180);
	cans!.font = font || "16px Microsoft JhengHei";
	cans!.fillStyle = textColor || "rgba(180, 180, 180, 0.3)";
	cans!.textAlign = 'left';
	cans!.textBaseline = 'middle';
	// 需要遍历添加文字
	for (let row = 0; row < can.height / rowLength; row++) {
		for (let col = 0; col < can.width / colLength; col++) {
			cans?.fillText(str, col * colLength, row * rowLength);
		}
	}
	// 在节点中添加内容
	parentNode.style.backgroundImage = "url(" + can.toDataURL("image/png") + ")";
}

function stringIsNullOrEmpty(content: string | undefined) {
	return content === null || content === undefined || content === '' || content.length === 0;
}

function objectIsNullOrEmpty(data: any) {
	return data === null || Object.keys(data).length === 0;
}

/**
 * 获取两个日期型字符串时间差(秒)YYYYMMDDHHmmss
 * @param date1 
 * @param date2 
 * @returns 
 */
function getTimeInterva(date1: string, date2: string) {
	if (date1 && date2) {
		let dt1 = Moment(date1, 'YYYYMMDDHHmmss').toDate();
		let dt2 = Moment(date2, 'YYYYMMDDHHmmss').toDate();
		let cz = dt2.getTime() - dt1.getTime();
		return cz / 1000;
	} else {
		return -1;
	}
}

/**
 * 设备工作情况的值格式化(10 s)
 * @param val
 * @param start 
 * @returns 
 */
function getValueFormat(val:any,start:string){
	if(val){
		return val+' '+start;
	}else{
		return '-'
	}
}

export default {
	dateFormat,
	formatPercent,
	addWaterMarker,
	dateFormatYMDHm,
	stringIsNullOrEmpty,
	objectIsNullOrEmpty,
	dateFormatNoSec,
	getTimeInterva,
	getValueFormat
}