/**
 * 表单页面点击提交按钮，跳转到登录/注册页面，完成后继续当前操作
 */
define(['zepto', 'https://review-formal.iplusmed.com/Common/javaScript/medtap-core-dev.js'], function($, medtapCore) {;
	(function(w, d) {
		var oldAlert = window.alert;
		window.alert = function(msg) {
			var iframe = document.createElement("IFRAME");
			iframe.style.display = "none";
//			iframe.setAttribute("src", 'data:text/plain,');
			document.documentElement.appendChild(iframe);
			window.frames[0].window.alert(msg);
			iframe.parentNode.removeChild(iframe);
		}
		var options = {
			id: '_beforeSubmitBox',
			getInfo: false,
			wechatId: '',
			doctorId:medtapCore.getRequest('doctorId'),
			inviteCode:medtapCore.getRequest('inviteCode'),
			agencyId:medtapCore.getRequest('agencyId'),
			operationType:medtapCore.getRequest('operationType'),
			businessDetail:medtapCore.getRequest('businessDetail'),
			channelId:medtapCore.getRequest('channelId'),
			/*校验的参数*/
			check: ['userId'],
			/*需要校验的值*/
			valueForCheck: {},
			/*跳转的链接*/
			url: 'https://review-formal.iplusmed.com/wechatForLungCancer/prd/wechat_lung_login/formLogin.html',
			success: function() {
				console.log('子页面success');
			},
			error: function() {
				console.log('子页面error');
			}
		};

		var validate = {
			box: null,
			init: function() {
				validate.setCallBack();
				if(options.getInfo) {
					validate.getUserInfo();
				} else {
					var flg = false;
					for(var key in options.valueForCheck) {
						flg = true;
					}
					if(flg) {
						validate.check(options.valueForCheck);
					} else {
						throw new Error('请将getInfo属性设置为true，或设置valueForCheck属性');
					}
				}
			},
			/*创建用于验证的iframe*/
			createIframe: function() {
				var _bg = d.createElement('div'),
					_iframe = d.createElement('iframe'),
					_close = d.createElement('div');
				_bg.setAttribute('style', 'width: 100%;height: 100%;position: fixed;top: 0;left: 0;z-index: 1000;background-color: rgba(0,0,0,.3);');
				_bg.setAttribute('id', options.id);
				_iframe.setAttribute('style', 'width: 6.7rem;height: 90%;background-color: white;position: absolute;top: 5%;left: 0.40rem;border: none');
				_iframe.setAttribute('src', options.url + '?v=2.0.0&wechatId=' + options.wechatId + '&doctorId=' + options.doctorId + '&inviteCode=' + options.inviteCode + '&agencyId=' + options.agencyId + '&operationType=' + options.operationType + '&businessDetail=' + options.businessDetail + '&channelId=' + options.channelId);
				_iframe.setAttribute('id', '_beforeSubmitIframe');
				_close.setAttribute('style', 'position: absolute;top: 5%;right: 5%;width: 0.8rem;height: 0.8rem;color: #e0e0e0;z-index: 100;font-size: 0.40rem;text-align: center;line-height: 0.8rem;');
				_close.innerHTML = 'X';
				_close.onclick = function() {
					if(d.getElementById('_beforeSubmitIframe').getAttribute('src').indexOf('userLicens.html') > -1) {
						d.getElementById('_beforeSubmitIframe').setAttribute('src', options.url + '?v=1.0.0&wechatId=' + options.wechatId + '&doctorId=' + options.doctorId + '&inviteCode=' + options.inviteCode + '&agencyId=' + options.agencyId + '&operationType=' + options.operationType + '&businessDetail=' + options.businessDetail + '&channelId=' + options.channelId);
						return;
					}
					if(confirm('需要登录/注册才能继续提交。是否确定离开？')) {
						w._beforeSubmitClose();
					}
				};
				_bg.appendChild(_close);
				_bg.appendChild(_iframe);
				d.body.appendChild(_bg);
				validate.box = _bg;
			},
			/*回调函数设置*/
			setCallBack: function() {
				w._beforeSubmitSuccess = options.success;
				w._beforeSubmitError = options.error;
				w._beforeSubmitClose = function() {
					d.getElementById(options.id).style.display = 'none';
					//parent.location.reload();
				}
			},
			/*判断值是否存在*/
			check: function(info) {
				var flag = true;
				for(var key in options.check) {
					if(!(info.hasOwnProperty(options.check[key]) && (!!info[options.check[key]] || info[options.check[key]] === 0))) {
						flag = false;
						break;
					}
					if(options.check[key] === 'mobile') {
						var reg = /^1[0-9]{10}$/;
						flag = reg.test(info[options.check[key]]);
						if(!flag) break;
					}
				}
				/*校验失败*/
				if(!flag) {
					var _el = d.getElementById(options.id);
					!!_el ? (_el.style.display = 'block') : validate.createIframe();
				} else { /*校验成功*/
					w._beforeSubmitSuccess();
				}
			},
			getUserInfo: function() {
				var wechatId = medtapCore.getRequest('wechatId');
				var token = localStorage.wxLungToken;
				wechatId = !!wechatId ? wechatId : (
					localStorage.hasOwnProperty('appUserData') ? JSON.parse(localStorage['appUserData']).wechatId : (
						localStorage.hasOwnProperty('medtapGlobalData') ? JSON.parse(localStorage['medtapGlobalData']).wechatId : ''
					)
				);
				$.ajax({
					url: 'https://gateway.medtap.cn/wechat/user/getWechatUser',
					headers: {
						'apptype': 'wechat_lung',
						'user-os':'wechat',
						'token':token
					},
					type: 'get',
					data: medtapCore.setToken({
						wechatId:wechatId
					}),
					success: function(data) {
						if(data.success == true) {
							var info = data.content.wechatUser;
							validate.check(info);
						}else{
							alert(data.resultDesc);
						}
					},
					error: function(){
						alert('获取个人信息失败，请重试');
					}
				});
			}
		};

		var api = {
			config: function(opts) {
				if(!opts) return options;
				for(var key in opts) {
					options[key] = opts[key];
				}
				return this;
			},
			listen: function() {
				if(typeof elem === 'string') {
					var elems = document.querySelectorAll(elem),
						i = elems.length;
					while(i--) {
						listen(elems[i]);
					}
					return;
				}
				injector(elem, options.splitter);

				return this;
			},
			init: function() {
				validate.init();
			}
		}
		this.BeforeSubmit = api;
	})(window, document);

	return BeforeSubmit;
});