/**
 * 分配人员明细动态list.js(负责人)
 */
shr.defineClass("shr.custom.DetailPrincipalDynamicList", shr.custom.CustomDynamicList, {
	isSum: false,
	initalizeDOM: function () {
		//新增编辑列
		this.editColumns.push("person.name");
		this.editColumns.push("bdpapd.functioncoefficient");
		this.editColumns.push("bdpapd.energyinputcoeff");
		this.editColumns.push("bdpapd.bonusduedate");
		this.editColumns.push("bdpapd.bonusstartingdate");
		this.editColumns.push("bdpapd.adjustmentdesc");
		this.editColumns.push("bdpapd.opinionamount");
		//设置金额字段显示精度
		this.decimalPrecisionFields.push({ name: "bdpapd.opinionamount", precision: 6 });
		this.decimalPrecisionFields.push({ name: "bdpapd.indivbonusamount", precision: 6 });
		this.decimalPrecisionFields.push({ name: "bdpapd.approvalamount", precision: 6 });
		shr.custom.DetailPrincipalDynamicList.superClass.initalizeDOM.call(this);
		this.setF7Attribute();
	},
	/**
	 * @Override
	 */
	queryGrid: function () {
		//设置按钮是否可见
		this.setButtonVisible()
		shr.custom.DetailPrincipalDynamicList.superClass.queryGrid.call(this);
	},
	/**
	 * 设置按钮是否可见
	 */
	setButtonVisible: function () {
		var busDepId = shr.getUrlParam('parentId');
		var options = {
			action: 'getStateByBusDepId',
			uipk: this.uipk,
			type: 'POST',
			async: false,
			param: {
				busDepId: busDepId
			},
			success: function (res) {
				if (1 == res.value) {
					//启用
					$("#saveDynGrid").show();
					$("#import").show();
					$("#submit").show();
					$("#delete").show();
					$("#submitRecheck").hide();
				} else if (2 == res.value) {
					//已提交
					$("#saveDynGrid").hide();
					$("#import").hide();
					$("#submit").hide();
					$("#delete").hide();
					$("#submitRecheck").hide();
				} else if (4 == res.value) {
					//待复核
					$("#submit").hide();
					$("#delete").hide();
					$("#saveDynGrid").show();
					$("#import").show();
					$("#submitRecheck").show();
				} else if (5 == res.value) {
					//已提交复核
					$("#saveDynGrid").hide();
					$("#import").hide();
					$("#submit").hide();
					$("#delete").hide();
					$("#submitRecheck").hide();
				}
			}
		};
		shr.remoteCall(options);
	},
	/**
	 * 设置F7组件属性
	 */
	setF7Attribute: function () {
		var self = this;
		// $("#grid").delegate(".ui-datepicker-layout", "keyup.datetimepicker click", function () {
		// 	//奖金期限截止日期  奖金期限开始日期
		// 	$("input[id$='_bdpapd.bonusduedate']").shrDateTimePicker('option', {
		// 		onchange: function (e, val) {
		// 			var info = val.current;
		// 			var rowid = $($(e.target).parents('tr')[0]).attr('id');
		// 			var personPosition = _self.getPersonPositionByPersonId(info["id"]);
		// 			//填充组织、职位、任职id
		// 			//$("#grid").wafGrid("setCell", rowid, "person.number", info["number"]);

		// 		},
		// 	});
		// });
	},
	/**
	 * 	单元格点击事件触发
	 * @param {*} rowid 
	 * @param {*} colIndex 
	 * @param {*} cellcontent 
	 * @param {*} e 
	 * @returns 
	 */
	onCellSelect: function (rowid, colIndex, cellcontent, e) {
		shr.custom.DetailPrincipalDynamicList.superClass.onCellSelect.call(this);
		// 选择的是选择框
		if (colIndex != 0) {
			var columnName = $("#grid").getColumnName(colIndex);
			var state = $("#grid").jqGrid("getCell", rowid, "bdp.state");
			if (1 == state && ("person.name" == columnName || "bdpapd.functioncoefficient" == columnName
				|| "bdpapd.energyinputcoeff" == columnName || "bdpapd.bonusstartingdate" == columnName || "bdpapd.bonusduedate" == columnName)) {
				$("#grid").jqGrid("setGridParam", { cellEdit: true })
			} else if (4 == state && ("bdpapd.opinionamount" == columnName || "bdpapd.adjustmentdesc" == columnName)) {
				$("#grid").jqGrid("setGridParam", { cellEdit: true })
			} else {
				$("#grid").jqGrid("setGridParam", { cellEdit: false })
			}
		}
	},
	// 根据动态列表配置 取业务主键
	getBillIdFieldName: function () {
		return 'bdpapd.id';
	},
	//导出选中
	getExportFieldName: function () {
		return 'bdpapd.id';
	},
	/**
	 * 表格加载完成后操作，供子类复写
	 */
	afterLoadComplete: function (ret) {
		//当状态非启用 编辑列单元格背景色显示白色
		if (ret.records > 0) {
			for (let i = 0; i < ret.rows.length; i++) {
				var rowData = ret.rows[i];
				var state = rowData["bdp.state"];
				var fid = rowData[this.getBillIdFieldName()];
				var tr = $('tr[id="' + fid + '"]')
				var tds = [];
				for (var j = 0; j < this.editColumns.length; j++) {
					tds.push(tr.find('[aria-describedby="grid_' + this.editColumns[j] + '"]'));
				}
				if (1 == state.value) {
					for (var j = 0; j < tds.length; j++) {
						var describedby = $(tds[j]).attr("aria-describedby")
						if ("grid_bdpapd.opinionamount" == describedby || "grid_bdpapd.adjustmentdesc" == describedby) {
							$(tds[j]).removeClass('cellEditItem')
						} else {
							$(tds[j]).addClass('cellEditItem')
						}
					}
				} else if (4 == state.value) {
					for (var j = 0; j < tds.length; j++) {
						var describedby = $(tds[j]).attr("aria-describedby")
						if ("grid_bdpapd.opinionamount" == describedby || "grid_bdpapd.adjustmentdesc" == describedby) {
							$(tds[j]).addClass('cellEditItem')
						} else {
							$(tds[j]).removeClass('cellEditItem')
						}
					}
				} else {
					for (var j = 0; j < tds.length; j++) {
						$(tds[j]).removeClass('cellEditItem')
					}
				}
			}
		}
	},
	/**
	 * 获得自定义过滤条件，供子类覆写使用
	 */
	getCustomFilterItems: function () {
		var parentId = shr.getUrlParam('parentId');
		return "BDP.id = '" + parentId + "' and bDPAPD.id is not null";
	},
	/**
	 * 描述: 导入action
	 */
	importAction: function () {
		var self = this;
		//自定义参数
		var parentId = shr.getUrlParam('parentId');
		var customParam = { "parentId": parentId }
		self.beforeSave();
		if (self.checkEditCell()) {
			shr.showConfirm("您有编辑数据未保存，是否忽略？", function () {
				self.doImportData('import', customParam);
			}, function () {
				return;
			});
		} else {
			self.doImportData('import', customParam);
		}
	},
	/**
	* 组装保存时传至服务端的数据
	*/
	assembleSaveData: function (action) {
		var _self = this;
		//组装需要修改的数据
		var data = [];
		var meta;
		var id, column, value, cur, element, personCode, datatype;
		var tds = $("#grid td[class*='dirty-cell']");
		var $table = $("#grid")[0];

		for (var i = 0; i < tds.length; i++) {
			//获取父节点，以获取对应id
			meta = {};
			var cur = $(tds[i]);
			//获取输入的内容，而不是转以后的字符实体，同时对单引号处理

			fid = cur.parent().attr('id');
			element = cur.attr('aria-describedby').replace('grid_', '');
			value = $($table).getCell(fid, element);
			//value = cur.text().replace(/\'/g, "''").trim();
			datatype = _self.getColumnType(element);
			if ("promptbox" == datatype) {
				column = element.split('.')[0];
				value = value["id"];
			} else {
				column = element.split('.')[1];
			}
			//列表需要显示id列
			id = $("#" + _self.getEscapeChars(fid) + " td[aria-describedby='grid_" + _self.getBillIdFieldName() + "']").attr('title');
			//校验
			_self.checkData(column, tds[i], value);
			//校验输入内容
			if (!_self.checkNumValid(value, datatype)) {
				$(tds[i]).focus();
				$(tds[i]).css({
					"border": "solid 2px red"
				});
				throw new Error("请输入正确的格式");
			}
			meta.fid = id;
			meta.column = column;
			meta.value = value;
			meta.type = datatype;
			data.push(meta);
		}
		return data;
	},
	/**
	 * 
	 */
	checkData: function (column, td, value) {
		var _self = this;
		if ("bonusstartingdate" == column || "bonusduedate" == column) {
			//奖金期限开始日期  || 奖金期限截止日期
			var bonusstarting = $("#" + _self.getEscapeChars(fid) + " td[aria-describedby='grid_bdpapd.bonusstartingdate']")[0].innerText;
			var bonusdue = $("#" + _self.getEscapeChars(fid) + " td[aria-describedby='grid_bdpapd.bonusduedate']")[0].innerText;
			if (bonusstarting && bonusdue) {
				var bonusstartingdate = new Date(bonusstarting + ' 00:00:00')
				var bonusduedate = new Date(bonusdue + ' 00:00:00')
				if (bonusduedate < bonusstartingdate) {
					$(td).focus();
					$(td).css({
						"border": "solid 2px red"
					});
					throw new Error("奖金期限截止日期 不得早于 奖金期限开始日期");
				}
			}
		} else if ("person" == column && !value) {
			$(td).focus();
			$(td).css({
				"border": "solid 2px red"
			});
			throw new Error("分配人员不能为空!");
		}
		//  else if ("initialproportion" == column && (1 < value || 0 > value)) {
		// 	$(td).focus();
		// 	$(td).css({
		// 		"border": "solid 2px red"
		// 	});
		// 	throw new Error("个人初始比例只能在[0,1]之间!");
		// }
	},
	/**
	 * 计算
	 */
	// calculateAction: function (option) {
	// 	var self = this;
	// 	//事业部ids
	// 	var busDepId = shr.getUrlParam('parentId');
	// 	if (busDepId) {
	// 		var options = {
	// 			action: 'calculate',
	// 			uipk: this.uipk,
	// 			type: 'POST',
	// 			async: false,
	// 			param: {
	// 				busDepId: busDepId
	// 			},
	// 			success: function (res) {
	// 				shr.showSuccess({
	// 					message: "计算成功!",
	// 					hideAfter: 3
	// 				});
	// 				self.queryGrid();
	// 			},
	// 			error: function (res) {
	// 				shr.showError({
	// 					message: res.summary,
	// 					hideAfter: 3
	// 				});
	// 				setTimeout(function () {
	// 					location.reload();
	// 				}, 3000);
	// 			}
	// 		};
	// 		self.beforeSave();
	// 		if (self.checkEditCell()) {
	// 			shr.showConfirm("您有编辑数据未保存，是否忽略？", function () {
	// 				shr.remoteCall(options);
	// 			}, function () {
	// 				return;
	// 			});
	// 		} else {
	// 			shr.remoteCall(options);
	// 		}
	// 	} else {
	// 		shr.showError({
	// 			message: "事业部id为空",
	// 			hideAfter: 3
	// 		});
	// 	}
	// },
	/**
	 * 提交
	*/
	submitAction: function (option) {
		var self = this;
		//事业部ids
		var busDepId = shr.getUrlParam('parentId');
		if (busDepId) {
			var options = {
				action: 'customSubmit',
				uipk: this.uipk,
				type: 'POST',
				async: false,
				param: {
					busDepId: busDepId
				},
				success: function (res) {
					shr.showSuccess({
						message: "提交成功!",
						hideAfter: 3
					});
					self.queryGrid();
				},
				error: function (res) {
					$.block.hide();
					shr.showError({
						message: res.summary,
						hideAfter: 3
					});
				}
			};
			self.beforeSave();
			if (self.checkEditCell()) {
				shr.showConfirm("您有编辑数据未保存，是否忽略？", function () {
					$.block.show({
						text: '正在提交中'
					});
					shr.remoteCall(options);
				}, function () {
					return;
				});
			} else {
				$.block.show({
					text: '正在提交中'
				});
				shr.remoteCall(options);
			}
		} else {
			shr.showError({
				message: "事业部id为空",
				hideAfter: 3
			});
		}
	},
	/**
	 * 提交复核
	 * @param {*}  
	 */
	submitRecheckAction: function () {
		var self = this;
		//事业部ids
		var busDepId = shr.getUrlParam('parentId');
		if (busDepId) {
			self.beforeSave();
			if (self.checkEditCell()) {
				shr.showConfirm("您有编辑数据未保存，是否忽略？", function () {
					self.verifyDiffAmount();
				}, function () {
					return;
				});
			} else {
				self.verifyDiffAmount();
			}
		} else {
			shr.showError({
				message: "事业部id为空",
				hideAfter: 3
			});
		}
	},
	/**
	 * 校验奖金是否有出入
	 */
	verifyDiffAmount: function () {
		var self = this;
		var busDepId = shr.getUrlParam('parentId');
		var tableData = [];
		var options = {
			action: 'getDifferenceAmount',
			uipk: this.uipk,
			type: 'POST',
			async: false,
			param: {
				busDepId: busDepId
			},
			success: function (res) {
				if(res){
                    tableData = res;
                }
			},
		};
		shr.remoteCall(options);
		if (tableData.length > 0) {
			var colNames = ['person.number', 'person.name', 'bdpapd.indivbonusamount', 'bdpapd.opinionamount'];
			var colModels = self.getTipsColModels(colNames);
			$(self).cusDetailTips({
				tableData: tableData,
				failureCount: tableData.length,
				isSortable: true,
				callback: function () { self.doSubmitRecheck() }, //回调函数
				title: "个人奖金存在超发情况",
				piece: "条",
				colModels: colModels
			}).cusDetailTips("open");
		} else {
			self.doSubmitRecheck();
		}
	},
	/**
	 * 真正的提交复核方法
	 */
	doSubmitRecheck: function () {
		var self = this;
		var busDepId = shr.getUrlParam('parentId');
		var options = {
			action: 'submitRecheck',
			uipk: this.uipk,
			type: 'POST',
			async: false,
			param: {
				busDepId: busDepId
			},
			success: function (res) {
				$.block.hide();
				shr.showSuccess({
					message: "提交成功!",
					hideAfter: 3
				});
				self.queryGrid();
			},
			error: function (res) {
				$.block.hide();
				shr.showError({
					message: res.summary,
					hideAfter: 3
				});
			}
		};
		$.block.show({
			text: '正在提交中'
		});
		shr.remoteCall(options);
	},
});

