/*
 * @Descripttion: 工具集
 * @version: 1.1
 * @LastEditors: sakuya
 * @LastEditTime: 2021年7月20日10:58:41
 */

const tool = {}

/* localStorage */
tool.data = {
	set(table, settings) {
		var _set = JSON.stringify(settings)
		return localStorage.setItem(table, _set);
	},
	get(table) {
		var data = localStorage.getItem(table);
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data;
	},
	remove(table) {
		return localStorage.removeItem(table);
	},
	clear() {
		return localStorage.clear();
	}
}

/*sessionStorage*/
tool.session = {
	set(table, settings) {
		var _set = JSON.stringify(settings)
		return sessionStorage.setItem(table, _set);
	},
	get(table) {
		var data = sessionStorage.getItem(table);
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data;
	},
	remove(table) {
		return sessionStorage.removeItem(table);
	},
	clear() {
		return sessionStorage.clear();
	}
}

/* Fullscreen */
tool.screen = function (element) {
	var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
	if(isFull){
		if(document.exitFullscreen) {
			document.exitFullscreen();
		}else if (document.msExitFullscreen) {
			document.msExitFullscreen();
		}else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		}else if (document.webkitExitFullscreen) {
			document.webkitExitFullscreen();
		}
	}else{
		if(element.requestFullscreen) {
			element.requestFullscreen();
		}else if(element.msRequestFullscreen) {
			element.msRequestFullscreen();
		}else if(element.mozRequestFullScreen) {
			element.mozRequestFullScreen();
		}else if(element.webkitRequestFullscreen) {
			element.webkitRequestFullscreen();
		}
	}
}

/* 复制对象 */
tool.objCopy = function (obj) {
	return JSON.parse(JSON.stringify(obj));
}

/* 日期格式化 */
tool.dateFormat = function (date, fmt='yyyy-MM-dd hh:mm:ss') {
	date = new Date(date)
	var o = {
		"M+" : date.getMonth()+1,                 //月份
		"d+" : date.getDate(),                    //日
		"h+" : date.getHours(),                   //小时
		"m+" : date.getMinutes(),                 //分
		"s+" : date.getSeconds(),                 //秒
		"q+" : Math.floor((date.getMonth()+3)/3), //季度
		"S"  : date.getMilliseconds()             //毫秒
	};
	if(/(y+)/.test(fmt)) {
		fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	for(var k in o) {
		if(new RegExp("("+ k +")").test(fmt)){
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
		}
	}
	return fmt;
}

/* 千分符 */
tool.groupSeparator = function (num) {
	num = num + '';
	if(!num.includes('.')){
		num += '.'
	}
	return num.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
		return $1 + ',';
	}).replace(/\.$/, '');
}

//十六进制颜色值转换为RGB(A)颜色值
tool.hexToRgb  = function (val, flag) {
    // 16进制颜色值的正则
	var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
	// 把颜色值变成小写
	var color = val.toLowerCase();
	var result = '';
	if (reg.test(color)) {
		// 如果只有三位的值，需变成六位，如：#fff => #ffffff
		if (color.length === 4) {
			var colorNew = "#";
			for (var i = 1; i < 4; i += 1) {
				colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
			}
			color = colorNew;
		}
		// 处理六位的颜色值，转为RGB
		var colorChange = [];
		for (var j = 1; j < 7; j += 2) {
			colorChange.push(parseInt("0x" + color.slice(j, j + 2)));
		}
		result = "rgb(" + colorChange.join(",") + ")";
		return { RGB: result, R: colorChange[0], G: colorChange[1], B: colorChange[2], A: 255 };//a表示透明度
	} else {
		if (flag) {
			return  {
				A: 0,
				R: 255,
				G: 255,
				B: 255
			};
		}
		else {
			return  {
				A: 255,
				R: 0,
				G: 0,
				B: 0
			};
		}
	}
}

tool.rgbaToHex = function (val) {
	var newVal = 'rgb(' + val.R + ',' + val.G + ',' + val.B + ',' + val.A + ')';
	return tool.rgbToHex(newVal);
}

//RGB(A)颜色转换为十六进制的颜色值
//调用rgbToHex('rgb(235,241,221,1)')
tool.rgbToHex = function (val) {
	var r, g, b, a;
	var regRgba = /rgba?\((\d{1,3}),(\d{1,3}),(\d{1,3})(,([.\d]+))?\)/;
	// //判断rgb颜色值格式的正则表达式，如rgba(255,20,10,.54)
	 var rsa = val.replace(/\s+/g, '').match(regRgba);
	if (rsa) {
		r = parseInt(rsa[1]).toString(16);
		r = r.length == 1 ? '0' + r : r;
		g = (+rsa[2]).toString(16);
		g = g.length == 1 ? '0' + g : g;
		b = (+rsa[3]).toString(16);
		b = b.length == 1 ? '0' + b : b;
		a = (+(rsa[5] ? rsa[5] : 1)) * 100;
		return { hex: '#' + r + g + b, r: parseInt(r, 16), g: parseInt(g, 16), b: parseInt(b, 16), alpha: Math.ceil(a) };
	} else {
		return { hex: "" };
	}
}

//毫米转pt
tool.mmToPt = function (value) {
	if (!value) {
		return 0.0;
	}
	var val = Number(parseFloat(value) * 5 / 1.76).toFixed(2);
	return parseFloat(val);
}

//pt转毫米
tool.ptToMM = function (value) {
	if (!value) {
		return 0.0;
	}
    var val = Number(parseFloat(value) * 1.76 / 5).toFixed(2);
	return parseFloat(val);
}

//pix转pt
tool.pxToPt = function (value) {
	if (!value) {
		return 0.0;
	}
	var val = Number(parseFloat(value) * 3 / 4).toFixed(2);
	return parseFloat(val);
}

//pt转pix
tool.ptToPx = function (value) {
	if (!value) {
		return 0.0;
	}
    var val = Number(parseFloat(value) * 4 / 3).toFixed(2);
	return parseFloat(val);
}

//毫米转pix
tool.mmToPx = function (value) {
	if (!value) {
		return 0.0;
	}
	var tempValue = tool.mmToPt(value)
	var val = parseFloat(tool.ptToPx(tempValue))
	return val;
}

//pix转mm
tool.pxToMM = function (value) {
	if (!value) {
		return 0.0;
	}
    var tempValue = tool.pxToPt(value)
	var val = parseFloat(tool.ptToMM(tempValue))
	return val;
}

//获取总长度
tool.getCharCount = function (strTemp) {
	var count = 0;
	var length = 0;
	for (var i = 0; i < strTemp.split('').length; i++) {
		if (strTemp[i] === ' ' || strTemp[i] === '　') {
			count = 1;
		}
		else {
			length += tool.checkCharLength(strTemp[i]);
		}
	}
	length += count;
	return length;
}

//验证中英文,可以是字符，也可以是字符串
tool.checkCharLength = function (text) {
	let length = 0;
	let surLength = text.length;
	let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g;
	let mat = text.match(cnReg);
	if (mat) {
		length += mat.length;
		surLength = surLength - mat.length
	}
	let regs = /[A-Z]/g;
	let matD = text.match(regs);
	if (matD) {
		length += matD.length * 0.75;
		surLength = surLength - matD.length;
	}
	length += surLength * 0.55;
	return length;
}

tool.readFile = function (filePath) {
	let xhr = new XMLHttpRequest();
	xhr.open('GET', filePath, false);
	xhr.overrideMimeType('text/html;charset=utf-8');
	xhr.send(null);
	//var result = xhr.responseText.replace(/\s*/g,"");
	var result = xhr.responseText;
	return result;
}

tool.splitSemicolon = function (str, c) {
	var arr = str.split(c);
	var list = []
	if (arr && arr.length > 0) {
		arr.forEach(d => {
			if (d && d.length > 0) {
				list.push(d);
			}
		});
	}
	return list;
}


tool.selfBase64 =   {

    encode(input) {
		var _keyStr = "0123456789+/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=";
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = this._utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    },

     decode(input) {
		if(input==''||input==undefined)
		{
			return '';
		}
		var _keyStr = "0123456789+/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=";
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
		// eslint-disable-next-line no-useless-escape
		input = input.replace(/[^a-zA-Z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output =this._utf8_decode(output);
        return output;
    },

     _utf8_encode(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c <2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },

    // private method for UTF-8 decoding
     _utf8_decode(utftext) {
        var string = "";
        var i = 0;
        var c = 0;
        var c1 = 0;
        var c2 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c1 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
                i += 2;
            } else {
                c1 = utftext.charCodeAt(i + 1);
                c2 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
                i += 3;
            }
        }
        return string;
    }
}


export default tool
