(function(_self, factory) {
	var nameSpace = 'customBtn_1992789877417263104';

	if (!window[nameSpace] && typeof factory === 'function') {
		var Builder = factory();
		window[nameSpace] = {
			initBtn : {}
		};
		/**
		 * 初始化方法
		 */
		 console.log("初始化")
		window[nameSpace].init = function(el, options) {
			var identification = Math.floor(Math.round() * 10000000000)
					.toString();
			window[nameSpace].initBtn[identification] = new Builder(el,
					options, _self, identification);
		}
	}
})
		(
				window,
				function() {
					/**
					 * js,css文件加载方法
					 */
					var dynamicLoading = {
						css : function(path, name, callBk) {
							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';
							link.setAttribute('data-name', name);
							link.onload = function() {
								callBk();
							}
							head.appendChild(link);
						},
						insertCss : function(innerTexts, name) {
							var head = document.getElementsByTagName('head')[0];
							var style = document.createElement('style');
							style.type = 'text/css';
							style.setAttribute('data-name', name);
							try {
								style.appendChild(document
										.createTextNode(innerTexts));
							} catch (ex) {
								style.styleSheet.cssText = innerTexts;// 针对IE
							}
							head.appendChild(style);
						},
						checkCss : function(name) {
							var styleList = document
									.getElementsByTagName('style');
							for (var i = 0; i < styleList.length; i++) {
								if (styleList[i].getAttribute('data-name') === name)
									return true;
							}
							return false;
						},
						js : function(path, callBk) {
							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';
							script.onload = function() {
								callBk();
							}
							head.appendChild(script);
						},
						checkJs : function(name) {
							var scriptList = document
									.getElementsByTagName('script');
							for (var i = 0; i < scriptList.length; i++) {
								if (scriptList[i].getAttribute('data-name') === name)
									return true;
							}
							return false;
						},
					}
					/**
					 * 浏览器
					 */
					function myBrowser() {
						var userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
						var isOpera = userAgent.indexOf("Opera") > -1;
						if (isOpera) { // 判断是否Opera浏览器
							return "Opera"
						}
						;
						if (userAgent.indexOf("Firefox") > -1) { // 判断是否Firefox浏览器
							return "FF";
						}
						;
						if (userAgent.indexOf("Chrome") > -1) {
							return "Chrome";
						}
						;
						if (userAgent.indexOf("Safari") > -1) { // 判断是否Safari浏览器
							return "Safari";
						}
						;
						if (userAgent.indexOf("compatible") > -1
								&& userAgent.indexOf("MSIE") > -1 && !isOpera) { // 判断是否IE浏览器
							return "IE";
						}
						;
					}
					/**
					 * 定义标签打印按钮的构造函数
					 *
					 * @param {*}
					 *            options
					 * @param {*}
					 *            _self
					 */
					function labelPrintingBtn(el, options, _self,
							identification) {
						var self = this;
						self.window_self = _self;
						self.el = el;
						self.identification = identification;
						// 解析传进来的数据
						self.initParams(options);
						// 处理挂载
						self.initBtn(el);
						// 销毁自己
						self.beforeDestroy = function() {
							self = null;
						}
					}
					/**
					 * 构造函数的原型方法
					 */
					labelPrintingBtn.prototype = {
						initParams : function(options) {
						console.log("初始化")
							this.place = options.place;
							this.rowData = options.rowData;
							this.data = options.data;
						},
						initBtn : function(el) {
							/**
							 * 挂载dom初始化处理
							 */
							var innerTexts = '.labelPrintingBtnHandler {'
									+ 'background-color: rgba(0,0,0,0);'
									+ 'font-family: "Ping Fang SC", "Microsoft YaHei", Arial, Helvetica, sans-serif, "SimSun";'
									+ 'cursor: pointer;'
									+ 'white-space : nowrap;'
									+ 'border: 0;'
									+ 'overflow: hidden;'
									+ 'text-overflow: ellipsis;'
									+ '}'
									+ '.labelPrintingBtnBox { box-sizing: border-box; cursor: pointer; outline: none; font-family: inherit; white-space: nowrap;display: inline-block; margin-top: 5px; vertical-align: middle; margin-right: 5px;'
									+ ' background-color: #fff; border: 1px solid #d4d4d4; color: #666;font-size: 14px; line-height: 28px; border-radius: 15px; height: 30px;}'
									+ '.labelPrintingBtnBox:hover{ border-color: #1f85ec; }'
									+ '.labelPrintingBtnRow{color: #1f85ec;}'
									+ '.labelPrintingBtnRow:hover{color : #479bf3}'
									+ '.labelPrintingBtnLi{color : #333}'
									+ '.labelPrintingBtnLi:hover{color : #fff}';
							if (!dynamicLoading.checkCss('labelPrintingBtn')) {
								dynamicLoading.insertCss(innerTexts,
										'labelPrintingBtn');
							}
							// 挂载dom
							this.appendDom(el);
						},
						appendDom : function(el) {
							var self = this;
							var labelPrint = document.createElement('div'), labelPrintToolbar, labelPrintIcon;
							// 对代码片段进行配置
							el.appendChild(labelPrint);
							// 根据不同位置渲染按钮
							switch (this.place) {
							case 'toolbar':
								labelPrint.parentNode.setAttribute('class',
										'labelPrintingBtnBox');
								labelPrint.style.padding = '0 14px';
								// 加入icon
								labelPrintIcon = document.createElement('i');
								labelPrintIcon.setAttribute('class',
										'CAP cap-icon-dayin');
								labelPrintIcon.style.color = '#C3AF1C';
								labelPrint.appendChild(labelPrintIcon);
								// 加入name信息
								labelPrintToolbar = document
										.createElement('span');
								labelPrintToolbar.innerHTML = this.data
										&& this.data.name ? this.data.name : '';
								labelPrintToolbar.style.paddingLeft = '3px';
								labelPrint.appendChild(labelPrintToolbar);
								break;
							case 'li':
								labelPrint.innerHTML = this.data
										&& this.data.name ? this.data.name : '';
								labelPrint
										.setAttribute('class',
												'labelPrintingBtnLi labelPrintingBtnHandler')
								break;
							case 'row':
								labelPrint.innerHTML = this.data
										&& this.data.name ? this.data.name : '';
								labelPrint
										.setAttribute('class',
												'labelPrintingBtnRow labelPrintingBtnHandler')
								break;
							default:
							}
							labelPrint.onclick = function() {
								switch (self.place) {
								case 'toolbar':
									// 点击执行对应的操作
									self.implementClick();
									break;
								case 'li':
								case 'row':
									// 点击执行对应的操作
									self.implementClick(self.rowData);
									break;
								default:
								}

							}
							// 阻止数据污染
							labelPrint.parentNode.onclick = function(e) {
								e.stopPropagation();
							}
						},
						// 执行点击事件
						implementClick : function(rowData) {
							var self = this;
							var datas;
							if (!rowData && window.extendApi
									&& window.extendApi.getChooseId) {
								datas = window.extendApi.getChooseId();
							} else {
								datas = rowData.id;
							}
							// 获取模版id
							this.handlerLogic(datas);
						},
						// 点击逻辑执行
						handlerLogic : function(rowData) {
							this.getImages();
						},
						getImages: function() {
                            var batchCode = window.localStorage.getItem('saomiaoyi');
	                        var saoMiaoYiApiBaseUrl = "http://localhost:8080";

                            // 1. 阻塞获取图片列表
                            var xhr = new XMLHttpRequest();
                            xhr.open("GET", saoMiaoYiApiBaseUrl + "/jControls/getImage", false);
                            xhr.setRequestHeader("batchNumber", batchCode);
                            xhr.send(null);

                            if (xhr.status !== 200) {
                                console.error("getImage 请求失败", xhr.status);
                                return;
                            }

                            var res = JSON.parse(xhr.responseText);
                            var imgs = res.data.imgList || [];

                            // 2. 逐张上传（阻塞）
                            for (var i = 0; i < imgs.length; i++) {
                                this.uploadImage(imgs[i],i)
                            }
                               var xhr2 = new XMLHttpRequest();
                                                        xhr2.open("GET", saoMiaoYiApiBaseUrl + "/jControls/getStop", false);
                                                        xhr2.send(null);

                                                        if (xhr2.status !== 200) {
                                                            console.error("getImage 请求失败", xhr.status);
                                                            return;
                                                        }

                        },
                        	 base64ToBlob: function(base64String) {
                               // 如果包含 "data:" 则按 dataURL 解析
                                   if (base64String.startsWith("data:")) {
                                       const arr = base64String.split(',');
                                       const pre = arr[0];
                                       const base64Data = arr[1];

                                       // 获取 MIME 类型
                                       let mime = "application/octet-stream";
                                       const mimeMatch = pre.match(/data:(.*?);base64/);
                                       if (mimeMatch && mimeMatch[1]) {
                                           mime = mimeMatch[1];
                                       }

                                       const byteString = atob(base64Data);
                                       const len = byteString.length;
                                       const u8arr = new Uint8Array(len);

                                       for (let i = 0; i < len; i++) {
                                           u8arr[i] = byteString.charCodeAt(i);
                                       }

                                       return new Blob([u8arr], { type: mime });
                                   }

                                   // ---- 如果没有 data: 前缀，按纯 Base64 解码 ----
                                   const byteString = atob(base64String);
                                   const len = byteString.length;
                                   const u8arr = new Uint8Array(len);

                                   for (let i = 0; i < len; i++) {
                                       u8arr[i] = byteString.charCodeAt(i);
                                   }

                                   // 默认二进制流类型
                                   return new Blob([u8arr], { type: "application/octet-stream" });
                            },

                            // 如果想要 File 对象
                             base64ToFile: function(base64, filename) {
                                const blob = this.base64ToBlob(base64);
                                return new File([blob], filename, { type: blob.type });
                            },

                          uploadImage:  function(base64, filename) {
                              const file = this.base64ToFile(base64, filename);

                              const formData = new FormData();
                              formData.append('file', file);
                              var apiBaseUrl = window.location.origin;
                              const xhr = new XMLHttpRequest();
                              xhr.open('POST', apiBaseUrl + '/seeyon/rest/saomiaoyi/fileSave', true); // 可以改成 false 同步
                              xhr.onreadystatechange = function() {
                                  if (xhr.readyState === 4) {
                                      if (xhr.status === 200) {
                                          console.log('上传成功:', xhr.responseText);
                                      } else {
                                          console.error('上传失败:', xhr.status, xhr.responseText);
                                      }
                                  }
                              };
                              xhr.send(formData);
                          }
					};
					/**
					 * 返回值
					 */
					return labelPrintingBtn;
				});