/**
 * 判断是否为null
 *
 * @param value
 * @returns {boolean}
 */
function isBlank(data) {
	return data == null || data === undefined || data === 'null' || $.trim(data) === '' ||
		data === 'undefined' || data === 'unknown';
}

/**
 * 是否数字
 *
 * @param val
 * @returns {boolean}
 */
function isNumber(val) {
	return !isNaN(parseFloat(val)) && isFinite(val);
}

/**
 * 是否整数
 *
 * @param obj
 * @returns {boolean}
 */
function isInteger(obj) {
	return (obj | 0) == obj;
}

/**
 * 正整数校验
 *
 * @param input
 * @returns {boolean}
 */
function isPositiveInteger(input) {
	var pattern = /^[1-9]\d*$/; // 只能包含非零开头的数字
	if (pattern.test(input)) {
		return true;
	} else {
		return false;
	}
}

/**
 * 正数校验
 *
 * @param input
 * @returns {boolean}
 */
function isPositiveNumber(input) {
	return !isBlank(input) && isNumber(input) && (input > 0);
}

/**
 * 消息提示
 *
 * @param msg
 */
function message(msg) {
	WindowUtil({
		title: "提示:",
		content: "<div class='kendo-del-message'>" + msg + "</div>"
	});
}

/**
 * 消息提示
 *
 * @param title
 * @param msg
 */
function message2(title, msg) {
	WindowUtil({
		title: title,
		content: "<div class='kendo-del-message'>" + msg + "</div>"
	});
}

/*/!**
 * 文件下载路径
 *
 * @param docId
 * @returns {string}
 *!/
function downloadHref(docId) {
	// S3地址有外网
	// return IPLATUI.CONTEXT_PATH + ("run" == PROJECT_ENV ? ('/docFileDownload/' + docId)
	// 	: ('/EU/DM/EUDM06.jsp?docId=' + docId));
	// S3地址无外网
	return IPLATUI.CONTEXT_PATH + ("run" == PROJECT_ENV ? ('/file/download/' + docId)
		: ('/EU/DM/EUDM06.jsp?docId=' + docId));
}*/

/**
 * 文件下载路径
 *
 * @param docId
 * @param isPreview 是否预览,true:预览
 * @returns {string}
 */
function downloadHref(docId, isPreview) {
	if (isPreview) {
		return IPLATUI.CONTEXT_PATH + '/file/download/preview/' + docId;
	} else {
		// S3地址必须支持公网
		return IPLATUI.CONTEXT_PATH + '/file/download/' + docId;
	}
}

/**
 * 预览
 *
 * @param 文件类型,例如:jpg/docx/pdf
 * @param 文件ID
 */
function previewDoc(fileType, docId) {
	if (!isBlank(fileType) && fileType.toLowerCase() == "docx") {
		let url = "HPWD098?inqu_status-0-docId=" + docId;
		window.open(url, '_blank');
	} else {
		window.open(downloadHref(docId, true), '_blank');
	}
}

/**
 * 获取窗口宽度
 *
 * @returns {number}
 */
function getWindowWidth() {
	var winWidth = 1024;
	if (window.innerWidth) {
		winWidth = window.innerWidth;
	} else if ((document.body) && (document.body.clientWidth)) {
		winWidth = document.body.clientWidth;
	}
	if (document.documentElement && document.documentElement.clientWidth) {
		winWidth = document.documentElement.clientWidth;
	}
	return winWidth;
}

/**
 * 获取窗口高度
 *
 * @returns {number}
 */
function getWindowHeight() {
	var winHeight = 600;
	if (window.innerHeight) {
		winHeight = window.innerHeight;
	} else if ((document.body) && (document.body.clientHeight)) {
		winHeight = document.body.clientHeight;
	}
	// 通过深入 Document 内部对 body 进行检测,获取窗口大小
	if (document.documentElement && document.documentElement.clientHeight) {
		winHeight = document.documentElement.clientHeight;
	}
	return winHeight;
}

/**
 * 显示用户名称
 *
 * @param loginName
 * @param userName
 */
function showUserName(loginName, userName) {
	if (!isBlank(loginName) && !isBlank(userName)) {
		return loginName + "-" + userName;
	} else if (!isBlank(loginName)) {
		return loginName;
	} else if (!isBlank(userName)) {
		return userName;
	} else {
		return "";
	}
}

/**
 * 刷新下拉框
 *
 * @param container
 * @param inInfo
 */
function refreshSelect(container, inInfo) {
	let grid = container.closest(".k-grid").data("kendoGrid");
	let cellIndex = grid.cellIndex(container);
	let input = $('<input />');
	let field = inInfo.get("field");
	input.attr("name", field);
	input.attr("id", field);
	input.appendTo(container);
	let dataSource;
	let serviceName = inInfo.get("serviceName");
	let methodName = inInfo.get("methodName");
	let blockId = inInfo.get("blockId");
	EiCommunicator.send(serviceName, methodName, inInfo, {
		onSuccess: function (ei) {
			dataSource = ei.getBlock(blockId).getMappedRows();
		},
		onFail: function (ei) {
		}
	}, {async: false});
	input.kendoDropDownList({
		valuePrimitive: true,
		dataTextField: "textField",
		dataValueField: "valueField",
		dataSource: dataSource,
		template: "#=textField#",
		filter: "contains"
	});
	return dataSource;
}

/**
 * 刷新下拉框,可手动输入
 *
 * @param container
 * @param inInfo
 */
function refreshInputSelect(container, inInfo) {
	let grid = container.closest(".k-grid").data("kendoGrid");
	let cellIndex = grid.cellIndex(container);
	let input = $('<input />');
	let field = inInfo.get("field");
	input.attr("name", field);
	input.attr("id", field);
	input.appendTo(container);
	let dataSource;
	let serviceName = inInfo.get("serviceName");
	let methodName = inInfo.get("methodName");
	let blockId = inInfo.get("blockId");
	EiCommunicator.send(serviceName, methodName, inInfo, {
		onSuccess: function (ei) {
			dataSource = ei.getBlock(blockId).getMappedRows();
		},
		onFail: function (ei) {
		}
	}, {async: false});
	input.kendoAutoComplete({
		valuePrimitive: true,
		dataSource: dataSource,
		dataTextField: "textField",
		dataValueField: "valueField",
		required: "true",
		optionLabelTemplate: "#:textField#",
		valueTemplate: "#:valueField#",
		template: "#:textField#",
		filter: "contains"
	});
	input.data("kendoAutoComplete").search();
	return dataSource;
}

/**
 * 当前日期 YYYY-MM-DD
 *
 * @returns {string}
 */
function currDate() {
	const date = new Date();
	const year = date.getFullYear();
	const month = date.getMonth() + 1; // 月份从0开始,需要加1
	const day = date.getDate();
	return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
}

/**
 * 当前日期 YYYYMMDD
 *
 * @returns {string}
 */
function currShortDate() {
	const date = new Date();
	const year = date.getFullYear();
	const month = date.getMonth() + 1; // 月份从0开始,需要加1
	const day = date.getDate();
	return  year + (month < 10 ? '0' + month : month.toString()) + (day < 10 ? '0' + day : day);
}

/**
 * 当前月份 YYYYMM
 *
 * @returns {string}
 */
function currShortMonth() {
	const date = new Date();
	const year = date.getFullYear();
	const month = date.getMonth() + 1; // 月份从0开始,需要加1
	return  year + (month < 10 ? '0' + month : month);
}

/**
 * 当前日期 YYYY-MM-DD
 *
 * @returns {string} 日期
 */
function formatYYYYMMDD(dateStr) {
	// 假设输入是一个有效的日期字符串
	const date = new Date(dateStr);

	// 使用两位数的年月日格式化函数
	const yyyy = date.getFullYear().toString().padStart(4, '0');
	const mm = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的
	const dd = date.getDate().toString().padStart(2, '0');

	return `${yyyy}${mm}${dd}`;
}

/**
 * cookie 操作
 *
 * @param c_name
 * @param value
 * @param expiredays
 */
function setCookie(c_name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value) +
		((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

/**
 *
 * @param c_name
 * @returns {string}
 */
function getCookie(c_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1) {
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) {
				c_end = document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return ""
}

/**
 *
 * @param date
 * @param fmt
 * @returns {*}
 */
function dateFormate(date, fmt) {
	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;
}

/**
 *
 * @param AddDayCount
 * @param fmt
 * @returns {*}
 */
function getDateStr(AddDayCount, fmt) {
	var dt = new Date();
	dt.setDate(dt.getDate() + AddDayCount);//获取AddDayCount天后的日期
	return dateFormate(dt, fmt);
}

/**
 *
 * @param AddDayCount
 * @param fmt
 * @returns {*}
 */
function getDateStrAndClearTime(AddDayCount, fmt) {
	var dt = new Date();
	dt.setDate(dt.getDate() + AddDayCount);//获取AddDayCount天后的日期
	clearTime(dt);
	return dateFormate(dt, fmt);
}

/**
 * 清除时间
 */
function clearTime(date) {
	date.setHours(0);
	date.setMinutes(0);
	date.setSeconds(0);
	return date;
}

/**
 * 绘制表格
 *
 * @param blockId
 * @param jsonObj
 * @param gridIdSuffix
 * @param descNameInited
 */
function drawGrid(blockId, jsonObj, gridIdSuffix, descNameInited) {
	var blk = jsonObj.getBlock(blockId);
	var colsECName = jsonObj.get('colsECNameMap');
	var colsWidth = jsonObj.get('colsWidth') || {};
	var metas = blk.getBlockMeta().getMetas();
	var __grid_ef_grid_result = new efgrid(blockId, "ef_grid_" + gridIdSuffix);
	var matas_arr = [];
	var index = {};
	for (var attr in metas) {
		var meta = metas[attr];
		if (colsECName != null && !descNameInited) {
			meta.descName = colsECName[meta.name];
			if (!meta.descName) {
				meta.descName = meta.name == 'rn' ? '行号' : meta.descName;
			}
		}
		var pos = parseInt(meta.pos);
		index[attr] = pos;
		var newMeta = {};
		matas_arr[pos] = newMeta;
		newMeta.name = meta.name;
		newMeta.descName = $.trim(meta.descName) || meta.name;
		newMeta.primaryKey = meta.primaryKey;
		newMeta.width = colsWidth[meta.name] || meta.width;
		newMeta.sumType = "none";
		newMeta.attr = {enable: true};
		newMeta.pos = pos;
		newMeta.align = meta.align || '';
		if (meta.name == 'rn') {
			newMeta.align = 'center';
		}
	}
	var custom_cols = {"index": index, "metas": matas_arr, "groupIndex": {}, "columnGroups": []};
	__grid_ef_grid_result.setToolBarPosition("");
	__grid_ef_grid_result.setEnable(false);
	__grid_ef_grid_result.setReadonly(true);
	__grid_ef_grid_result.setAjax(true);
	__grid_ef_grid_result.setCanPageAll(false);
	__grid_ef_grid_result.setAutoDraw('yes');
	__grid_ef_grid_result.setServiceName("");
	__grid_ef_grid_result.setQueryMethod("query");
	__grid_ef_grid_result.setCustomColumns(custom_cols);
	__grid_ef_grid_result.setXlsExportMode("");
	__grid_ef_grid_result.setButtonBarId("");
	__grid_ef_grid_result.setButtonBarPosition("");
	__grid_ef_grid_result.setData(jsonObj);
	__grid_ef_grid_result.setStyle({"toolBar": "true"});
	$(document).ready(function () {
		__grid_ef_grid_result.paint();
	});
};


/**
 * 回车退出编辑状态
 */
function downKeyUp() {
	window.document.addEventListener("keyup", function (event) {
		if (event.keyCode === 13) {
			var grid1 = $("#ef_grid_result").data("kendoGrid");
			var grid2 = $("#ef_grid_detail").data("kendoGrid");
			// 回填
			//grid.addRows(returnRows);
			if(grid1 !== undefined){
				grid1.closeCell();
			}
			if(grid2 !== undefined){
				grid2.closeCell();
			}

		}
	})
}

function loadChange(grid,e,field) {
	var cell_label = field,that = grid;
	// locked 表示是否为固定列
	var locked = that.isCellLocked(cell_label);
	// tr 表示 locked 和非 locked 的行,index 表示此行的第几列
	var tr,index;
	// 获取此 model 元素信息
	var item = e.items[0];
	var _uid = item.uid;
	if (locked) {
		tr = $(".k-grid-content-locked tr[data-uid="+ _uid +"]");
		index = $("th[data-field='"+cell_label+"']").data("index");
	} else {
		tr = $(".k-grid-content tr[data-uid="+ _uid +"]");
		index = parseInt($("th[data-field='"+cell_label+"']").data("index")) - that.lockedHeader.find("th").length;
	}
	// 获取子 cell(td)
	var td = tr.children("td:eq("+index+")");
	// 触发 td.click 事件,
	td.trigger("click");
}

/**
 * 工具类
 */
(function ($) {

	/**
	 * 上传文件
	 *
	 * @param bizType
	 * @param bizId
	 * @param
	 */
	let uploadFile = function (bizType, bizId, callback) {
		let params = {
			"inqu_status-0-bizId": bizId,
			"inqu_status-0-bizType": bizType
		}
		JSColorbox.open({
			href: "HPDM099A",
			title: "<div style='text-align: center;'>附件上传</div>",
			width: "60%",
			height: "50%",
			params: params,
			callbackName: function (res) {
				if (typeof callback === 'function') {
					callback(res);
				}
			}
		});
	}

	// export 到全局作用域 window对象
	$.extend(window, {
		CommonUtils: {
			uploadFile: uploadFile,
		}
	});
})(window.jQuery);