var ptlogin2_onSuccess = function(){
	PP.Api.logined = true;
};
PP.Api = (function(){
	var appId = 168115,
		appOAuthId = '700039662',
		secretOAuthKey = 'SRBhE5hMlpKIHbHC',
		accessToken= '',
		uin = '';
	var User = {}, App = {};
	
	return {
		init: function(user, app){
			User = user,
			App = app;
			
			accessToken = App.accessToken,
			uin = User.uin;
		},
		request: function(cid, arg, callback){
			var arg = $.extend({
				timeStamp: new Date().getTime(),
				randomValue: parseInt(1000000 + Math.random() * 1e6),
				uin: User.uin,
				accessToken: App.accessToken,
				appOAuthID: App.appOAuthID,
				sellerUin: User.uin,
				charset: 'utf-8',
				pureData: 1,
				_: new Date().getTime()
			}, arg),
			sign = (function(){
				var data = [];
				$.each(arg, function(key, val){
					data.push(key + '=' + val);
				});
				data.sort();
				
				var data2 = ['POST'];
				data2.push(encodeURIComponent('/' + cid.replace(/\./g, '/') + '.xhtml'));
				data2.push(encodeURIComponent(data.join('&')));
				return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(data2.join('&'), (App.secretOAuthKey || secretOAuthKey) + '&'));
			})(),
			url = str_replace('http://api.paipai.com/{1}.xhtml', cid.replace(/\./g, '/'));
			
			$.ajax({
				url: url,
				type: 'post',
				dataType: 'json',
				data: $.extend(arg, {
					sign: sign
				}),
				success: function(data, jqXhr, textStatus){
					callback(data);
				},
				error: function(jqXhr, textStatus){
					var data;
					try{
						data = (new Function("return " + $.trim(jqXhr.responseText)))();
					}catch(e){}
					callback(data);
				}
			});
		},
		getAccessToken: function(userid, callback){
			var self = this;
			var getAccessTokenIframe = function(){
				var successArr = [
						'&#24744;&#24050;&#32463;&#35746;&#36141;&#20102;&#35813;&#24212;&#29992;'
					],
					accessTokenReg = /access_token=(\w+)/,
					step = 0,
					lastMsg = '';
				Dialog.alert({
					title: '拍拍授权',
					content: '授权中……<iframe style="display:none;" width="800" height="550" frameborder="0" application="yes" src="http://fuwu.paipai.com/my/app/orderApp.xhtml?agree=1&appId=' + appId + '&r=' + Math.random() + '"></iframe>',
					style: {
						width: 180
					},
					action: function($content){
						$content.find('iframe').load(function(){
							step++;
							var Win = this.contentWindow,
								lastMsg = msg = Win.msg,
								$doc = $(Win.document);
								
								if(Win.location.href.indexOf('access_token') > -1){
								//try{
									var accessToken;
									 accessToken = Win.location.href.match(accessTokenReg)[1];
									if(accessToken){
										Dialog.hide();
										
										
										callback({
											accessToken: accessToken,
											secretOAuthKey: secretOAuthKey,
											appOAuthID: appOAuthId
										});
										return false;
									}
								//}catch(e){alert([e.description, Win.location.href]);}
								}
	
							if($.inArray(msg, successArr) > -1 || $doc.find('.tips_title>strong').text() == '应用订购成功'){
								Win.location = 'http://fuwu.paipai.com/my/app/authorizeGetAccessToken.xhtml?responseType=access_token&appOAuthID=' + appOAuthId;
							}else{
								Dialog.alert({
									title: '拍拍授权',
									content: '授权失败：'+lastMsg,
									style: {
										width: 180
									}
								});
							}
						});
					},
					button: {
						'确 定': false
					}
				});				
			};
			
			if(userid){
				Dialog.normalAlert('拍拍授权', '读取拍拍授权信息……');
				Pur5.get({
					action: 'getCookiesForUid',
					token: Pur5.getToken(),
					uid: Pur5.getUserId(),
					source: 'paipai',
					account: encodeURI(userid)
				}, function(Result, errMsg){
					if(Result && Result.paipai && Result.paipai.uin == userid){
						self.testAccessToken({
							uin: Result.paipai.uin,
							accessToken: Result.paipai.accessToken,
							appOAuthID: Result.paipai.appOAuthID,
							sellerUin: Result.paipai.uin
						}, function(success){
							if(!success){
								getAccessTokenIframe();
							}else{
								Dialog.hide();
								callback(Result.paipai);
							}
						});
					}else{
						getAccessTokenIframe();
					}
				});
			}else{
				getAccessTokenIframe();
			}		
		},
		testAccessToken: function(arg, cb){
			PP.Api.getOrders($.extend({
				dealState: 'DS_WAIT_BUYER_PAY',
				listItem: 1
			}, arg), function(Result){
				if(Result && Result.pageIndex && Result.pageIndex == 1){
					cb(true);
				}else{
					cb(false);
				}
			});
		},
		getOrders: function(arg, callback){//根据标识取客户订单
			this.request('deal.sellerSearchDealList', $.extend({}, arg), callback);
		},
		deliver: function(dealCode, callback){//订单发货
			this.request('deal.sellerConsignDealItem', {
				dealCode: dealCode,
				logisticsName: 'NO'//无需物流
			}, callback);
		},
		getDealDetail: function(arg, callback){
			this.request('deal.getDealDetail', $.extend({
				listItem: 1
			}, arg), callback);
		},
		sellerCancelDeal: function(arg, callback){
			this.request('deal.sellerCancelDeal', $.extend({
				closeReason: 2
			}, arg), callback);
		}
	}
})();