

var Tools = function(){
	/**
	  * 计时组件封装
	  * @param: {Object}
	  *	@example1: var timerA = new Tools.timerLoop(3000, 'timerA');
				timerA(function(){});
				timerA.stop();
				timerA.start();
				timerA.setTime();
				timerA.clear();
	  * @return: 
	  * @author: Kimber
	  * @createtime: 2021/10/28
	  */
	var timerLoop = function(timer, name){
		var defaultTiem = 5000;
		var Cache = {timer:timer || defaultTiem, name:name};
		var layer = function(timer){
			Cache.timer = timer;
			Cache.layer = this;
			this.start = () => {
				clearTimeout(Cache.timerPointer);
				Cache.timerPointer = setInterval(Cache.fn.bind(this), Cache.timer);
			};
			var interval = function(fn, timer, name){
				if(typeof fn === 'function'){
					Cache.name = name;
					timer && (Cache.timer = timer);
					Cache.fn = fn;
					Cache.layer.start()
				};
			};
			interval.__proto__ = this.__proto__;
			return interval
		}; layer.prototype = {
			stop: function(){
				clearInterval(Cache.timerPointer);
			},
			start: function(){
				Cache.fn && Cache.layer.start()
			},
			setTime: function(timer){
				timer && (Cache.timer = timer);
				Cache.fn && Cache.layer.start()
			},
			clear: function(){
				clearInterval(Cache.timerPointer);
				Cache = {timer:defaultTiem};
			},
		};
		return new layer(timer)
	};

	// 日期时间工具
	var Dates = function(){
		/* 
			Dates.format('yyyy-MM-dd EE HH:mm:ss')
			Dates.format.call(new Date(), 'yyyy-MM-dd EE HH:mm:ss')
		*/
		var format = function(fmt){
			var Date_ = this.getDate ? this : new Date();
			var o = {           
			"M+" : Date_.getMonth()+1, //月份           
			"d+" : Date_.getDate(), //日           
			"h+" : Date_.getHours()%12 == 0 ? 12 : Date_.getHours()%12, //小时           
			"H+" : Date_.getHours(), //小时           
			"m+" : Date_.getMinutes(), //分           
			"s+" : Date_.getSeconds(), //秒           
			"q+" : Math.floor((Date_.getMonth()+3)/3), //季度           
			"S" : Date_.getMilliseconds() //毫秒           
			};           
			var week = {           
			"0" : "\u65e5",           
			"1" : "\u4e00",           
			"2" : "\u4e8c",           
			"3" : "\u4e09",           
			"4" : "\u56db",           
			"5" : "\u4e94",           
			"6" : "\u516d"          
			};           
			if(/(y+)/.test(fmt)){           
				fmt=fmt.replace(RegExp.$1, (Date_.getFullYear()+"").substr(4 - RegExp.$1.length));           
			}           
			if(/(E+)/.test(fmt)){           
				fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[Date_.getDay()+""]);           
			}           
			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;
		}
		
		var getDayStamp = function(){
			var start = new Date(new Date().toLocaleDateString()).getTime() / 1000;
			var end = ~~(new Date().getTime() / 1000);
			return {start:start, end:end};
		}

		return {format:format, getDayStamp:getDayStamp,}
	};

	
	// 利用 canvas 将 File 的 blob stream 转为 base64
	var canvasTobase64 = function(img, w, h){
		// canvas
		var canvas = document.createElement('canvas');
		canvas.width = w;
		canvas.height = h;
		var ctx = canvas.getContext('2d');
		ctx.fillStyle = 'transparent';
		ctx.fillRect(0, 0, w, h);
		ctx.drawImage(img, 0, 0, w, h);
		// 生成结果
		var results = {};
		results.base64 = canvas.toDataURL('image/jpeg', 0.7);
		results.base64Len = results.base64.length;
		canvas = null;		// 释放内存
		return results;
	};
	var blobStreamToBase64 = function(blob, fn){
		var img = new Image();
		img.src = blob;
		img.crossOrigin = "*";
		img.onerror = function() {
			var error = new Error('图片加载失败');
		};
		img.onload = function(){
			var w = img.width, h = img.height;
			var verify = fn(img);
			if(verify || verify === void 0){
				return fn(canvasTobase64(img, w, h), img = null) ;
			};

			// 重设比例
			//that.setCoordRatio();
		}
	};

	// 选择列表事件绑定
	var selectEventBind = function(dom, fn){
		dom.onchange = function(e){
			var tag = e.target || e.srcElement;
			var option = tag.selectedOptions[0];
			fn && fn(option.value, option);
		};
	};
	// 创建选择列表
	var createSelect = function(dom, arr){
		var len = arr.length, optionText = '';
		for(var i=0; i<len; i++){
			var item = arr[i];
			if(typeof item === 'string'){
				optionText += '<option value="'+item+'" data-index="'+i+'">'+item+'</option>';
			};
		};
		return dom.innerHTML = optionText, dom;
	};

	/**
	  * 异步遍历
	  * @param: {Object || Array} param
	  * @param: {Function} fn
	  *	@example1: var selectList = this.Dict.selectList;
					Tools.asyncLoop.call(this, selectList, function(key, value, next){
						if(typeof value === 'function'){
							value().then(function(res){
								selectList[key] = res;
								next();
							})
						}else{
							next();
						};
					}, function(){});
	  *	@example1: Tools.asyncLoop.call(this, [{name:'123'}, {name:'234'}], function(key, value, next){
						var reqItem = value;
						reqApi.getItem(reqItem.param).then((res) => {
							if(res && res.stat){
								next();
							};
						});
					}, function(){});
	  * @author: Kimber
	  * @updatetime: 2021/12/10(周五)
	  * @createtime: 2021/12/10(周五)
	  */
	var asyncLoop = function(param, fn, end){
		var list = typeof param === 'object' ? Object.keys(param) : param || [], len = list.length;
		!function loop(i){
			(i < len) ? (()=>{
				var key = list[i];
				var item = param[key];
				fn && fn.call(this,key, item, ()=>{
					loop.call(this, ++i);
				});
			})() : (()=>{end&&end.call(this)})();
		}.bind(this)(0);
	};
	
	/**
	  * 计时组件封装
	  * @param: {Object}
	  *	@example1: Tools.loopTimeout(3000, function(next){next()});
	  * @return: 
	  * @author: Kimber
	  * @createtime: 2022/1/20
	  */
	var loopTimeout = function(timer, fn){
		timer = timer || 3000;
		(function loop(){
			setTimeout(() => {
				fn && fn(loop)
			}, timer);
		})();
	};

	return {
		timerLoop:timerLoop, Dates:Dates(), blobStreamToBase64:blobStreamToBase64,
		SelectEventBind:selectEventBind, CreateSelect:createSelect,
		asyncLoop:asyncLoop, loopTimeout:loopTimeout,
	}
};


/**
  * 文件下载
  * @return: Object
  * @author: Kimber
  * @updatetime: 2021/7/20
  * @createtime: 2021/7/20
  */
var FileStream = function(){
	function s2ab(s) {
		var buf = new ArrayBuffer(s.length);
		var view = new Uint8Array(buf);
		for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
		return buf;
	};

	/**
	  * 字符转换 Blob 对象
	  * @param: {String} str 
	  * @example1: var aaa = FileStream.toBlob(str);
	  * @return: 
	  * @author: Kimber
	  * @updatetime: 2021/7/20
	  * @createtime: 2021/7/20
	  */
	var toBlob = function(str){
		return new Blob([s2ab(str)], {
			type: "application/octet-stream"
		});
	};
	
	/**
	  * 利用 A标签 下载文件
	  * @param: {Blob} url 
	  * @param: {String} saveName	// 文件名
	  * @example1: FileStream.download(blob, 'Test.xlsx');
	  * @return: 
	  * @author: Kimber
	  * @updatetime: 2021/7/20
	  * @createtime: 2021/7/20
	  */
	var download = function(url, saveName){
		if (typeof url == 'object' && url instanceof Blob) {
			url = URL.createObjectURL(url); // 创建blob地址
		}
		var aLink = document.createElement('a');
		aLink.href = url;
		aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
		var event;
		if (window.MouseEvent) event = new MouseEvent('click');
		else {
			event = document.createEvent('MouseEvents');
			event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
		}
		aLink.dispatchEvent(event);
	};

	return {toBlob:toBlob, download:download}
};

export var Tools = Tools();
export var FileStream = FileStream();


/* exports = {
	HttpReq: HttpReq(),
	Dates: Dates(),
	Tools: Tools(),
}; */
