/**
 * 自定义动态列表.js
 */
shr.defineClass("shr.custom.CustomDynamicList", shr.compensation.CmpTBDynamicList, {
	//编辑列数组(大小写不区分)
	editColumns: [],
	//金额字段显示精度
	decimalPrecisionFields: [],
	initalizeDOM: function () {
		shr.custom.CustomDynamicList.superClass.initalizeDOM.call(this);
	},
	/**
	 * 返回
	 */
	backAction: function (callback) {
		var self = this;
		self.beforeSave();
		if (self.checkEditCell()) {
			shr.showConfirm("您有编辑数据未保存，是否忽略？", function () {
				if (typeof (callback) == 'function') {
					callback.call();
				}
				self.back();
			}, function () {
				return;
			});
		} else {
			if (typeof (callback) == 'function') {
				callback.call();
			}
			self.back();
		}
	},
	/**
	 * 获取可以编辑列
	 * @returns 
	 */
	getEditColumns: function () {
		return this.editColumns;
	},
	/**
	* 扩展jqgrid options,供子类复写
	*/
	extendGridOptions: function (options) {
		var _self = this;
		var editCol = _self.getEditColumns();
		$.extend(true, options, {
			gridOption: {
				cellEdit: true,
				cellsubmit: 'clientArray'
			}
		});
		$.extend(true, options.gridConfig, {
			editCol: editCol
		});

		_self.editColumnsSetting = _self.initData.editColumnsSetting;
		if (_self.editColumnsSetting && !$.isEmptyObject(_self.editColumnsSetting) && options.gridConfig) {
			var columns = options.gridConfig.columns;
			if (columns) {
				$.each(columns, function (key, value) {
					if (value) {
						var name = value.name;
						var editSetting = _self.editColumnsSetting[name];
						if (editSetting) {
							$.extend(value, editSetting);
							if (value.editable && (value.editable == "true" || value.editable == true)) {
								if (value.formatter && value.formatter == "promptBox") {
									if (options.datatype == "json") {
										value.name = value.name + ".*";
									}
								}
							}
						}
					}
				});
			}
		}
	},
	/**
	 * 处理表格操作
	 * @param {*} options 
	 */
	handleGridOptions: function (options) {
		var columns = options.gridConfig.columns;
		var editCol = options.gridConfig.editCol;
		for (var i = 0; editCol && i < editCol.length; i++) {
			editCol[i] = editCol[i].toUpperCase();
		}
		if (editCol && editCol.length > 0 && columns && columns.length > 0) {
			for (var i = 0; i < columns.length; i++) {
				var column = columns[i];
				var columnName = column.name;
				//设置金额字段显示精度
				for (var j = 0; j < this.decimalPrecisionFields.length; j++) {
					var decimalPrecisionField = this.decimalPrecisionFields[j];
					if (columnName == decimalPrecisionField.name) {
						column.extendOptions.numberOptions.decimalPrecision = decimalPrecisionField.precision
						break;
					}
				}
				var index = $.inArray(columnName.toUpperCase(), editCol);
				if (index >= 0) {
					column.editable = true;
					if ("number" == column.type.toLowerCase() || "double" == column.type.toLowerCase() || "integer" == column.type.toLowerCase() || "bigdecimal" == column.type.toLowerCase()) {
						column.edittype = 'numberfield';
						column.editoptions = { maxlength: '50' };
						column.editoptions.inputJson = column.extendOptions.numberOptions;
					} else if ("date" == column.type.toLowerCase()) {
						column.edittype = 'shrDateTimePicker';
						column.formatter = 'shrDateTimePicker';
						column.datepickerjson = column.extendOptions.datetimeOptions
					} else if (!column.edittype) {
						column.edittype = 'shrtext';
						column.editoptions = { maxlength: '100' };
					}
					column.classes = "cellEditItem";
				}
			}
		}
		$.extend(true, options, options.gridOption);
	},
	/**
	* 设置插件，非002信息集必须复写
	*/
	getParamPlus: function () {
		return {};
	},
	/**
	 * 获取插件过滤条件，非002信息集必须复写
	 */
	getPlusFilterItems: function () {
		return null;
	},

	/**
	* 判断是否存在修改的单元格
	*/
	checkEditCell: function () {
		var _self = this;
		var tds = $("#grid td[class*='dirty-cell']");
		//判断是否存在已经修改但是没有切换的单元格
		var editCell = $("#grid input[type='text']");
		if (tds && tds.length > 0) {
			return true;
		} else {
			if (editCell) {
				var value = $("#grid input[type='text']").parent().attr('title');
				if (editCell.val() != value) {
					return true;
				}
			}
		}
		return false;
	},
	/*
	 * 确认是否存在已经修改但是没有保存的数据
	 */
	dynCalonfirm: function (message, action, cancel) {
		shr.msgHideAll();
		var _self = this;
		//		var tds = $("#grid td[class='dirty-cell']");
		if (_self.checkEditCell()) {
			var msg = top.Messenger().post({
				message: message,
				hideAfter: null,
				actions: {
					retry: {
						label: '确认',
						auto: false,
						delay: 0,
						showCloseButton: true,
						action: function () {
							shr.msgHideAll();
							if (action && $.isFunction(action)) {
								action.call(this);
							}
						}
					},
					cancel: {
						label: '取消',
						action: function () {
							shr.msgHideAll();
							if (cancel && $.isFunction(cancel)) {
								cancel.call(this);
							} else {
								return msg.cancel();
							}
						}
					}
				}
			});
			return msg;
		} else {
			shr.msgHideAll();
			if (action && $.isFunction(action)) {
				action.call(this);
			}
		}
	},
	/**
	 * 校验 子类可重写
	 * @returns 
	 */
	validate: function () {
		// shr.showWarning({
		// 	message: "提示",
		// });
		return true;
	},
	/**
	* 组装保存时传至服务端的数据 有编辑列 子类必须重写
	*/
	assembleSaveData: function (action) {
		// var _self = this;
		// var data = _self.prepareParam(action + 'Action');
		// data.method = action;
		// //data.operateState = _self.getOperateState();
		// data.model = shr.toJSON(_self.assembleModel());
		// // relatedFieldId
		// var relatedFieldId = this.getRelatedFieldId();
		// if (relatedFieldId) {
		// 	data.relatedFieldId = relatedFieldId;
		// }

		// return data;
	},
	/**
	* 根据列名称获取字段类型
	*/
	getColumnType: function (col) {
		var cols = $('#dynamicGrid').data("options").gridConfig.columns;
		var item;
		for (var i = 0; i < cols.length; i++) {
			item = cols[i];
			if (col.toUpperCase() == item.name.toUpperCase()) {
				return item.type;
			}
		}
		//默认数字
		return "NUMBER";
	},
	//判断是否为数字,整数位和小数位分别不超过10位
	checkNumValid: function (value, type) {
		var mesasage;
		if (value == null) {
			return true;
		}
		value = value.toString();
		if (type != undefined && !type) {//type为空默认校验数字
			mesasage = "未获取到该列的数据类型";
		}
		if ('NUMBER' == type.toUpperCase() || 'INTEGER' == type.toUpperCase() || 'BIGDECIMAL' == type.toUpperCase()) {
			// if (!/^-?[0-9]{1,10}\.?[0-9]{0,5}$/.test(value)) {
			// 	return false;
			// }
			// 移除小数点和指数符号后的长度就是有效数字位数
			let significantDigits = value.replace('.', '').replace('e+', '').length;
			if (significantDigits > 12) {
				return false;
			}
		}
		return true;
	},
	/**
	 * 保存前置方法
	 */
	beforeSave: function () {
		var _self = this;
		//将处于编辑状态的单元格执行savecell方法
		var $table = $("#grid")[0];
		var iRow = $table.p.iRow;
		var iCol = $table.p.iCol;
		$("#grid").jqGrid("saveCell", iRow, iCol);
		//var tds = $("#grid td[class*='dirty-cell']");
	},
	/**
	* 增加action参数，执行保存后继续执行其他方法
	*/
	saveDynGridAction: function (action) {
		if (this.validate()) {
			var _self = this;
			this.beforeSave();
			if (!_self.checkEditCell()) {
				shr.showWarning({
					message: "您没有修改列表中的数据，不需要保存!"
				});
				return;
			}
			try {
				var data = _self.assembleSaveData(action);
			} catch (error) {
				// 捕获到异常后的处理代码
				shr.showWarning({
					message: error.message,
					hideAfter: 3
				});
				return;
			}
			if (!data) {
				shr.showWarning({
					message: "请求参数为空!"
				});
				return;
			}
			$.block.show();
			_self.remoteCall({
				method: "saveDynGrid",
				async: false,
				param: { modi: JSON.stringify(data) },
				success: function (res) {
					//存在action则先不刷新
					if (action && $.isFunction(action)) {
						action.call(this);
					} else {
						shr.showInfo({
							message: res,
							hideAfter: 3
						});
						_self.queryGrid();
					}
				},
				error: function (res) {
					shr.showError({
						message: res.summary
					});
				},
				complete: function (jqXHR, textStatus) {
					if (jqXHR.responseText.indexOf("\"result\":\"error\"") > 0) {
						$.block.hide();
					}
				}
			});
		}
	},
	/**
	 * 批量提示行数据，方便子类覆写
	 */
	getBatchTipsRowDatas: function (ids, options) {
		var _self = this;
		var $table = $(_self.gridId);
		return $table.jqGrid('getSelectedRowsData');
	},
	/**
	 * 默认的action处理方法
	 */
	defaultBatchActionHandle: function (option) {
		var self = this;
		var selectedIds = this.getSelectedIds();
		if (!selectedIds) {
			shr.showWarning({ message: "请先选中数据!", hideAfter: 3 })
			return;
		}
		self.beforeSave();
		if (self.checkEditCell()) {
			shr.showConfirm("您有编辑数据未保存，是否忽略？", function () {
				shr.custom.CustomDynamicList.superClass.defaultBatchActionHandle.call(self, option);
			}, function () {
				return;
			});
		} else {
			shr.custom.CustomDynamicList.superClass.defaultBatchActionHandle.call(self, option);
		}
	},
	/**
	 * 描述:删除操作
	 * @action 
	 */
	deleteAction: function () {
		var self = this;
		var selectedIds = this.getSelectedIds(this.getBillIdFieldName());
		if (selectedIds) {
			self.beforeSave();
			if (self.checkEditCell()) {
				shr.showConfirm("您有编辑数据未保存，是否忽略？", function () {
					self.deleteRecord(selectedIds);
				}, function () {
					return;
				});
			} else {
				self.deleteRecord(selectedIds);
			}
		} else {
			shr.showWarning({
				message: "请先选中数据",
				hideAfter: 3
			});
		}
	},
	/**
	 * 描述:导出全部
	 * @action 
	 */
	exportToExcelAction: function () {
		var self = this;
		self.beforeSave();
		if (self.checkEditCell()) {
			shr.showConfirm("您有编辑数据未保存，是否忽略？", function () {
				shr.custom.CustomDynamicList.superClass.exportToExcelAction.call(self);
			}, function () {
				return;
			});
		} else {
			shr.custom.CustomDynamicList.superClass.exportToExcelAction.call(self);
		}
	},
	/**
	 * 描述:导出选中
	 * @action 
	 */
	exportCurrentAction: function () {
		var self = this;
		self.beforeSave();
		if (self.checkEditCell()) {
			shr.showConfirm("您有编辑数据未保存，是否忽略？", function () {
				shr.custom.CustomDynamicList.superClass.exportCurrentAction.call(self);
			}, function () {
				return;
			});
		} else {
			shr.custom.CustomDynamicList.superClass.exportCurrentAction.call(self);
		}
	},
	/**
	* 描述: 导入action
	*/
	importAction: function (customParam, callback) {
		var self = this;
		self.beforeSave();
		if (self.checkEditCell()) {
			shr.showConfirm("您有编辑数据未保存，是否忽略？", function () {
				self.doImportData('import', customParam, callback);
			}, function () {
				return;
			});
		} else {
			self.doImportData('import', customParam, callback);
		}
	},
	/**
	 * 获取父级窗口url参数
	 */
	getParentUrlParam: function (param) {
		var url = window.parent.location.search;
		return shr.getUrlRequestParam(param, url);
	},
	/**
	 * 获取提示字段
	 */
	getTipsColModels: function (colNames) {
		var colModels = [];
		if (colNames && colNames.length > 0) {
			var tablemodels = [];
			//拷贝一份新数据,避免影响原有配置
			$.extend(true, tablemodels, this.getBatchTipsTableModel())
			tablemodels.forEach(function (col, index) {
				if (colNames.includes(col.name)) {
					colModels.push(col);
					colNames.splice(jQuery.inArray(col.name, colNames), 1);
				}
			})
		}
		return colModels;
	},
	/**
	 * 设置金额显示精度
	 */
	setMoneyDecimalPrecision: function () {

	}
});

