Tb.Api.Monitor = (function(){
	$.ajaxSetup({
		timeout: 30000
	});
	var User, App,
		authorise = false,
		orders = [], t3_orders = [], order = false,
		lastOrderTime,//上次抓到订单的时间
		is = {
			pause: false,
			stop: true,
			debug: false
		},
		timer,
		t3Toggle = false,
		layout,
		l = function(selector){
			return layout.find(selector);
		},
		startTime = new Date().getTime(),
		FailedId = {},
		logTime = startTime;
	
	return  {
		init: function(Layout){
			var self  = this;
			layout = Layout;
			l('.loginBtn').click(function(){
				authorise = false;
				self.record('获取授权');
				
				Tb.Api.authorise(function(userNickName){
					if(!userNickName){
						alert('授权失败，授权成功才能监控！');
						self.record('授权失败');
						return false;
					}
					
					l('.uin').text(userNickName);
					self.record('授权成功：' + userNickName);
					authorise = true;
					self.start();
				}, '开始监控[{1}]？');
			});
			
			l('.startBtn').click(function(){
				if(authorise){
					self.start();
				}
			});
			
			l('.stopBtn').click(function(){
				self.stop();
			});
			
			l('.pause_checker').click(function(){
				if(is.stop) return false;
				is.pause = this.checked;
				l('.status').text(is.pause?'暂停中':'监控中');
				$('#statusBarMonitorTB').text(is.pause?'暂停中':'监控中');
			});
			
			l('.ico_recycle').click(function(){
				self.clearRecord();
			});
			
			l('.noorderwarn').click(function(){
				if(this.checked){
					lastOrderTime = new Date().getTime();
				}
			});
			
			l('.tip1').click(function(){
				Dialog.alert({
					content: '自动关闭倍拍未付款订单；<br />填写好商品名称关键字或者不区分关键字选择全部关闭'
				});
			});
			
			l('.seekNoPayBtn').click(function(){
				var This = $(this);
				if(This.attr('ing')) return false;
				This.attr('ing', 1);
				Dialog.alert({
					content: '数据加载中…',
					style: {
						width: 200,
						height: 50
					}
				});
				Tb.Api.getNoPayOrders({}, function(result){
					
					This.removeAttr('ing');
					var hasNoPur5Deal = false,
						Deal,
						limitedReason,
						limitedMap = {},
						Result = [];
						
					if(result && result.length && result[0].adjust_fee){
						for(var i=0; i<result.length; i++){
							Deal = result[i];
							Deal.order = Deal.orders.order[0];
							delete Deal.orders;
							limitedReason = self.isLimitedDeal(Deal, true);
							if(/^pur5.com/i.test(Deal.order.outer_iid)){
								//dealCodes.push(Deal.tid);
								Result.push({
									title: Deal.order.title,
									wangwang: Deal.buyer_nick,
									price: Deal.total_fee,
									created: Deal.created
								});
								limitedMap[Deal.tid] = limitedReason;
							}else{
								hasNoPur5Deal = true;
							}
						}
					}
					
					if(!Result.length){
						Dialog.alert({
							content: '没有未付款的订单',
							style: {
								width: 200,
								height: 50
							}
						});
						return false;
					}
					Dialog.alert({
						title: '<span style="color: #f00; font-weight: bold;">以下为未付款订单，请注意骗子，未付款的订单不要去软件里手工充值</span>',
						content: l('.noPayList')[0].outerHTML,
						style: {
							height: 350,
							width: 650,
							border: '1px solid #67080f'
						},
						action: function(content, layout){
							content.find('.noPayList').addClass('gridview').gridview().trigger('refresh', [{
								list: Result,
								page: {
									page_no: 6,
									page_size: 40,
									count: 1000
								},
								pageAction: function(page_no){
									alert(page_no);
								}
							}]);
						}
					});
				});
			});
		},
		start: function(){
			if(!is.stop) return false;
			var self = this;
			
			is.stop = is.pause = false;
			order = false;
			orders = [];
			t3_orders = [];
			lastOrderTime = new Date().getTime();
			clearInterval(timer);
			
			l('.pause_checker').attr('checked', false);
			l('.stopBtn, .after, .wangwang').show();
			l('.startBtn, .before').hide();
			l('.status').text('监控中');	
			$('#statusBarMonitorTB').text('监控中');		

			self.get.ing =
			self.send.ing = false;
			self.record('当前服务器：' + pur5.Cfg.loginedHostName);
			self.record('开始监控 ' + toJson(new Date()));
			timer = setInterval(function(){
				if(!is.pause){
					self.closeBlackAndMultiOrder();
					self.t3();
					self.autoRate();
					self.refreshSession();
				}

				if(is.pause || self.get.ing || self.send.ing || self.refreshSession.ing) return false;
				
				if(new Date().getTime() - logTime > 1000 * 60 * 60 * 12){
					logTime = new Date().getTime();
					self.record('当前服务器：' + pur5.Cfg.loginedHostName);
				}

				if(!order) order = (function(){
					t3Toggle = !t3Toggle;
					if(t3Toggle || !t3_orders.length){
						return orders.shift();
					}else{
						return t3_orders.shift();
					}
				})();
				if(!order){
					self.get();
				}else{
					order.tryCount = 0;
					self.send();
				}
			}, 50);
		},
		stop: function(){
			clearInterval(timer);
			is.stop = true;
			
			l('.stopBtn, .after, .wangwang').hide();
			l('.startBtn, .before').show();			
			l('.status').text('未监控');	
			$('#statusBarMonitorTB').text('未监控');	
			this.record('停止监控');
		},
		get: function(){
			var thisAction = arguments.callee;
			if(isActionRunning(thisAction, 1000*60)) return false;
			
			var	self = this,
				dealCodes = [];
			Tb.Api.getOrders({}, function(result, errMsg){
				if(errMsg){
					self.record('抓单出错：'+(/timeout/.test(errMsg)?'超时！':errMsg));
				}
				
				try{//授权过期
					if(result.error_response.code == 27){
						self.record('授权失效');
						self.stop();
						return false;
					}
				}catch(e){}
				
				var hasNoPur5Deal = false,
					Deal;
					
				if(result && result.length && result[0].adjust_fee){
					for(var i=0; i<result.length; i++){
						Deal = result[i];
						Deal.order = Deal.orders.order[0];
						delete Deal.orders;
						if(/^pur5.com/i.test(Deal.order.outer_iid)){
							dealCodes.push(Deal.tid);
						}else{
							hasNoPur5Deal = true;
						}
					}
				}

				if(!dealCodes.length){
					self.record((hasNoPur5Deal?'没有第五代订单 ':'没有订单 ') + toJson(new Date()).split(/\s/)[1]);
					try{//无单报警
						var noorderTime = l('.noorderTime').val()-0;
						if(l('.noorderwarn').attr('checked')){
							if((new Date().getTime()-lastOrderTime)/1000/60 > noorderTime){
								UI.pop('在指定时间[' + noorderTime + '分钟]内无订单！');
							}
						}
					}catch(e){}
					thisAction.ing = false;
					return false;
				}
				
				lastOrderTime = new Date().getTime();
				
				var index = 0,
					dealCodeCount = dealCodes.length,
					returnBackCount = 0;
				while(index < dealCodeCount){
					setTimeout((function(dealCode){
						return function(){
							Tb.Api.getDealDetail(dealCode, function(result){
								if(result && result.tid == dealCode && /^WAIT_SELLER_SEND_GOODS|WAIT_BUYER_CONFIRM_GOODS|TRADE_FINISHED$/.test(result.status)){
									result.receiver_address = result.receiver_address.replace(/\s+/g, '');
									orders.$push(result, 'tid');
								}
								returnBackCount++;
								if(returnBackCount == dealCodeCount){//alert(orders.length);
									thisAction.ing = false;
								}
							});
						}
					})(dealCodes[index]), index * 200);
					index++;
				}
			});			
		},
		send: function(){
			var self = this, thisAction = arguments.callee;
			if(isActionRunning(thisAction, 1000)) return false;

			self.record('<br/>分析订单：' + order.tid + ' ' + toJson(new Date()));		
			if(FailedId[order.tid]){
				self.record('订单失败：' + FailedId[order.tid].errMsg);
				order = false;
				thisAction.ing = false;
				return false;
			}

			//if(order.status == 'TRADE_CLOSED'){//todo:删除trading
			if(order.order.refund_status !== 'NO_REFUND'){//有退款的就不给发货
				self.record('提示：此订单申请了退款，不能自动发货，请去淘宝处理。');
				order = false;
				thisAction.ing = false;
				return false;
			}
			
			if(!self.isGoodDeal(order)){
				order = false;
				thisAction.ing = false;
				return false;
			}
			self.record(' 订单合格');
			
			self.record(' 提交订单');
			self.saveTrade(function(isSuccess){
				var setNull = false;
				if(!isSuccess){
					if(/timeout/.test(arguments[1]||'')){
						self.record(' 提交失败：提交超时，稍后自动重新提交。');
					}else{
						self.record(' 提交失败：' + arguments[1] + ' ' + toJson(new Date()));
						setNull = true;
					}
					
					if('1005' == arguments[2] || '1004' == arguments[2]){
						if(!/^pur5.com[：:](1[0-9]|20)$/.test(order.order.outer_iid)){
							FailedId[order.tid] = {
								errMsg: arguments[1] || ''
							}
						}
						
						setNull = true;
					}
					
					if(setNull){
						order = false;
					}
					
					thisAction.ing = false;
					return false;
				}

				self.record(' 提交成功');
				self.record(' 淘宝发货');
				
				self.deliver(function(isSuccess){
					if(!isSuccess){
						if(/timeout/.test(arguments[1]||'')){
							self.record(' 发货失败：淘宝超时，稍后自动重发。');
						}else{
							self.record(' 发货失败' + (arguments[1]?(':'+arguments[1]):'') + ' ' + toJson(new Date()));
						}
						
						thisAction.ing = false;
						return false;
					}
					self.record(' 发货成功');
					self.record(' 平台下单');
					
					self.pur5Deliver(function(isSuccess){
						if(!isSuccess){
							if(/timeout/.test(arguments[1]||'')){
								self.record(' 下单失败：下单超时，稍后自动重新下单。');
							}else{
								self.record(' 下单失败：' + arguments[1]　+ ' ' + toJson(new Date()));
								order = false;
							}
						}else{
							self.record(' 下单成功');
							order = false;
						}
						
						thisAction.ing = false;						
					});
				});
			});
		},
		refreshSession: function(){
			var thisAction = arguments.callee;
			if(isActionRunning(thisAction, 1000 * 60 * 60 * 10)) return false;
			
			var self = this;
			Tb.Api.refreshSession(function(){
				thisAction.ing = false;
			});
		},
		t3: function(){
			var thisAction = arguments.callee;
			if(isActionRunning(thisAction, 1000*60*5)) return false;
			
			Pur5.Deal.t3('taobao', function(orderIds){
				var index = 0,
					dealCodeCount = orderIds.length,
					returnBackCount = 0;
				while(index < dealCodeCount){
					setTimeout((function(dealCode){
						return function(){
							Tb.Api.getDealDetail(dealCode, function(result){
								if(result && result.tid == dealCode && /^WAIT_SELLER_SEND_GOODS|WAIT_BUYER_CONFIRM_GOODS|TRADE_FINISHED$/.test(result.status)){
									result.receiver_address = result.receiver_address.replace(/\s+/g, '');
									t3_orders.$push(result, 'tid');
								}
								returnBackCount++;
								if(returnBackCount == dealCodeCount){
									thisAction.ing = false;
								}
							});
						}
					})(orderIds[index]), index * 200);
					index++;
				}
			});
		},
		closeBlackAndMultiOrder: function(){
			var multi = l('.mult_limited_checker').attr('checked'),
				blackList = l('.blacklist_checker').attr('checked');
			if(!multi && !blackList){
				return  false;
			}
			
			var thisAction = arguments.callee;
			if(isActionRunning(thisAction, 1000*5)) return false;
			
			var	self = this,
				dealCodes = [];
			Tb.Api.getNoPayOrders({}, function(result){
				var hasNoPur5Deal = false,
					Deal,
					limitedReason,
					limitedMap = {};
					
				if(result && result.length && result[0].adjust_fee){
					for(var i=0; i<result.length; i++){
						Deal = result[i];
						Deal.order = Deal.orders.order[0];
						delete Deal.orders;
						limitedReason = self.isLimitedDeal(Deal, true);
						if(/^pur5.com/i.test(Deal.order.outer_iid) && limitedReason != ''){
							dealCodes.push(Deal.tid);
							limitedMap[Deal.tid] = limitedReason;
						}else{
							hasNoPur5Deal = true;
						}
					}
				}

				if(!dealCodes.length){
					thisAction.ing = false;
					return false;
				}
				
				var index = 0,
					dealCodeCount = dealCodes.length,
					returnBackCount = 0;
				while(index < dealCodeCount){
					setTimeout((function(dealCode){
						return function(){
							var limitedReason = limitedMap[dealCode];
							if(limitedReason == '倍拍限制'){
								limitedReason = '信息填写错误，重新拍';
							}
							Tb.Api.closeOrder(dealCode, limitedReason, function(result){
								if(result){
									self.record('订单关闭：'+dealCode + '['+limitedMap[dealCode]+']');
								}
								returnBackCount++;
								if(returnBackCount == dealCodeCount){//alert(orders.length);
									thisAction.ing = false;
								}
							});
						}
					})(dealCodes[index]), index * 50);
					index++;
				}
			});			
		},
		autoRate: function(){
			var content = ''+l('.autocomment_text').val();
			if(!l('.autocomment_checker').attr('checked') || content == ''){
				return  false;
			}
			var thisAction = arguments.callee;
			if(isActionRunning(thisAction, 1000*60)) return false;
			
			var self = this
			Tb.Api.getNeedRateTids(function(tids){
				if(tids && tids.length){
				}else{
					thisAction.ing = false;
					return false;
				}
				
				var index = 0,
					tidsCount = tids.length,
					returnBackCount = 0;
				while(index < tidsCount){
					setTimeout((function(dealCode){
						return function(){
							Tb.Api.rate(dealCode, content, function(result, errMsg){
								try{
									if(result){
										self.record('评价成功：订单号=' + dealCode);
									}else{
										//self.record('评价失败：订单号=' + dealCode + errMsg?('原因='+errMsg):'');
									}
								}catch(e){}
								
								returnBackCount++;
								if(returnBackCount == tidsCount){//alert(orders.length);
									thisAction.ing = false;
								}
							});
						}
					})(tids[index]), index * 100);
					index++;
				}
			});
		},
		isGoodDeal: function(){
			var self = this;
			if(!/^(WAIT_SELLER_SEND_GOODS|WAIT_BUYER_CONFIRM_GOODS|TRADE_FINISHED)$/.test(order.order.status)){
				self.record('订单状态错误，当前状态：' + order.order.status);
				return false;
			}
			return self.isLimitedDeal(order) == '';			
		},
		isLimitedDeal: function(order, hideRecord){
			var self = this;
			var limited = false,
				limitedReason = '',
				multi = l('.mult_limited_checker').attr('checked'),
				blackList = l('.blacklist_checker').attr('checked');
				
			if(order.num > 1 && multi){
				if(l('.multi_limited_all').attr('checked')){
					limited = true;
				}else{
					var titleKeyWords = l('.goodsNames').val();
					if(titleKeyWords != '' && new RegExp(titleKeyWords.replace(/,/g,'|')).test(order.order.title)){
						limited = true;
					}
				}
			}
			if(limited && !hideRecord) self.record('限倍拍');
			if(limited){
				limitedReason = '倍拍限制';
			}
			
			var blackListText = l('.blackList').val();
			if(blackList && $.inArray(order.buyer_nick, blackListText.split(',')) > -1){
				limited = true;
				limitedReason = '黑名单限制';
				if(!hideRecord) self.record('买家黑名单');
			}
			return limitedReason;
		},
		saveTrade: function(callback){
			Pur5.Deal.saveTrade('taobao', order, callback);
		},
		deliver: function(callback){
			if(/^WAIT_BUYER_CONFIRM_GOODS|TRADE_FINISHED$/.test(order.status)){
				callback(true);
			}else{
				Tb.Api.deliver(order.tid, callback);
			}
		},
		pur5Deliver: function(callback){;
			Pur5.Deal.deliver('taobao', order, callback);
		},
		record: function(msg, debug){
			Fso.append(
				'../log/tbapimonitor_' + toJson(new Date()).split(/\s/)[0] + '-' + logTime + '.pur5',
				'\r\n' + msg
			);
			
			if(debug && !is.debug) return false;
			var record = l('.record'),
				recordCount = record.find('p').length;
			if(recordCount > 50){
				this.clearRecord();
			}
			
			record.append('<p>' + msg + '</p>');
			if(l('.scroll_checker').attr('checked')){
				record.scrollTop(recordCount * 60);
			}			
		},
		clearRecord: function(){
			l('.record').html('');
		}
	}
})();