Tb.Api = (function() {
	var appkey = '12444247',
		appsecret = '',
		signOnClient = false,
		dataCache = {
			WAIT_SELLER_SEND_GOODS: {},
			WAIT_BUYER_PAY: {},
			RATE_UNSELLER: {},
			RATE_BUYER_UNSELLER: {}
		},
		timeDiffTaobao = 0,
		getApiError = function(result) {
			var errMsg = '';
			try {
				errMsg = '错误：' + result.error_response.msg;
				errMsg += result.error_response.sub_msg ? ('；子错误：' + result.error_response.sub_msg) : '';
			} catch (e) {}

			var callerArg = arguments.callee.caller.arguments;

			try {
				if (callerArg[1]) errMsg += 'response=' + callerArg[1];
			} catch (e) {}

			try {
				if (callerArg[2]) errMsg += ';textStatus=' + callerArg[2];
			} catch (e) {}

			return errMsg;
		},
		callbackArg = {};

	return {
		setAppkey: function(Appkey) {
			appkey = Appkey;
		},
		getAppkey: function() {
			return appkey;
		},
		getArg: function() {
			return callbackArg;
		},
		authorise: function(callback, actionString) {
			var self = this,
				success = function(html) {
					var authoriseSuccess = false;
					try {
						var arr = $.parseJSON(html);
						callbackArg = {
							session: arr[0],
							refresh_token: arr[7].match(/refresh_token=([^&]+)&/)[1],
							refresh_time: new Date().getTime(),
							REFRESH_SESSION_URL: arr[7],
							userNickName: arr[5],
							wwId: arr[8]
						};
						authoriseSuccess = true;
					} catch (e) {}

					if (authoriseSuccess) {
						Dialog.normalAlert('请等待', '正在读取店铺信息……');
						Tb.Api.request('taobao.shop.get', {
							nick: callbackArg.userNickName,
							fields: 'sid, cid, nick, title, desc, bulletin, pic_path, created, modified, shop_score'
						}, function(result, errMsg) {
							Dialog.hide();
							var Shop,
								userHaveNoShop  =  false;
							try {
								Shop = result.shop_get_response.shop;
							} catch (e) {}

							if (!Shop) {
								if (($.stringify(result) || '').indexOf('user-without-shop') > -1) {
									userHaveNoShop = true;
/*									Tb.Api.request('taobao.increment.customer.stop', {
										nick: callbackArg.userNickName,
										type: 'get,syn,notify'
									}, function() {
										Tb.User.cancelAuthorise({
											appId: 445470,
											callback: function(cancelAuthoriseResult) {}
										});
									});
									Dialog.normalAlert(
										'授权失败',
										'当前登录旺旺 [<strong style="color:#f00;">' + callbackArg.userNickName + '</strong>] 没有开店！');
*/
								} else {
									var err = getApiError(result);
									Dialog.alert({
										title: '读取店铺信息失败',
										content: '失败原因：' + (/timeout/.test(err) ? '超时！' : err),
										style: {
											width: 250
										}
									});
								}

								//return false;
							}

							self.getTaobaoTime(function(time) {
								if (callback.toString().indexOf('监控') == -1) { //不是监控才订阅
									Tb.Api.request('taobao.increment.customer.permit', {
										type: 'get,syn,notify'
									}, function() {
										callback(callbackArg.userNickName);
									});
								} else {
									$.ajax({ //托管
										url: pur5.Cfg.GBHOSTSOFT + 'offline/offline.asp?updateSessionOnMonitor',
										type: 'post',
										cache: false,
										data: {
											token: pur5.Cfg.token,
											lv: 't1',
											updateReason: 'monitor',
											source: 'taobao',
											ww: encodeURIComponent(callbackArg.userNickName),
											wwId: callbackArg.wwId,
											cookie: encodeURIComponent($.stringify({
												session: callbackArg.session,
												refresh_token: callbackArg.session,
												refresh_time: new Date().getTime()
											}))
										}
									});
									callback(callbackArg.userNickName);
								}
							});
						});
					} else {
						setTimeout(function() {
							Dialog.alert({
								title: '淘宝店铺授权结果',
								content: '店铺授权失败！',
								style: {
									width: 250
								}
							});
						}, 10);
					}
				},
				authoriseFunc = function() {
					var returnUrl = Pur5.makeFullPath('offline/TaobaoApiBack.asp');
					Dialog.superIframe({
						title: '淘宝授权',
						src: 'http://container.api.taobao.com/container?' + $.param({
							scope: 'item,usergrade',
							appkey: appkey,
							token: Pur5.getToken(),
							serverHttp: Pur5.makeFullPath(''),
							appType: 'dwdClient',
							returnUrl: returnUrl
						}),
						style: {
							width: 370,
							height: 230
						},
						action: function($doc, Win, $content, layout) {
							var url = Win.location.href,
								html = $doc.find('body').html(),
								confirmReg = 'http://container.api.taobao.com/container',
								callbackUrlReg = /http:\/\/[^\/]+\/pages\/offline\/TaobaoApiReback.Temp.asp/,
								successTag = 'PUR5[授权成功]';

							if (url.indexOf(confirmReg) > -1) {
								$doc.css({
									overflow: 'hidden'
								}).find('body').find('.header').end()
									.find('.content').find('.img_text, .cont, .auth_option, #more').hide().end()
									.find('.change_user a').click(function() {
									setTimeout(function() {
										self.authorise(callback);
									}, 0);
									return false;
								});

								var size = {
									width: 500,
									height: 320
								};

								/*
								$content.children().eq(0).css(size);
								
								layout.css({
									'margin-left': size.width/2*-1,
									'margin-top': size.height/2*-1
								});
								*/
							} else if (callbackUrlReg.test(url)) {
								Win.location = url.replace(callbackUrlReg, returnUrl);
							}

							if (html.indexOf(successTag) > -1) {
								success($doc.find('body').text());
								Dialog.hide();
							}
						},
						button: {
							'确 定': false
						}
					});
				};


			Tb.User.login(function(loginedNick) {
				authoriseFunc();
			});
		},
		getSign: function(method, stringForSign, callback) {
			$.ajax({
				url: Pur5.makeFullPath('offline/taobaoapisign.asp?' + method),
				type: 'post',
				dataType: 'text',
				cache: false,
				data: {
					a: 'getsign',
					v: stringForSign,
					token: Pur5.getToken()
				},
				success: function(result) {
					callback(result);
				},
				error: function(jqXhr, textStatus) {
					//alert(['签名错误', this.url, $.stringify(this.data)]);
					callback(false, jqXhr.responseText);
				}
			});
		},
		request: function(method, arg, callback) {
			var arg = $.extend({
				method: method,
				timestamp: toJson(new Date(new Date() - timeDiffTaobao)),
				format: 'json',
				app_key: appkey,
				session: callbackArg.session,
				v: '2.0'
			}, arg),
				sign = (function() {
					var data = [];
					$.each(arg, function(key, val) {
						data.push('' + key + val);
					});

					data.sort();
					data.unshift(appsecret);
					return $.md5(data.join('')).toUpperCase();
				})(),
				stringForSign = (function() {
					var data = [];
					$.each(arg, function(key, val) {
						data.push('' + key + val);
					});

					data.sort();
					return data.join('');
				}()),
				url = 'http://gw.api.taobao.com/router/rest',
				func = function(data) {
					$.ajax({
						url: url,
						type: 'post',
						timeout: 1000 * 30,
						dataType: 'json',
						data: data,
						success: function(data, textStatus, jqXhr) {
							callback(data);
						},
						error: function(jqXhr, textStatus) {
							var data;
							try {
								data = (new Function("return " + $.trim(jqXhr.responseText).replace(/[\r\n]/g, ' ')))();
							} catch (e) {}
							callback(data, jqXhr.responseText, textStatus);
						}
					});
				}

			if (signOnClient) {
				func($.extend(arg, {
					sign: sign
				}));
				return false;
			}

			if (method == 'taobao.trades.sold.get') {
				if (/^WAIT_BUYER_PAY|WAIT_SELLER_SEND_GOODS$/.test(arg.status) && dataCache[arg.status].data && new Date().getTime() - dataCache[arg.status].time < 1000 * 60 * 60 * 4) {
					func(dataCache[arg.status].data);
					return false;
				}
				if (/^RATE_UNSELLER|RATE_BUYER_UNSELLER$/.test(arg.rate_status) && dataCache[arg.rate_status].data && new Date().getTime() - dataCache[arg.rate_status].time < 1000 * 60 * 60 * 4) {
					func(dataCache[arg.rate_status].data);
					return false;
				}
			}

			this.getSign(method, stringForSign, function(sign, errMsg) {
				if (!/^[\dA-Z]{32}$/.test(sign)) {
					//alert('淘宝API参数签名错误:' + sign);
					//return false;
					callback(false, errMsg);
				} else {
					var data = $.extend(arg, {
						sign: sign
					});

					method == 'taobao.trades.sold.get' && ! function() {
						if (/^WAIT_BUYER_PAY|WAIT_SELLER_SEND_GOODS$/.test(arg.status)) {
							dataCache[arg.status].data = data,
							dataCache[arg.status].time = new Date().getTime()
						}
						if (/^RATE_UNSELLER|RATE_BUYER_UNSELLER$/.test(arg.rate_status)) {
							dataCache[arg.rate_status].data = data,
							dataCache[arg.rate_status].time = new Date().getTime()
						}

					}();
					func(data);
				}
			});
		},
		refreshSession: function(callback) {
			var self = this;

			$.extend(callbackArg, {
				refresh_time: new Date().getTime()
			});

			$.ajax({
				url: callbackArg.REFRESH_SESSION_URL,
				type: 'post',
				dataType: 'json',
				success: function(result) {
					this.callbackFn(result);
				},
				error: function(jqXhr) {
					var result;
					try {
						result = (new Function("return " + $.trim(jqXhr.responseText)))();
					} catch (e) {}
					this.callbackFn(result);
				},
				callbackFn: function(result) {
					if (result && result.sign && result.top_session) {
						self.refreshUrl(function(flag) {
							if (flag) {
								dataCache = {
									WAIT_SELLER_SEND_GOODS: {},
									WAIT_BUYER_PAY: {},
									RATE_UNSELLER: {},
									RATE_BUYER_UNSELLER: {}
								};
							}
							callback(flag);
						});
					} else {
						callback();
					}
				}
			});
		},
		refreshUrl: function(cb) { //session更新完需要更新抓单地址
			var self = this;
			$.ajax({
				url: Pur5.makeFullPath('offline/TaobaoApiBack.asp'),
				type: 'get',
				dataType: 'json',
				data: {
					top_appkey: appkey,
					top_parameters: $.param({
						refresh_token: callbackArg.refresh_token,
						visitor_nick: callbackArg.userNickName
					}),
					pur5_type: 1,
					top_session: callbackArg.session,
					dataType: 'json',
					t: new Date().getTime(),
					serverHttp: '',
					top_sign: ''
				},
				success: function(arr) {
					try {
						$.extend(callbackArg, {
							session: arr[0],
							refresh_token: arr[7].match(/refresh_token=([^&]+)&sessionkey/)[1],
							REFRESH_SESSION_URL: arr[7]
						});
						cb(true);
					} catch (e) {
						cb(false);
					}
				},
				error: function() {
					cb(false);
				}
			});
		},
		getNeedRateTids: function(callback) {
			var tids = [],
				ajaxResult = 0,
				resultFunc = function(result) {
					try {
						var trade = result.trades_sold_get_response.trades.trade;
						for (var i = 0; i < trade.length; i++) {
							if (trade[i].orders.order.length != 1) continue;
							if (!/^pur5.com[：\:]/.test(trade[i].orders.order[0].outer_iid)) continue;

							if ($.inArray(trade[i].tid, tids) == -1) {
								tids.push(trade[i].tid);
							}
						}
					} catch (e) {}

					ajaxResult++;
					if (ajaxResult === 2) {
						callback(tids);
					}
				};

			this.request('taobao.trades.sold.get', {
				start_created: toJson(new Date(new Date() - timeDiffTaobao - (1000 * 60 * 60 * 24 * 15))),
				status: 'TRADE_FINISHED',
				rate_status: 'RATE_BUYER_UNSELLER',
				fields: 'tid,orders'
			}, resultFunc);

			this.request('taobao.trades.sold.get', {
				start_created: toJson(new Date(new Date() - timeDiffTaobao - (1000 * 60 * 60 * 24 * 15))),
				status: 'TRADE_FINISHED',
				rate_status: 'RATE_UNSELLER',
				fields: 'tid,orders'
			}, resultFunc);
		},
		rate: function(tid, content, callback) {
			this.request('taobao.traderate.add', {
				tid: tid,
				result: 'good',
				role: 'seller',
				content: content
			}, function(result) {
				var rateResult;
				try {
					rateResult = (result.traderate_add_response.trade_rate.tid == tid);
				} catch (e) {}

				callback(rateResult, getApiError(result));
			});
		},
		getOrders: function(arg, callback) {
			this.request('taobao.trades.sold.get', {
				status: 'WAIT_SELLER_SEND_GOODS',
				use_has_next: 'true',
				page_size: 100,
				start_created: toJson(new Date(new Date() - timeDiffTaobao - (1000 * 60 * 60 * 24 * 5))),
				fields: 'seller_nick, buyer_nick, title, type, created, tid, seller_rate,buyer_flag, buyer_rate, status, payment, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, commission_fee, buyer_memo, seller_memo, alipay_no, buyer_message, pic_path, num_iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email,seller_flag, seller_alipay_no, seller_mobile, seller_phone, seller_name, seller_email, available_confirm_fee, has_post_fee, timeout_action_time, snapshot_url, cod_fee, cod_status, shipping_type, trade_memo, is_3D,buyer_memo,buyer_email,orders'
			}, function(result) {
				var trade;
				try {
					trade = result.trades_sold_get_response.trades.trade;
				} catch (e) {}

				callback(trade, getApiError(result));
			});
		},
		getNoPayOrders: function(arg, callback) {
			this.request('taobao.trades.sold.get', {
				status: 'WAIT_BUYER_PAY',
				use_has_next: 'true',
				start_created: toJson(new Date(new Date() - timeDiffTaobao - (1000 * 60 * 60 * 24 * 5))),
				fields: 'seller_nick, buyer_nick, title, type, created, tid, seller_rate,buyer_flag, buyer_rate, status, payment, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, commission_fee, buyer_memo, seller_memo, alipay_no, buyer_message, pic_path, num_iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email,seller_flag, seller_alipay_no, seller_mobile, seller_phone, seller_name, seller_email, available_confirm_fee, has_post_fee, timeout_action_time, snapshot_url, cod_fee, cod_status, shipping_type, trade_memo, is_3D,buyer_memo,buyer_email,orders'
			}, function(result) {
				var trade;
				try {
					trade = result.trades_sold_get_response.trades.trade;
				} catch (e) {}

				callback(trade, getApiError(result));
			});
		},
		closeOrder: function(tid, closeReason, callback) {
			this.request('taobao.trade.close', {
				tid: tid,
				close_reason: closeReason
			}, function(result) {
				var closeResult;
				try {
					closeResult = (result.trade_close_response.trade.tid == tid);
				} catch (e) {}

				callback(closeResult, getApiError(result));
			});
		},
		deliver: function(tid, callback) {
			this.request('taobao.logistics.dummy.send', {
				tid: tid
			}, function(result) {
				var sendResult;
				try {
					sendResult = result.logistics_dummy_send_response.shipping.is_success;
				} catch (e) {}

				try {
					if (result.error_response.sub_code == 'isv.logistics-dummy-service-error:B04') {
						sendResult = true;
					}
				} catch (e) {}

				callback(sendResult, getApiError(result));
			});
		},
		getDealDetail: function(tid, callback) {
			this.request('taobao.trade.fullinfo.get', {
				tid: tid,
				fields: 'seller_nick, buyer_nick, title, type, created, tid, seller_rate,buyer_flag, buyer_rate, status, payment, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, commission_fee, buyer_memo, seller_memo, alipay_no, buyer_message, pic_path, num_iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email,seller_flag, seller_alipay_no, seller_mobile, seller_phone, seller_name, seller_email, available_confirm_fee, has_post_fee, timeout_action_time, snapshot_url, cod_fee, cod_status, shipping_type, trade_memo, is_3D,buyer_memo,buyer_email,orders'

			}, function(result) {
				var trade;
				try {
					trade = result.trade_fullinfo_get_response.trade;
					trade.order = trade.orders.order[0];
					delete trade.orders;
				} catch (e) {}

				callback(trade, getApiError(result));
			});
		},
		getUserInfo: function(callback) {
			this.request('taobao.user.get', {
				fields: 'user_id, nick, seller_credit'
			}, function(result) {
				var user;
				try {
					user = result.user_get_response.user;
				} catch (e) {}

				callback(user, getApiError(result));
			});
		},
		getSellercats: function(callback) {
			this.request('taobao.sellercats.list.get', {
				nick: callbackArg.userNickName
			}, function(result) {
				var cats;
				try {
					cats = result.sellercats_list_get_response.seller_cats.seller_cat;
				} catch (e) {}

				callback(cats, getApiError(result));
			});
		},
		getItemDetail: function(num_iid, callback) { //宝贝详情
			this.request('taobao.item.get', {
				num_iid: num_iid,
				fields: 'approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id,detail_url,props_name,'
			}, function(result) {
				var detail;
				try {
					detail = result.item_get_response.item;
				} catch (e) {}

				callback(detail, getApiError(result));
			});
		},
		getGoodsOnSale: function(arg, callback) { //售中宝贝
			this.request('taobao.items.onsale.get', $.extend({
				fields: 'approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id'
			}, arg), function(result) {
				var items,
				itemCount;
				try {
					items = result.items_onsale_get_response.items.item,
					itemCount = result.items_onsale_get_response.total_results;
				} catch (e) {}

				callback(items, itemCount, getApiError(result));
			});
		},
		getGoodsInStock: function(arg, callback) { //仓库宝贝
			this.request('taobao.items.inventory.get', $.extend({
				fields: 'approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru, list_time,price,has_discount,has_invoice,has_warranty,has_showcase, modified,delist_time,postage_id,seller_cids,outer_id'
			}, arg), function(result) {
				var items,
				itemCount;
				try {
					items = result.items_inventory_get_response.items.item,
					itemCount = result.items_inventory_get_response.total_results;
				} catch (e) {}

				callback(items, itemCount, getApiError(result));
			});
		},
		listing: function(num_iid, num, callback) { //宝贝上架
			this.request('taobao.item.update.listing', {
				num_iid: num_iid,
				num: num
			}, function(result) {
				var result_num_iid;
				try {
					result_num_iid = result.item_update_listing_response.item.num_iid;
				} catch (e) {}

				callback(result_num_iid == num_iid, getApiError(result));
			});
		},
		delisting: function(num_iid, callback) { //宝贝下架
			this.request('taobao.item.update.delisting', {
				num_iid: num_iid
			}, function(result) {
				var result_num_iid;
				try {
					result_num_iid = result.item_update_delisting_response.item.num_iid;
				} catch (e) {}

				callback(result_num_iid == num_iid, getApiError(result));
			});
		},
		deleteItem: function(num_iid, callback) { //删除宝贝
			this.request('taobao.item.delete', {
				num_iid: num_iid
			}, function(result) {
				var result_num_iid;
				try {
					result_num_iid = result.item_delete_response.item.num_iid;
				} catch (e) {}

				callback(result_num_iid == num_iid, getApiError(result));
			});
		},
		itemJoinImg: function(arg, callback) {
			this.request('taobao.item.joint.img', $.extend({}, arg), function(result) {
				var url;
				try {
					url = result.item_joint_img_response.item_img.url;
				} catch (e) {}

				callback(url, getApiError(result));
			});
		},
		addGoods: function(arg, callback) { //添加宝贝
			this.request('taobao.item.add', $.extend({
				type: 'fixed',
				stuff_status: 'new'
			}, arg), function(result) {
				var item;
				try {
					item = result.item_add_response.item;
				} catch (e) {}

				callback(item, getApiError(result));
			});
		},
		updateSku: function(arg, callback) {
			this.request('taobao.item.sku.update', $.extend({}, arg), function(result) {
				var num_iid;
				try {
					num_iid = result.item_sku_update_response.sku.num_iid;
				} catch (e) {}

				callback(num_iid == arg.num_iid, getApiError(result));
			});
		},
		addCommend: function(arg, callback) { //橱窗推荐
			this.request('taobao.item.recommend.add', $.extend({}, arg), function(result) {
				var num_iid;
				try {
					num_iid = result.item_recommend_add_response.item.num_iid;
				} catch (e) {}

				callback(num_iid == arg.num_iid, getApiError(result));
			});
		},
		deleteCommend: function(arg, callback) { //取消橱窗推荐
			this.request('taobao.item.recommend.delete', $.extend({}, arg), function(result) {
				var num_iid;
				try {
					num_iid = result.item_recommend_delete_response.item.num_iid;
				} catch (e) {}

				callback(num_iid == arg.num_iid, getApiError(result));
			});
		},
		getTaobaoTime: function(callback) {
			this.request('taobao.time.get', {}, function(result) {
				var time;
				try {
					time = result.time_get_response.time;

					var times = time.match(/\d+/g).join(',');
					times[1] = times[1].replace(/^0/, '');
					times[1] = (times[1] - 1);

					timeDiffTaobao = new Function('return new Date()-new Date(' + times + ').getTime();')();
				} catch (e) {}

				callback(time, getApiError(result));
			});
		}
	}
})();