Tb = (window.Tb || {});
Tb.Api = (function() {
	var me,
		Data = {
			appkey: '12444247',
			shopId: '',
			session: '',
			nick: '',
			appsecret: '',
			group_name: 'dbb'
		},
		signOnClient = false,
		timer,
		getApiError = function(result) {
			var callerArg = arguments,
				method = callerArg[3];
			var errMsg = '';

			try {
				errMsg += '错误：' + result.error_response.msg;
				errMsg += result.error_response.sub_msg ? ('<br />\n子错误：' + result.error_response.sub_msg) : '';
			} catch (e) {
				errMsg = '';
			}

			if (errMsg == '') {
				errMsg = method + '<br />';
				if (callerArg[2] == 'timeout') {
					errMsg += '请求超时，请重试！';
				} else {
					try {
						if (callerArg[1]) errMsg += ';response=' + $.stringify(callerArg[1]);
					} catch (e) {}
					try {
						if (callerArg[2]) errMsg += ';textStatus=' + callerArg[2];
					} catch (e) {}
				}
			}
			return errMsg;
		},
		translateApiError = function(method, sub_code, cb) {
			$.ajax({
				url: 'http://api.taobao.com/apitools/errorCode.htm',
				cache: false,
				data: {
					apiName: method,
					errorCode: sub_code
				},
				success: function(html) {
					var Error = getFields({
						introduction: /<div class="introduction" style="text-align:left">\s+(.+)\s+<\/div>/,
						solution: /<div class="introduction"  style="text-align:left">\s+(.+)\s+<\/div>/
					}, html);

					if (Error.introduction && Error.solution) {
						cb(parseData2Template('<strong>错误描述</strong>：$introduction<br /><strong>解决方案</strong>：$solution', Error));
					} else {
						cb();
					}
				}
			});
		},
		translateApiName = function(method, cb) {
			$.ajax({
				url: 'http://open.taobao.com/search/searcher.htm',
				data: {
					t: 'api',
					q: method
				},
				success: function(html) {
					try {
						var Reg = /<h2><a href="[^"]+" target="_blank"> <span class="key-word">(taobao.[A-Za-z\.]+)<\/span>\s+(.+)<\/a><\/h2>/,
							matched = html.match(Reg);
					} catch (e) {
						//alert('74error:'+html);
					}

					if (matched) {
						cb(matched[1] == method ? matched[2] : method);
					} else {
						cb(method);
					}
				}
			});
		};

	return {
		init: function(){
			me = this;
			return me;
		},
		getAppkey: function(){
			return Data.appkey;
		},
		setData: function(oData) {
			$.extend(Data, oData);
			//Tb.User.nick = Data.nick,
			//Tb.User.session = Data.session;
		},
		getShop: function(cb) {
			me.req('taobao.shop.get', {
				nick: Data.nick,
				fields: 'sid, cid, nick, title, desc, bulletin, pic_path, created, modified, shop_score'
			}, function(result, errMsg) {
				cb(result.shop);
			})
		},
		authorise: function(callback, Login) {
			var Authorise = arguments2object(arguments, true);

			function authoriseSuccess(Field) {
				Data.session = Field.access_token;
				Data.refresh_token = Field.refresh_token;
				Data.wwId = Field.taobao_user_id;
				Data.nick = Field.taobao_user_nick;
				Data.re_expires_in = Field.re_expires_in;

				me.getShop(function(MyShop){//读取店铺信息
					function callback(){
						Shop.set($.extend(Data, {//设置店铺信息
							id: MyShop.sid,
							shopId: MyShop.sid,
							ww: Data.nick
						}), function(result, errMsg) {
							if (!result) {
								alert(errMsg);
								return false;
							}

							Dialog.hide();
							Authorise.callback(Data.nick);
						});
					}

					if(Field.taobao_user_id == '333739601'){
						callback();
						return;
					}

					if(Field.taobao_user_id == '22552328'){
						Data.group_name = 'dbbjk';
					}

					me.req('taobao.tmc.user.permit', {}, function(){//订阅消息

						me.req('taobao.tmc.group.add', {
							group_name: Data.group_name,
							nicks: Data.nick
						}, function(){
							me.req('taobao.logistics.address.search', {}, function(Addr, errMsg) {//读取发货地址列表
								var addressesCount = 0;
								try{
									addressesCount = Addr.addresses.address_result.length;
								}catch(e){}


								if(addressesCount){//存在发货地址
									callback();
									return;
								}

								me.req('taobao.logistics.address.add', {//添加一个发货地址
									contact_name: '卖家名字',
									province: '浙江省',
									city: '杭州市',
									country: '西湖区',
									addr: '华星路xx号',
									zip_code: '315040',
									mobile_phone: '13412345612'
								}, callback);
							});
						});						
					});
				});
			}

			function authoriseFunc(arg) {
				Dialog.normalAlert('淘宝授权', '信息读取中……');
				var authorUrl = 'https://oauth.taobao.com/authorize',
					args = $.param({
						client_id: Data.appkey,
						response_type: 'token',
						scope: 'item, usergrade'
					}),
					authorPageUrl = authorUrl + '?' + args;

				function authorBox(AuthorBox) {
					var eventNames = [];

					MiniBrowser.navigate({
						title: '淘宝授权',
						url: AuthorBox.url,
						type: AuthorBox.params?'post':'get',
						params: AuthorBox.params,
						//hide: true,
						top: true,
						width: AuthorBox.width,
						height: AuthorBox.height,
						callback: function(obj, eventName) {
							if (eventName == 'close') {
								Dialog.hide();
								return;
							}

							(function() {
								if (eventName != 'navigateComplete') return;

								var url = obj.url;

								if (/access_token=\w+/.test(url)) { //授权成功
									var Field = getFields({
										access_token: /access_token=(\w+)/,
										refresh_token: /refresh_token=(\w+)/,
										taobao_user_id: /taobao_user_id=(\d+)/,
										taobao_user_nick: /taobao_user_nick=([^&]+)/,
										re_expires_in: /re_expires_in=(\d+)/
									}, url);

									if (Field.access_token && Field.refresh_token && Field.taobao_user_nick) {
										Field.taobao_user_nick = decodeURI(Field.taobao_user_nick);

										Dialog.hide();
										authoriseSuccess(Field);
										MiniBrowser.hide({
											blank: true
										});
									}
								}
							})();

							(function() {
								if (!AuthorBox.params || eventName != 'documentComplete') return;
								var $body = $(obj.Win.document.body);
								$body.append('<style>html{overflow:hidden;}.aq_overlay_mask,.piao,.footer,.header,.aq_def_overlay_x{display:none;}.ad_def_overlay{position: static;}</style>');

								MiniBrowser.show(true, AuthorBox.width, AuthorBox.height);

								obj.Win.AQPop.addMethod({
									'cancel': function() {
										MiniBrowser.hide();
										Dialog.hide();
									}
								});
							})();
						}
					});
				}

				$.ajax({//读取授权参数
					url: authorPageUrl,
					success: function(html) {
						var that = this;
						(function() {
							var reg = /<form[\s\S]+?<\/form>/,
								form = reg.exec(html),
								Field;

							if (!form) {//未读到表格，直接打开用户自行处理
								that.error();
								return;
							}

							form = form[0];
							Field = $(form).serializeObject();
							Field.agreement = 'true';

							authorBox({//提交参数
								url: authorUrl,
								params: $.param(Field),
								width: 320,
								height: 280
							});
						})();
					},
					error: function(){
						authorBox({
							url: authorPageUrl
						});
					}
				});
			}

			Tb.User.login($.extend({}, Authorise.Login, {//登录先
				callback: function(loginedNick){
					if(~loginedNick.indexOf(':')){
						Dialog.hide();
						Dialog.tip('不支持子账号授权', 1500);						
						return;
					}
					authoriseFunc();
				}
			}));
		},
		req: function(method, arg, callback, returnError) {
			if (!Data.nick) {
				this.authorise(function() {}, {});
				return false;
			}

			this.request(method, arg, function(result, errMsg, errResult) {
				if (!result) {
					try {
						if (errResult.error_response.code == 27) {
							Dialog.tip('淘宝授权过期，请重新登录淘宝并授权！');

							me.authorise(function() {
								me.req(method, arg, callback, errResult);
							});
							return false;
						}
					} catch (e) {}

					if (!returnError) {
						Dialog.alert({
							title: '淘宝调用错误(' + method + ')',
							content: errMsg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<'),
							style: {
								width: 300
							}
						});
						return false;
					}
				}
				callback(result, errMsg);
			}, returnError);
		},
		request: function(method, arg, callback, returnError) {
			var arg = $.extend({
				method: method,
				timestamp: toJson(new Date()),
				format: 'json',
				app_key: Data.appkey,
				session: Data.session,
				v: '2.0'
			}, arg),
				stringForSign,
				sign = (function() {
					var Args = [],
						data = [];

					$.each(arg, function(key, val) {
						Args.push({
							key: key,
							val: val
						});
					});
					Args.sort(function(A, B){
						return A.key>B.key?1:-1;
					});

					$.each(Args, function(index, couple) {
						data.push('' + couple.key + couple.val);
					});

					stringForSign = data.join('');
					data.unshift(Data.appsecret);
					return $.md5(data.join('')).toUpperCase();
				})(),
				url = 'http://gw.api.taobao.com/router/rest',
				func = function(sign, errMsg) {
					$.ajax({
						url: url,
						type: 'post',
						dataType: method == 'taobao.picture.get' ? 'text' : 'json',
						data: $.extend(arg, {
							sign: sign
						}),
						success: function(data, textStatus, jqXhr) {
							if (method == 'taobao.picture.get') {
								try {
									data = (new Function("return " + $.trim(jqXhr.responseText.replace(/("picture_id":)(\d+)/g, '$1"$2"')).replace(/[\r\n]/g, ' ')))();
								} catch (e) {
									this.error();
									return;
								}
							}
							this.callback(data, jqXhr, textStatus);
						},
						error: function(jqXhr, textStatus) {
							var data;
							if (method == 'taobao.picture.get') {
								try {
									data = (new Function("return " + $.trim(jqXhr.responseText.replace(/("picture_id":)(\d+)/g, '$1"$2"')).replace(/[\r\n]/g, ' ')))();
								} catch (e) {
									//textStatus += ';e1:' + e.description;
								}
							} else {
								try {
									data = (new Function("return " + $.trim(jqXhr.responseText).replace(/[\r\n]/g, ' ')))();
								} catch (e) {
									//textStatus += ';e1:' + e.description;
								}
							}
							this.callback(data, jqXhr, textStatus);
						},
						callback: function(data, jqXhr, textStatus) {
							var result;
							try {
								result = data[method.replace('taobao.', '').replace(/\./g, '_') + '_response'];
							} catch (e) {
								//textStatus += ';e2:' + e.description;
							}

							if (result) {
								callback(result);
								return;
							}

							translateApiName(method, function(methodName) {
								var sub_code,
									sub_msg,
									errSubMsg = '<strong>调用接口</strong>：' + methodName + '<br />';

								try {
									sub_code = data.error_response.sub_code;
									sub_msg = data.error_response.sub_msg;
								} catch (e) {}

								if (sub_msg && sub_msg.match(/[^x00-xff]/)) {
									callback(result, errSubMsg + '<strong>错误描述</strong>：' + sub_msg, data);
								} else if (sub_code) {
									translateApiError(method, sub_code, function(errMsg) {
										if (errMsg) {
											callback(result, errSubMsg + errMsg, data);
										} else {
											callback(result, errSubMsg + getApiError(data, jqXhr, textStatus, method), data);
										}
									});
								} else {
									callback(result, errSubMsg + getApiError(data, jqXhr, textStatus, method), data);
								}
							});
						}
					});
				}

			if (signOnClient) {
				func(sign);
			} else {
				Dwd.interface('API参数签名', 'Taobao/TaobaoSign.asp?' + method, {
					v: stringForSign
				}, function(result, errMsg) {
					if (!result) {
						if (returnError) {
							callback(false, errMsg);
						} else {
							alert(errMsg);
						}
						return;
					}
					if (!result.value || !('' + result.value).match(/^[0-9A-Z]{32}$/)) {
						if (returnError) {
							callback(false, errMsg);
						} else {
							alert('API签名错误');
						}
						return;
					}
					func(result.value);
				});
			}
		},
		deletePicByOuterId: function(outerId, cb) { //根据商家编码批量删除图片
			var page_no = 1,
				page_size = 100,
				page_count,

				picIds = [];

			function getPic() {
				me.req('taobao.picture.get', {
					deleted: 'unfroze',
					page_size: page_size,
					page_no: 1,
					title: outerId
				}, function(result) {
					if (!result) {
						getPic();
						return;
					}

					if (result.totalResults === 0) {
						cb && cb();
						return;
					}

					page_no++;
					page_count = Math.ceil(result.totalResults / page_size);

					picIds = $.map(result.pictures.picture, function(pic, index) {
						return pic.picture_id;
					});

					delPic();
				})
			}

			function delPic() {
				var picId = picIds.splice(0, 50);

				if (!picId.length) {
					getPic();
					return;
				}

				me.req('taobao.picture.delete', {
					picture_ids: picId.join(',')
				}, function() {
					delPic();
				}, true);
			}

			getPic();
		}
	}
})().init();