/**
 *  공통 유틸용 JS
 *  2022.05.25
 *  @author 문다운
 */

(function($) {
	$.utils = {
		// 공백값 체크
		isBlank: function(v) {
			return (v == null || v == undefined || v == '' || (typeof v == 'string' && v.trim() == ''));
		},
		// 공백값 체크
		isNotBlank: function(v) {
			return !(this.isBlank(v));
		},
		isEmpty: function (v) {
			if(v == null || v == undefined || v == '' || (typeof v == 'string' && v.trim() == '')) {
				return "";
			} else {
				return v;
			}

		},
		// DataTable 관련 유틸
		dataTable: {
			url: '',
			opts: {},
			// 초기값 세팅
			init: function(url, opts) {
				this.url = url;
				this.opts = opts;
			},
			// 리스트 데이터 조회
			getListData: function(data, callback) {
				var _this = this;
				$.ajax({
					url: _this.url,
					type: 'POST',
					data: data,
					success: callback
				});
			},
		},
		info: function(v) {
			swal(v, {
				icon: "info",
				buttons: "확인"
			});
		},
		success: function(v) {
			swal(v, {
				icon: "success",
				buttons: "확인"
			});
		},
		warning: function(v) {
			swal(v, {
				icon: "warning",
				buttons: "확인"
			});
		},
		error: function(v) {
			swal(v, {
				icon: "error",
				buttons: "확인"
			});
		},
		confirm: function(v, callback) {
			swal(v, {
				icon: "info",
				buttons: ["취소", "확인"]
			}).then(function(ok) {
				if (ok) {
					callback()
				}
			});
		},
		confirmElse: function(v, callback, fail) {
			swal(v, {
				icon: "info",
				buttons: ["취소", "확인"]
			}).then(function(ok) {
				if (ok) {
					callback()
				} else {
					fail();
				}
			});
		},
		successAnd: function(v, callback) {
			swal(v, {
				icon: "success",
				buttons: "확인"
			}).then(function(ok) {
				if (ok) {
					callback()
				}
			});
		},
		successAndElse: function(v, callback, fail) {
			swal(v, {
				icon: "success",
				buttons: "확인"
			}).then(function(ok) {
				if (ok) {
					callback()
				} else {
					fail();
				}
			});
		},
		zeroPad: function(v) {
			try {
				v = (typeof v == 'string' ? Number(v) : (typeof v == 'number' ? v : null));
				if(this.isBlank(v)) return false;
				return v < 10 ? '0' + v : v;
			} catch(e) {
				console.debug('숫자(문자형 포함)만 입력 가능합니다.')
				return false;
			}
		},
		addComma: function(v) {
			return v.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",")
		},

		sliceDateTimeFormat: function(v) {
			let sDateTime = v.slice();
			let year = sDateTime[0];
			let month = sDateTime[1];
			let day = sDateTime[2];
			let hour = sDateTime[3];
			let min = sDateTime[4];
			let second = sDateTime[5];

			if (parseInt(month) < 10)
				month = "0" + month;
			if (parseInt(day) < 10)
				day = "0" + day;
			if (parseInt(hour) < 10)
				hour = "0" + hour;
			if (parseInt(min) < 10)
				min = "0" + min;
			if (parseInt(second) < 10)
				second = "0" + second;
			if (second == undefined) { second = "00"; }

			return String(year) + "-" + String(month) + "-" +  String(day) + " " +  String(hour) + ":" +  String(min) + ":" +String(second);
		},

		// falg 값을 입력 받아 현재 날짜를 리턴
		// ex)	1. flag "", -> YYYYMMDD
		//		2. flag "/" -> YYYY/MM/DD
		getDateNow: function(flag) {
			let today = new Date();
			let year = today.getFullYear();
			let month = (today.getMonth() + 1);
			let day = today.getDate();

			if (parseInt(month) < 10)
				month = "0" + month;
			if (parseInt(day) < 10)
				day = "0" + day;

			return String(year) + flag + String(month) + flag + String(day);
		},

		// falgs 배열로 입력 받아 현재 날짜를 리턴
		// ex)	1. flags ["-", "-", " ", ":", ":"], -> YYYY-MM-DD HH:mm:ss
		// 배열 값이 없을 경우 아래는 공백으로 대체
		getDateTimeNow: function (flags) {
			let today = new Date();
			let year = today.getFullYear();
			let month = (today.getMonth() + 1);
			let day = today.getDate();
			let hour = today.getHours();
			let min = today.getMinutes();
			let second = today.getSeconds();

			for (let i=flags.length; i < 5; i++) {
				flags.push("");
			}

			if (parseInt(month) < 10)
				month = "0" + month;
			if (parseInt(day) < 10)
				day = "0" + day;
			if (parseInt(hour) < 10)
				hour = "0" + hour;
			if (parseInt(min) < 10)
				min = "0" + min;
			if (parseInt(second) < 10)
				second = "0" + second;

			return String(year) + flags[0] + String(month) + flags[1] + String(day) + flags[2] + String(hour) + flags[3] + String(min) + flags[4] + String(second);
		},

		fillZero : function(width, str) {
			return str.length >= width ? str:new Array(width-str.length+1).join('0')+str;
		},

		scenarioVersionString : function(version) {
			let result;
			if (typeof version != 'number') {
				result = "version is not number"
				// console.log(result);
				return result;
			}

			//if (version == 0) { return ""; }

			result = "V" + this.fillZero(3, version.toString());
			return result
		},

		getStringToChecksum : function (contents) {
			let hash = CryptoJS.MD5(contents);
			return CryptoJS.enc.Base64.stringify(hash); // hash 값을 base64 인코딩
		},
		getUUID : function () {
			return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16));
			// return self.crypto.randomUUID();
		},
		redirect(url) {
			let atag = $('<a href="#"></a>');
			atag.attr('href', url);
			atag[0].click();
		}
	};

	// 테이블 그리기
	$.fn.renderTable = function(data) {
		var defaultOpt = {
			"autoWidth": false,
			"destroy": true,
			"paging": true,
			"pagingType": "full_numbers",
			"ordering": true,
			"filter": false,
			"lengthChange": true,
			"select": true,
			"language": {
				"lengthMenu": '<div class="sel_box">' +
					'<select>' +
					'<option value="10">10</option>' +
					'<option value="30">30</option>' +
					'<option value="50">50</option>' +
					'<option value="-1">All</option>' +
					'</select>' +
					'</div>',
			},
			"dom": '<"row view-filter"<"col-sm-12"<"pull-left"><"pull-right"><"clearfix">>>t<"row view-pager"<"col-sm-12"<"text-center"pi>>>',
			//"dom": 'rti<"bottom"fp><"clear">',
			"data": data,
			createdRow: function(row, data, index) { },
			drawCallback: function(settings) { }
		}

		var opts = $.extend(defaultOpt, $.utils.dataTable.opts);
		$(this).dataTable(opts);
		$('.sel_box select').niceSelect();
	};

	// 공백값 체크
	$.fn.isBlank = function() {
		var _this = $(this);
		var v = _this.val();
		var tagName = _this.prop("tagName");
		if (tagName != 'INPUT' && tagName != 'SELECT' && tagName != 'TEXTAREA') {
			console.debug('값을 가질 수 있는 태그만 지원합니다.');
			return false;
		}
		return (v == null || v == undefined || v == '' || v.trim() == '');
	}
	// 공백값 체크
	$.fn.isNotBlank = function() {
		return !($(this).isBlank())
	}


	$.modal = {
		modalLoad : function(targetModal){
			let $self = $(this);

			// open and focusin
			targetModal.attr('tabindex', '0').fadeIn(250).focus();
			targetModal.css({ display: 'table' });
			targetModal.attr('class', 'modal open');
			// create sizing
			let layerHeight = targetModal.outerHeight();
			let layerWidth = targetModal.outerWidth();
			targetModal.css({
				marginLeft : -layerWidth/2,
				marginTop : -layerHeight/2
			});

			// create background
			createDim();

			// keydown focus repeat
			targetModal.find(".close").on('keydown', function(e){
				if(e.which=='9'){
					targetModal.attr('tabindex', '0').focus();
				}
			});

			// close and focusout
			targetModal.find(".close").on('click',function(e){
				e.preventDefault();
				targetModal.fadeOut(250);
				removeDim();
				$self.focus();
				$(this).off('click');
				targetModal.attr('class', 'modal');
				let isVisible = targetModal.is(':visible');
				let modalLength = $('.modal:visible').length;

				if (isVisible) {
					if (modalLength > 1) {
						targetModal.fadeOut(250);
					} else {
						$('.dim').fadeOut(250);
					}
				}
			});

			targetModal.find(".modalLoad").on('click',function(e){
				e.preventDefault();
				targetModal.fadeOut(250);
				$self.focus();
				var isVisible = targetModal.is(':visible');
				var modalLength = $('.modal:visible').length;

				if (isVisible) {
					if (modalLength > 1) {
						targetModal.fadeOut(250);
					} else {
						$('.dim').fadeOut(250);
					}
				}
			});

			$(document).on("keyup", function(e){
				if(e.which=='27'){
					targetModal.fadeOut(250);
					removeDim();
					$self.focus();
					targetModal.attr('class', 'modal');
				}
			});
		}
	}

})(jQuery);
