let chatUrl = "http://192.168.1.175:2800/#/cus_customer";
// 客户端消息弹窗UI相关

// 图片
const base64ImageObject = {
	// pc端客服图片
	pcIcon: "data:image/png;base64,[encoded data, 13284 characters]",
	// 关闭客服服务，向下按钮
	putItAway:
		"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAHk0lEQVR4Xu3dXW5cNxBEYd7txNsJsp1I2xGynWQ7Eww8hmR7fppN8rLIOn4NOWpW9QcBGcA+Cn9IgAQeJnCQDQmQwOMEAMJ2kMCTBADCepAAQNgBEsglwG+QXG7cMkkAICZF88xcAgDJ5cYtkwQAYlI0z8wlAJBcbtwySQAgJkXzzFwCAMnlxi2TBABiUjTPzCUAkFxu3DJJACAmRfPMXAIAyeXGLZMEAGJSNM/MJQCQXG7cMkkAICZF88xcAgDJ5cYtkwQAYlI0z8wlAJBcbtwySQAgJkXzzFwCAMnlxi2TBABiUjTPzCUAkFxu3DJJACAmRfPMXAIAyeXGLZMEAGJSNM/MJQCQXG7cMkkAICZF88xcAgDJ5cYtkwQAYlI0z8wlAJBcbtwySQAgJkXzzFwCAMnlxi2TBABiUjTPzCUAkFxu3DJJACAmRfPMXAIAyeXGLZMEAGJSNM/MJQCQXG7cMkkAICZF88xcAgDJ5cYtkwQAYlI0z8wlAJBcbtwySQAgJkXzzFwCAMnlxi2TBABiUjTPzCUAkFxu3DJJYCiQy+Xyx3Ec/5lkyTMnJDB6x4YBuVwub6WUP0spf4FkwuYY/MgrjlLKRynln+M4rvvW/c8QIDccf9+m/Rck3Xuz/8AvOL7dwngfgaQ7kF9w/CgSJPYr3S+AOzh+fHh3JF2BPMABkn67Yf9JT3AMQdINyAscILFf7fYAAji6I+kCJIgDJO07YvsJFTi6ImkGUokDJLYrnn94Akc3JE1AkjhAkt8Vu5sNOLogSQNpxAESu1Wvf3AHHM1IUkA64QBJ/c7Y3OiIowlJNZDOOEBis/Lxhw7AkUZSDeT6k0ASL5uTdQko4bhOngICkrrSOR1L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ATgh5ABJwnNQbQE4KuiMScJzYGUBODLsDEnCc3BdATg68AQk4JnQFkAmhJ5CAY1JPAJkUfAUScEzsCCATww8gAcfkfgAyuYAnSMAh0A1ABEq4gwQcIr0ARKSIL0gKf/uITikA0emCSQQTAIhgKYykkwBAdLpgEsEEACJYCiPpJAAQnS6YRDABgAiWwkg6CQBEpwsmEUwAIIKlMJJOAgDR6YJJBBMAiGApjKSTAEB0umASwQQAIlgKI+kkABCdLphEMAGACJbCSDoJAESnCyYRTAAggqUwkk4CANHpgkkEEwCIYCmMpJMAQHS6YBLBBAAiWAoj6SQAEJ0umEQwAYAIlsJIOgkARKcLJhFMACCCpTCSTgIA0emCSQQTAIhgKYykkwBAdLpgEsEEACJYCiPpJAAQnS6YRDABgAiWwkg6CQBEpwsmEUwAIIKlMJJOAgDR6YJJBBMAiGApjKSTAEB0umASwQQAIlgKI+kkABCdLphEMAGACJbCSDoJAESnCyYRTAAggqUwkk4CANHpgkkEEwCIYCmMpJMAQHS6YBLBBAAiWAoj6SQAEJ0umEQwAYAIlsJIOgkARKcLJhFMACCCpTCSTgIA0emCSQQTAIhgKYykkwBAdLpgEsEE/gf9UbX2kaDu0wAAAABJRU5ErkJggg==",
};
let customerServer = null;

//事件添加和执行
window.$chat = {
	event: {},
	on(name, fun) {
		if (this.event[name] === undefined) {
			this.event[name] = [];
		}
		this.event[name].push(fun);
	},
	emit(name, attr) {
		if (this.event[name] && this.event[name].length) {
			this.event[name].map((item) => {
				if (typeof item === "function") {
					item(...attr);
				}
			});
		}
	},
};

//放入默认事件
window.$chat.on("postMessage", function (type, data) {
	if (!this.iframe_contanier) {
		return;
	}
	this.iframe_contanier.contentWindow.postMessage(
		{ type: type, data: data },
		"*"
	); // 传送图文数据
});

const settingObj = {};

//悬浮按钮样式
function customerServerStyle() {
	//PC端悬浮按钮样式
	this.customerServer_container = {
		position: "fixed",
		bottom: "10px",
		right: "2px",
		// background: 'linear-gradient(270deg, #1890FF 0%, #3875EA 100%)',
		// color: '#fff',
		// 'border-radius': '4px',
		// width: '230px',
		// padding: '8px 10px',
		"box-sizing": "border-box",
		cursor: "pointer",
		"z-index": 99,
	};
	this.connect_customerServer = {
		display: "flex",
		"align-items": "center",
		"justify-content": "space-between",
	};
	this.connect_customerServer_img = {
		width: "100%",
	};

	//未读消息演示
	this.connent_count = {
		position: "absolute",
		top: "-12px",
		right: 0,
		background: "red",
		width: "25px",
		height: "25px",
		"border-radius": "50%",
		display: "flex",
		"align-items": "center",
		"justify-content": "center",
		"font-size": "12px",
		opacity: ".9",
	};
	//iframe样式
	this.iframe_content = {
		position: "fixed",
		"z-index": 999,
		right: 0,
		"border-radius": "4px",
		transition: ".3s",
	};
}

const customerServerStyleObject = new customerServerStyle();

//初始化函数
function initCustomerServer(option) {
	this.outLine = false; // 是否在离线界面
	this.openChat = false; //是否需要打开聊天窗口
	this.settingObj = settingObj;
	this.baseUrl = chatUrl || location.origin;
	this.settingObj.openUrl = `${this.baseUrl}`; //服务器地址加路由, 若不传入则自动获取引入应用所在服务器的域名
	this.settingObj.domId = "customerServerTip"; //浮动客服dom
	this.settingObj.insertDomNode = option.insertDomNode || "body"; // 插入的标签
	this.settingObj.token = option.token; // token为必填项
	this.settingObj.pcIcon = base64ImageObject.pcIcon; // pcIcon 电脑端客服图片
	this.settingObj.isShowTip = option.isShowTip; //  false隐藏 true 展示 客服悬浮按钮默认展示
	this.settingObj.windowStyle = option.windowStyle || ""; // pc 端打开默认最精简模式，center居中模式
	this.settingObj.kefuid = option.kefuid || 0; // 指定客服，默认随机
	this.settingObj.sendUserData = option.sendUserData || {}; // 用户信息，默认游客
	this.settingObj.productInfo = option.productInfo || {}; // 携带产品信息，默认空
	this.settingObj.version = option.version || ""; //版本号
	this.appDom = null;
	this.initStatus = false; //是否初始化过
	// 判断当前环境下的设备是pc端 || 移动端, 将客户信息挂载到iframe的链接上
	this.setMatchMedia = () => {
		if (!this.settingObj.deviceType) {
			const matchMedia = window.matchMedia;
			// 自动判断启动端 pc 或是 移动
			if (matchMedia("(max-width: 600px)").matches) {
				this.settingObj.deviceType = "Mobile";
			} else if (matchMedia("(max-width: 992px)").matches) {
				this.settingObj.deviceType = "pc";
			} else {
				this.settingObj.deviceType = "pc";
			}
		}
		// console.log(this.settingObj.deviceType);
		// 获取客服客户相关参数
		let params = {
			token: this.settingObj.token,
			deviceType: this.settingObj.deviceType,
			windowStyle: this.settingObj.windowStyle,
			isShowTip: this.settingObj.isShowTip,
			kefuid: this.settingObj.kefuid,
		};
		this.settingObj.openUrl += `?` + toParams(params) + `&`;
		let customerServerData = "";
		if (
			this.settingObj.sendUserData &&
			Object.keys(this.settingObj.sendUserData).length
		) {
			customerServerData = toParams(this.settingObj.sendUserData);
			this.settingObj.openUrl += `${customerServerData}`;
		}

		this.settingObj.openUrl += "&version=" + this.settingObj.version;
	};

	// 创建 联系客服小弹窗按钮（点击时打开聊天界面）,创建iframe容器 并将iframe添加至body中
	this.createCustomerServerContainer = () => {
		let iframeHtml = `<iframe src="${this.settingObj.openUrl}" frameborder="0" class="iframe_contanier" style="width:100%; height:100%;"></iframe>`;
		const app = document.createElement("div");
		this.appDom = app;
		app.setAttribute("id", "chat-app");

		//电脑端悬浮按钮样式
		app.innerHTML = `
            <div class="customerServer_container" id="${this.settingObj.domId}">
              <div class="connect_customerServer">
                  <img class="connect_customerServer_img" src="${this.settingObj.pcIcon}"/>
              </div>
              <div class="connent_count"></div>
            </div>
            `;
		this.body = document.querySelector(this.settingObj.insertDomNode);
		this.body.appendChild(app);
		// 创建完毕后，添加样式，样式可以从外部传入
		this.iframeLayout = document.createElement("div");
		this.iframeLayout.setAttribute("id", "iframe_content");
		this.setStyleOfCustomerServer(
			this.iframeLayout,
			customerServerStyleObject.iframe_content
		);
		this.iframeLayout.style["z-index"] = 999;
		this.iframeLayout.innerHTML = iframeHtml;
		this.body.appendChild(this.iframeLayout);

		// 获取联系客服按钮dom对象
		this.connentServerDom = document.querySelector(
			`#${this.settingObj.domId}`
		);

		// 判断联系客服按钮是否默认展示
		if (this.settingObj.isShowTip === false) {
			this.connentServerDom.style.display = "none";
		}
		// 获取 iframe 弹框dom对象，便于后期数据交互
		this.iframe_contanier = document.querySelector(".iframe_contanier");
	};

	// 设置基本样式样式
	this.batchSetStyle = () => {
		Object.keys(customerServerStyleObject).forEach((item) => {
			if (document.querySelector(`.${item}`)) {
				this.setStyleOfCustomerServer(
					document.querySelector(`.${item}`),
					customerServerStyleObject[item]
				);
			}
		});
	};

	// 设置初始化样式，包括iframe弹宽初始定位，未读消息等
	this.initPositionStyle = () => {
		// pc端初始化样式
		let pcInitStyle = {
			width: "377px",
			bottom: "-645px",
			height: "645px",
			"z-index": 999,
			"box-shadow": "1px 1px 15px 0px rgba(0, 0, 0, 0.3)",
		};
		this.setStyleOfCustomerServer(this.iframeLayout, pcInitStyle);

		// 用来展示未读消息数的小圆点
		this.connent_count = document.querySelector(".connent_count");
		this.connent_count.style.display = "none";
	};
	//加载聊天框
	this.loadwindow = () => {
		// 接收来自iframe中的参数
		window.addEventListener("message", (e) => {
			window.$chat.emit(e.data.type, [e.data]);
			// 关闭弹框
			if (e.data.type === "closeWindow") {
				if (this.settingObj.windowStyle === "center") {
					this.setStyleOfCustomerServer(this.iframeLayout, {
						display: "none",
					});
				} else {
					this.iframeLayout.style.bottom = "-660px";
					this.iframeLayout.style.opacity = "0";
				}
				if (this.settingObj.isShowTip !== false) {
					this.connentServerDom.style.display = "block";
				}
			}

			// 收取未读消息
			if (e.data.type === "onMessageNum") {
				if (e.data.data.num > 0) {
					this.connent_count.style.display = "flex";
					this.connent_count.innerHTML = e.data.data.num;
				} else {
					this.connent_count.style.display = "none";
				}
			}

			// 跳转到离线留言界面
			if (e.data.type === "customerOutLine") {
				this.outLine = true;
				this.setStyleOfCustomerServer(this.iframeLayout, {
					width: this.outLine ? "378px" : "730px",
				});
			}
			// 监听，跳转回中间页，重置outline（来自反馈成功界面）
			if (e.data.type === "reload") {
				this.outLine = false;
			}
		});
	};

	this.openChatWin = () => {
		//检测是否初始化过
		if (this.initStatus === false) {
			this.init();
		}

		if (this.settingObj.windowStyle === "center") {
			this.setStyleOfCustomerServer(this.iframeLayout, {
				top: 0,
				left: 0,
				bottom: 0,
				right: 0,
				margin: "auto",
				width: this.outLine ? "378px" : "730px",
				display: "block",
				transition: "none",
				"border-radius": "8px",
				overflow: "hidden",
				"box-shadow": "1px 1px 15px 0px rgba(0, 0, 0, 0.3)",
			});
		} else {
			this.iframeLayout.style.bottom = 0;
			this.iframeLayout.style.opacity = "1";
		}
		//悬浮按钮隐藏
		this.connentServerDom.style.display = "none";
		this.iframe_contanier.contentWindow.postMessage(
			{
				type: "getImgOrText",
				productInfo: this.settingObj.productInfo,
			},
			"*"
		); // 传送图文数据
		this.iframe_contanier.contentWindow.postMessage(
			{ type: "openCustomeServer" },
			"*"
		); //通知iframe 打开了客服弹框
		//打开聊天窗事件
		window.$chat.emit("openChatWin");
	};

	// 打开客服聊天框
	this.getCustomeServer = () => {
		this.openChat = true;
		if (this.initStatus) {
			this.openChatWin();
			this.openChat = false;
		}
	};

	// 更新传送的图文信息
	this.postProductMessage = (productInfo) => {
		this.iframe_contanier.contentWindow.postMessage(
			{ type: "getImgOrText", productInfo: productInfo },
			"*"
		); // 传送图文数据
	};
}

//销毁事件
initCustomerServer.prototype.destroy = function () {
	this.appDom.remove();
	this.iframeLayout.remove();
	this.initStatus = false;
};

initCustomerServer.prototype.runInit = function () {
	this.setMatchMedia();
	this.createCustomerServerContainer();
	this.batchSetStyle();
	this.initPositionStyle();
	this.loadwindow();
	this.initStatus = true;
	this.connentServerDom.removeEventListener("click", this.openChatWin);
	// 联系客服小按钮，点击事件
	this.connentServerDom.addEventListener("click", this.openChatWin);
	//初始化事件
	window.$chat.emit("init");

	if (this.openChat) {
		this.openChatWin();
		this.openChat = false;
	}
};

//初始化
initCustomerServer.prototype.init = function () {
	request(this.baseUrl, "get", null, this.settingObj.token)
		.then((res) => {
			this.settingObj.pcIcon = res.data.icon;
			this.runInit();
		})
		.catch(() => {
			this.runInit();
		});
};
//封装全局设置样式方法
initCustomerServer.prototype.setStyleOfCustomerServer = function (
	dom,
	styleObj
) {
	Object.keys(styleObj).forEach((item) => {
		dom["style"][item] = styleObj[item];
	});
};
//封装全局获取openUle方法
initCustomerServer.prototype.getOpenUrl = function () {
	return this.settingObj.openUrl;
};

window.getChatInstance = function () {
	return customerServer;
};

function request(url, method, data, token, header) {
	return new Promise(function (resolve, reject) {
		ajax({
			url: url,
			method: method,
			// data: data,
			token: token,
			header: header,
			success: function (res) {
				resolve(res);
			},
			error: function (error) {
				reject(error);
			},
		});
	});
}

function ajax(options) {
	let xhr = null;
	const params = options.data || "";
	options.method = options.method || "get";
	//创建对象
	xhr = new XMLHttpRequest();
	switch (options.method.toUpperCase()) {
		case "GET":
			xhr.send(params ? toParams(params) : "");
			break;
		case "POST":
			xhr.send(JSON.stringify(params));
			break;
		default:
			break;
	}

	xhr.onreadystatechange = function () {
		try {
			if (xhr.readyState === 4) {
				const response = xhr.responseText
					? JSON.parse(xhr.responseText)
					: {};
				if (response.status === 200) {
					options.success && options.success(response);
				} else {
					options.error && options.error(response);
				}
			}
		} catch (e) {
			options.error && options.error(e);
		}
	};
}

// 将Object 改装成以 & 符号连接的字符串
function toParams(param) {
	var result = "";
	for (let name in param) {
		if (typeof param[name] != "function") {
			result += "&" + name + "=" + encodeURI(param[name]);
		}
	}

	return result.substring(1);
}
