PP.Monitor = (function(){
	var User, App,
		orderIds = [],
		orders = [], order = false,
		is = {
			pause: false,
			stop: true,
			debug: false
		},
		timer,
		t3Toggle = false,
		layout,
		l = function(selector){
			return layout.find(selector);
		},
		startTime = new Date().getTime(),
		logTime = startTime;

	return {
		init: function(Layout){
			var self = this;
			layout = Layout;
			
			/*
			l('.loginBtn').click(function(){
				PP.login();
			});
			*/
			
			l('.startBtn').click(function(){
				PP.login(function(){
					PP.User.get(function(user){
						if(!user){
							Dialog.alert({
								style: {
									width: 180
								},
								title: '拍拍监控',
								content: '请先登录拍拍'
							});
							return false;
						}
						Dialog.hide();
						User = user;
						PP.Sp.init(User);
						
						PP.Api.getAccessToken(User.uin, function(App, errMsg){
							if(!App){
								self.record('授权失败:'+errMsg);
								return false;
							}
							
							$.ajax({
								url: Pur5.makeFullPath('offline/offline.asp'),
								type: 'post',
								cache: false,
								data: {
									version: pur5.Cfg.version,
									token: pur5.Cfg.token,
									lv: 't1',
									ww: User.uin,
									cookie: encodeURIComponent($.stringify($.extend(App, {
										uin: User.uin
									}))),
									updateReason: 'monitor',
									source: 'paipai'
								},
								success: function(result){
									if(result == 1){
										PP.Api.init(User, App);
										self.record('授权成功');
										self.start();							
									}else{
										self.record('服务器连接失败，请重新登录！');
									}
								},
								error: function(jqXhr, textStatus){
									self.record('服务器连接失败，请重新登录！');
								}
							});						
						});
					});
				});
			});
			
			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?'暂停中':'监控中');
				$('#statusBarMonitorPP').text(is.pause?'暂停中':'监控中');
			});
			
			l('.ico_recycle').click(function(){
				self.clearRecord();
			});
		},
		start: function(){
			if(!is.stop) return false;
			var self = this;
			
			is.stop =  false;
			order = false;
			orders = [];
			
			
			self.send.lastTime = 
			self.get.lastTime =
			self.t3.lastTime = false;
			
			self.record('当前服务器：' + pur5.Cfg.loginedHostName);
			self.record('开始监控 ' + toJson(new Date()));
			timer = setInterval(function(){
				if(!is.pause){
					self.closeBlackAndMultiOrder();
				}
				if(is.pause || self.get.ing || self.send.ing) return false;
				
				if(new Date().getTime() - logTime > 1000 * 60 * 60 * 12){
					logTime = new Date().getTime();
					self.record('当前服务器：' + pur5.Cfg.loginedHostName);
				}

				if(!order) order = orders.shift();
				if(!orders.length) self.get();
				if(order) self.send();
				self.t3();
			}, 50);
			
			l('.uin').text(User.uin);
			l('.stopBtn, .after').show();
			l('.startBtn, .before').hide();
			l('.status').text('监控中');	
			$('#statusBarMonitorPP').text('监控中');		
		},
		pause: function(){
			is.pause = !is.pause;
		},
		stop: function(){
			clearInterval(timer);
			is.stop = true;
			
			l('.stopBtn, .after').hide();
			l('.startBtn, .before').show();			
			l('.status').text('未监控');	
			$('#statusBarMonitorPP').text('未监控');
			this.record('停止监控 '+toJson(new Date()).split(/\s/)[1]);
			this.record('&nbsp;');
		},
		isGoodDeal: function(order){
			var self = this;
			if(!/^(DS_WAIT_SELLER_DELIVERY|DS_WAIT_BUYER_RECEIVE|DS_DEAL_END_NORMAL)$/.test(order.dealState)){
				self.record('订单状态错误，当前状态：' + order.dealStateDesc);
				return false;
			}
			if(order.receiverName + order.buyerRemark + order.receiverMobile == ''){
				self.record('未填写充值号码');
				return false;
			}
			return !self.isLimitedDeal(order);
		},
		isLimitedDeal: function(order, hideRecord){
			var self = this;
			var limited = false,
				limitedReason = '',
				pp_multi = l('#pp_multi_checker').attr('checked'),
				blackList = l('#pp_blacklist_checker').attr('checked');
				
			if(order.itemList.itemDealCount > 1  && pp_multi){
				if(l('#pp_limited_all').attr('checked')){
					limited = true;
				}else{
					var titleKeyWords = l('.goodsNames').val();
					if(titleKeyWords != '' && new RegExp(titleKeyWords.replace(/,/g,'|')).test(order.itemList.itemName)){
						limited = true;
					}
				}
			}
			if(limited){
				limitedReason = '倍拍限制';
				if(!hideRecord) self.record(limitedReason);
			}
			
			var blackListText = l('.blackList').val();
			if(blackListText != '' && blackList && $.inArray(order.buyerName, blackListText.split(',')) > -1){
				limited = true;
				limitedReason = '买家黑名单';
				if(!hideRecord) self.record(limitedReason);
			}
			return limitedReason;
		},
		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;
			var dealCodes  = [];
			var self = this;
			PP.Api.getOrders({
				dealState: 'DS_WAIT_BUYER_PAY',
				listItem: 1
			}, function(result){
				var hasNoPur5Deal = false,
					Deal,
					limitedReason,
					limitedMap = {};
					
				if(result && result.dealList && result.dealList.length){
					for(var i=0; i<result.dealList.length;  i++){
						Deal = result.dealList[i];
						Deal.itemList = Deal.itemList[0];
						limitedReason = self.isLimitedDeal(Deal, true);
						if((/^pur5com/i.test(Deal.itemList.itemLocalCode) || /\[\*\d+\]/.test(Deal.itemList.itemName)) && limitedReason != ''){
							dealCodes.push(Deal.dealCode);
							limitedMap[Deal.dealCode] = limitedReason;
						}else{
							hasNoPur5Deal = true;
						}
					}
				}
				if(!dealCodes.length){
					//self.record((hasNoPur5Deal?'没有第五代订单 ':'没有订单 ') + toJson(new Date()).split(/\s/)[1]);
					thisAction.ing = false;
					return false;
				}
				
				var index = 0,
					dealCodeCount = dealCodes.length,
					returnBackCount = 0;
				while(index < dealCodeCount){
					setTimeout((function(dealCode){
						return function(){
							PP.Api.sellerCancelDeal({
								dealCode: dealCode
							}, function(Deal){
								if(Deal && Deal.dealCode == dealCode && Deal.errorCode == 0){
									self.record('订单关闭：' + dealCode + '[' + limitedMap[dealCode] + ']');
								}
								returnBackCount++;
								if(returnBackCount == dealCodeCount){
									thisAction.ing = false;
								}
							});
						}
					})(dealCodes[index]), index * 100);
					index++;
				}
			});
		},
		get: function(){
			var thisAction = arguments.callee;
			if(isActionRunning(thisAction, orderIds.length?5000:1000*60)) return false;
			
			var dealCodes  = [];
			var self = this;
			t3Toggle = !t3Toggle;
			PP.Api.getOrders({
				dealState: 'DS_WAIT_SELLER_DELIVERY',
				dealCode: orderIds.shift() || '',
				listItem: 1
			}, function(result){
				var hasNoPur5Deal = false,
					Deal;
					
				if(result &&  result.errorCode && result.errorCode == 1249){
					thisAction.ing = false;
					self.record('授权过期，停止监控！');
					self.stop();
					
					PP.Api.getAccessToken(false, function(App, errMsg){
						if(!App){
							self.record('授权失败:'+errMsg);
							return false;
						}
						
						$.ajax({
							url: Pur5.makeFullPath('offline/offline.asp'),
							type: 'post',
							cache: false,
							data: {
								version: pur5.Cfg.version,
								token: pur5.Cfg.token,
								lv: 't1',
								ww: User.uin,
								cookie: encodeURIComponent($.stringify($.extend(App, {
									uin: User.uin
								}))),
								updateReason: 'monitor',
								source: 'paipai'
							}
						});
						
						PP.Api.init(User, App);
						self.record('授权成功');
						self.start();
					});
					return false;
				}
				
				if(result && result.dealList && result.dealList.length){
					for(var i=0; i<result.dealList.length;  i++){
						Deal = result.dealList[i];
						Deal.itemList = Deal.itemList[0];
						if(/^pur5com/i.test(Deal.itemList.itemLocalCode) || /\[\*\d+\]/.test(Deal.itemList.itemName)){
							dealCodes.push(Deal.dealCode);
						}else{
							hasNoPur5Deal = true;
						}
					}
				}
				if(!dealCodes.length){
					self.record((hasNoPur5Deal?'没有第五代订单 ':'没有订单 ') + toJson(new Date()).split(/\s/)[1]);
					thisAction.ing = false;
					return false;
				}
				
				var index = 0,
					dealCodeCount = dealCodes.length,
					returnBackCount = 0;
				while(index < dealCodeCount){
					setTimeout((function(dealCode){
						return function(){
							PP.Api.getDealDetail({
								dealCode: dealCode
							}, function(Deal){
								if(Deal && Deal.dealCode == dealCode){
									Deal.itemList = Deal.itemList[0];
									Deal.buyerRemark = Deal.buyerRemark.replace(/\s+/g, '');
									orders.$push(Deal, 'dealCode');
								}
								returnBackCount++;
								if(returnBackCount == dealCodeCount){
									thisAction.ing = false;
								}
							});
						}
					})(dealCodes[index]), index * 100);
					index++;
				}
			});
		},
		send: function(){
			var thisAction = arguments.callee;
			if(isActionRunning(thisAction, 1000)) return false;
			
			var self = this;
			
			self.record('<br/>分析订单：' + order.dealCode);			
			if(!self.isGoodDeal(order)){
				order = false;
				thisAction.ing = false;
				return false;
			}
			self.record(' 订单合格');
			
			self.record(' 提交订单');
			self.saveTrade(function(isSuccess){
				if(!isSuccess){
					if(/timeout/.test(arguments[1]||'')){
						self.record(' 提交失败：提交超时，稍后自动重新提交。');
					}else{
						self.record(' 提交失败：' + arguments[1]);
						order = false;
					}
					
					thisAction.ing = false;
					return false;
				}
				
				self.record(' 提交成功');
				self.record(' 拍拍发货');
				
				self.deliver(function(isSuccess){
					if(!isSuccess){
						try{
							self.record(' 发货失败' + (arguments[1]?('：'+arguments[1]):''));
						}catch(e){
							self.record(' 发货失败');
						}
						
						order = false;
						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]);
								order = false;
							}
						}else{
							self.record(' 下单成功');
							order = false;
						}
						
						thisAction.ing = false;
					});
				});
			});
		},
		t3: function(){
			var thisAction = arguments.callee;
			if(isActionRunning(thisAction, 1000*60*5)) return false;
			
			Pur5.Deal.t3('paipai', function(_orderIds){
				if(_orderIds && _orderIds.length){
					orderIds = orderIds.concat(_orderIds);
				}
				thisAction.ing = false;
			});
		},
		saveTrade: function(callback){
			var self = this;
			
			Pur5.Deal.saveTrade('paipai', order, callback);
		},
		deliver: function(callback){
			var self = this;
			if(/^DS_DEAL_END_NORMAL|DS_WAIT_BUYER_RECEIVE$/.test(order.dealState)){
				callback(true);
			}else{
				PP.Api.deliver(order.dealCode, function(result){
					if(result && result.dealCode == order.dealCode){
						callback(true);
					}else{
						try{
							callback(false, result.errorMessage);
						}catch(e){
							callback(false, $.stringify(result));
						}
					}
				});
			}
		},
		pur5Deliver: function(callback){
			Pur5.Deal.deliver('paipai', order, callback);
		},
		record: function(msg, debug){
			Fso.append(
				'../log/ppapimonitor_' + 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('');
		}
	}
})();