(function(factory) {
	var nameSpace = 'field_8899554679928334458';
	if (!window[nameSpace]) {
		console.log("开始实例化控件")
		var Builder = factory();
		window[nameSpace] = {
			instance: {}
		};
		window[nameSpace].init = function(options) {
			window[nameSpace].instance[options.privateId] = new Builder(options);
		};
	}
})(function() {
	function App(options) {
		var self = this;
		self.initParams(options);
		//初始化dom
		self.initDom();
		//事件
		self.events();
	}

	App.prototype = {
		initParams: function(options) {
			console.log("开始初始化参数")
			var self = this;
			self.adaptation = options.adaptation;
			self.privateId = options.privateId;
			self.preUrl = options.url_prefix;
			self.adaptation.formMessage = options.formMessage;
			self.messageObj = options.getData;
			console.log(self.messageObj)
		},
		initDom: function() {
			var self = this;
			console.log("开始渲染dom")
			dynamicLoading.css(self.preUrl + '/css/contractCompareBtn.css');
			self.appendChildDom();
		},
		events: function() {
			var self = this;
			// 监听是否数据刷新
			console.log("设置事件监听")
			self.adaptation.ObserverEvent.listen('Event' + self.privateId, function() {
				self.messageObj = self.adaptation.childrenGetData(self.privateId);
				self.appendChildDom();
			});
		},
		openCompareUrl: function(privateId, messageObj, adaptation) {
			// 实际的业务代码方法
					messageObj = adaptation.childrenGetData(privateId);
            							const targetObj = messageObj.formdata.formmains[adaptation.formMessage.tableName]
            							//backFill(ids, messageObj.id, messageObj.display, privateId,messageObj, adaptation);
            							//dialog.close()
            							console.log(targetObj)
            							if (targetObj) {
            								let contractRefId;
            								let templateRefId;
            								for (const key in targetObj) {
            									if (targetObj.hasOwnProperty(key) && !/^auxiliary/.test(key)) {
            										if (targetObj[key].display === "合同审批附件") {
            										   console.log(targetObj[key])
            										   contractRefId = targetObj[key].showValue;
                                                       console.log("合同附件refId: " + contractRefId)


            										}
            										if (targetObj[key].display === "原始合同模板文件") {
            									      console.log(targetObj[key])
                                                      templateRefId = targetObj[key].showValue;
                                                      console.log("模板文件refId: " + templateRefId)
                                                      }
            									}
            								}

            								$.ajax({
            									type: "POST",
            									url: '/seeyon/rest/cap4/etemplate/compareurl?templateRefId=' +
            										templateRefId + '&contractRefId=' +
            										contractRefId,
            									data: {},
            									dataType: "json",
            									contentType: 'application/json;charset=UTF-8',
            									success: function(res) {
            										// 后台解析数据后  将数据填写到表单中
            										if (res.code == 0) {
            											window.open(res.data, "_blank");
            										} else {
            											// 报错
            											$.alert(res.message);
            										}
            									},
            									complete: function() {},
            									error: function(e) {
            										top.$.error(e.responseText);
            									}
            								});
            							}
		},
		appendChildDom: function() {
			var self = this;
			const params = new URLSearchParams(window.location.search);
			console.log(params)
			const openFrom = params.get('openFrom'); // 返回"2025"
			const type = params.get('type');
			var edit = !((openFrom != null && (openFrom == 'listPending' || openFrom == 'listDone' ||
				openFrom == 'listSent')) || (type != null && type == 'browse'));
			console.log(edit)
			var domStructure = '<section class="customButton_box_content">' +
				'<div>' +
				'<button class = "customButton_class_box ' + self.privateId + '">' +
				self.messageObj.display.escapeHTML() +
				'</button>' +
				'</div>' +
				'</section>';
			document.querySelector('#' + self.privateId).innerHTML = domStructure;
			var compare = function() {
				self.openCompareUrl(self.privateId, self.messageObj, self.adaptation)
			}

			var content = self.messageObj.formdata.content;
			const picker = document.querySelector('.customButton_class_box' + '.' + self.privateId);
			if (picker) {
				document.querySelector('.customButton_class_box' + '.' + self.privateId)
					.removeEventListener(
						'click', compare);
				document.querySelector('.customButton_class_box' + '.' + self.privateId).addEventListener(
					'click', compare);
			}
			const goNewPages = document.querySelectorAll('.goToNewPage');
			if (goNewPages.length > 0) {
				goNewPages.forEach(element => {
					element.addEventListener('click', function(e) {
						window.open(e.currentTarget.dataset.href, '_blank'); //
					});
				});
			}
			//渲染隐藏权限
			if (self.messageObj.auth === 'hide') {
				document.querySelector('#' + self.privateId).innerHTML =
					'<div class="cap4-text__browse" style="line-height: 1.8; color: rgb(0, 0, 0) !important;">***</div>';
			}
		}

	};

	function backFill(ids, fieldName, fieldDisplay, privateId, messageObj, adaptation) {
		var param = new Object();
		param.masterId = messageObj.formdata.content.contentDataId;
		param.ids = ids;
		param.formId = messageObj.formdata.content.contentTemplateId;
		param.fieldName = fieldName;
		param.fieldDisplay = fieldDisplay;
		param.masterId = messageObj.formdata.content.contentDataId;
		$.ajax({
			type: "POST",
			url: '/seeyon/rest/cap4/hywp/fileref',
			data: JSON.stringify(param),
			dataType: "json",
			contentType: 'application/json;charset=UTF-8',
			success: function(res) {
				// 后台解析数据后  将数据填写到表单中
				if (res.code == 0) {
					var backfill = {};
					backfill.tableName = adaptation.formMessage.tableName;
					// 回填主表
					backfill.tableCategory = 'formmain';
					// 后台组装的data数据
					console.log(res.data)
					backfill.updateData = res.data;
					adaptation.backfillFormControlData(backfill, privateId);
				} else {
					// 报错
					$.alert(res.message);
				}
			},
			complete: function() {},
			error: function(e) {
				top.$.error(e.responseText);
			}
		});
	}
	var dynamicLoading = {
		css: function(path) {
			if (!path || path.length === 0) {
				throw new Error('argument "path" is required !');
			}
			var head = document.getElementsByTagName('head')[0];
			var link = document.createElement('link');
			link.href = path;
			link.rel = 'stylesheet';
			link.type = 'text/css';
			head.appendChild(link);
		},
		js: function(path) {
			if (!path || path.length === 0) {
				throw new Error('argument "path" is required !');
			}
			var head = document.getElementsByTagName('head')[0];
			var script = document.createElement('script');
			script.src = path;
			script.type = 'text/javascript';
			head.appendChild(script);
		}
	}
	return App;
});