jssdk.js 40.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
(function ($) {
'use strict';

function __$styleInject(css, returnValue) {
  if (typeof document === 'undefined') {
    return returnValue;
  }
  css = css || '';
  var head = document.head || document.getElementsByTagName('head')[0];
  var style = document.createElement('style');
  style.type = 'text/css';
  head.appendChild(style);
  
  if (style.styleSheet){
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }
  return returnValue;
}

$ = 'default' in $ ? $['default'] : $;

/* eslint-disable */
// Noop
function noop() {}

// Generic callback
function genericCallback(data) {
	lastValue = [data];
}

// Call if defined
function callIfDefined(method, object, parameters) {
	return method && method.apply && method.apply(object.context || object, parameters);
}

// Give joining character given url
function qMarkOrAmp(url) {
	return (/\?/.test(url) ? "&" : "?"
	);
}

var STR_ASYNC = "async";
var STR_CHARSET = "charset";
var STR_EMPTY = "";
var STR_ERROR = "error";
var STR_INSERT_BEFORE = "insertBefore";
var STR_JQUERY_JSONP = "_jqjsp";
var STR_ON = "on";
var STR_ON_CLICK = STR_ON + "click";
var STR_ON_ERROR = STR_ON + STR_ERROR;
var STR_ON_LOAD = STR_ON + "load";
var STR_ON_READY_STATE_CHANGE = STR_ON + "readystatechange";
var STR_READY_STATE = "readyState";
var STR_REMOVE_CHILD = "removeChild";
var STR_SCRIPT_TAG = "<script>";
var STR_SUCCESS = "success";
var STR_TIMEOUT = "timeout";
var win = window;
var Deferred = $.Deferred;
var head = $("head")[0] || document.documentElement;
var pageCache = {};
var count = 0;
var lastValue;
var xOptionsDefaults = {
	//beforeSend: undefined,
	//cache: false,
	callback: STR_JQUERY_JSONP,
	//callbackParameter: undefined,
	//charset: undefined,
	//complete: undefined,
	//context: undefined,
	//data: "",
	//dataFilter: undefined,
	//error: undefined,
	//pageCache: false,
	//success: undefined,
	//timeout: 0,
	//traditional: false,
	url: location.href
};
var opera = win.opera;
var oldIE = !!$("<div>").html("<!--[if IE]><i><![endif]-->").find("i").length;

// ###################### MAIN FUNCTION ##
function jsonp(xOptions) {

	// Build data with default
	xOptions = $.extend({}, xOptionsDefaults, xOptions);

	// References to xOptions members (for better minification)
	var successCallback = xOptions.success,
	    errorCallback = xOptions.error,
	    completeCallback = xOptions.complete,
	    dataFilter = xOptions.dataFilter,
	    callbackParameter = xOptions.callbackParameter,
	    successCallbackName = xOptions.callback,
	    cacheFlag = xOptions.cache,
	    pageCacheFlag = xOptions.pageCache,
	    charset = xOptions.charset,
	    url = xOptions.url,
	    data = xOptions.data,
	    timeout = xOptions.timeout,
	    pageCached,


	// Abort/done flag
	done = 0,


	// Life-cycle functions
	cleanUp = noop,


	// Support vars
	supportOnload,
	    supportOnreadystatechange,


	// Request execution vars
	firstChild,
	    script,
	    scriptAfter,
	    timeoutTimer;

	// If we have Deferreds:
	// - substitute callbacks
	// - promote xOptions to a promise
	Deferred && Deferred(function (defer) {
		defer.done(successCallback).fail(errorCallback);
		successCallback = defer.resolve;
		errorCallback = defer.reject;
	}).promise(xOptions);

	// Create the abort method
	xOptions.abort = function () {
		!done++ && cleanUp();
	};

	// Call beforeSend if provided (early abort if false returned)
	if (callIfDefined(xOptions.beforeSend, xOptions, [xOptions]) === !1 || done) {
		return xOptions;
	}

	// Control entries
	url = url || STR_EMPTY;
	data = data ? typeof data == "string" ? data : $.param(data, xOptions.traditional) : STR_EMPTY;

	// Build final url
	url += data ? qMarkOrAmp(url) + data : STR_EMPTY;

	// Add callback parameter if provided as option
	callbackParameter && (url += qMarkOrAmp(url) + encodeURIComponent(callbackParameter) + "=?");

	// Add anticache parameter if needed
	!cacheFlag && !pageCacheFlag && (url += qMarkOrAmp(url) + "_" + new Date().getTime() + "=");

	// Replace last ? by callback parameter
	url = url.replace(/=\?(&|$)/, "=" + successCallbackName + "$1");

	// Success notifier
	function notifySuccess(json) {

		if (!done++) {

			cleanUp();
			// Pagecache if needed
			pageCacheFlag && (pageCache[url] = { s: [json] });
			// Apply the data filter if provided
			dataFilter && (json = dataFilter.apply(xOptions, [json]));
			// Call success then complete
			callIfDefined(successCallback, xOptions, [json, STR_SUCCESS, xOptions]);
			callIfDefined(completeCallback, xOptions, [xOptions, STR_SUCCESS]);
		}
	}

	// Error notifier
	function notifyError(type) {

		if (!done++) {

			// Clean up
			cleanUp();
			// If pure error (not timeout), cache if needed
			pageCacheFlag && type != STR_TIMEOUT && (pageCache[url] = type);
			// Call error then complete
			callIfDefined(errorCallback, xOptions, [xOptions, type]);
			callIfDefined(completeCallback, xOptions, [xOptions, type]);
		}
	}

	// Check page cache
	if (pageCacheFlag && (pageCached = pageCache[url])) {

		pageCached.s ? notifySuccess(pageCached.s[0]) : notifyError(pageCached);
	} else {

		// Install the generic callback
		// (BEWARE: global namespace pollution ahoy)
		win[successCallbackName] = genericCallback;

		// Create the script tag
		script = $(STR_SCRIPT_TAG)[0];
		script.id = STR_JQUERY_JSONP + count++;

		// Set charset if provided
		if (charset) {
			script[STR_CHARSET] = charset;
		}

		opera && opera.version() < 11.60 ?
		// onerror is not supported: do not set as async and assume in-order execution.
		// Add a trailing script to emulate the event
		(scriptAfter = $(STR_SCRIPT_TAG)[0]).text = "document.getElementById('" + script.id + "')." + STR_ON_ERROR + "()" :
		// onerror is supported: set the script as async to avoid requests blocking each others
		script[STR_ASYNC] = STR_ASYNC;

		// Internet Explorer: event/htmlFor trick
		if (oldIE) {
			script.htmlFor = script.id;
			script.event = STR_ON_CLICK;
		}

		// Attached event handlers
		script[STR_ON_LOAD] = script[STR_ON_ERROR] = script[STR_ON_READY_STATE_CHANGE] = function (result) {

			// Test readyState if it exists
			if (!script[STR_READY_STATE] || !/i/.test(script[STR_READY_STATE])) {

				try {

					script[STR_ON_CLICK] && script[STR_ON_CLICK]();
				} catch (_) {}

				result = lastValue;
				lastValue = 0;
				result ? notifySuccess(result[0]) : notifyError(STR_ERROR);
			}
		};

		// Set source
		script.src = url;

		// Re-declare cleanUp function
		cleanUp = function cleanUp(i) {
			timeoutTimer && clearTimeout(timeoutTimer);
			script[STR_ON_READY_STATE_CHANGE] = script[STR_ON_LOAD] = script[STR_ON_ERROR] = null;
			head[STR_REMOVE_CHILD](script);
			scriptAfter && head[STR_REMOVE_CHILD](scriptAfter);
		};

		// Append main script
		head[STR_INSERT_BEFORE](script, firstChild = head.firstChild);

		// Append trailing script if needed
		scriptAfter && head[STR_INSERT_BEFORE](scriptAfter, firstChild);

		// If a timeout is needed, install it
		timeoutTimer = timeout > 0 && setTimeout(function () {
			notifyError(STR_TIMEOUT);
		}, timeout);
	}

	return xOptions;
}

// ###################### SETUP FUNCTION ##
jsonp.setup = function (xOptions) {
	$.extend(xOptionsDefaults, xOptions);
};

// ###################### INSTALL in jQuery ##
$.jsonp = jsonp;


/* eslint-disable */

__$styleInject(".featuretip.tip-wrap{position:fixed;top:0;left:0;width:100%;height:100%;z-index:1000;background:rgba(0,0,0,.5)}.featuretip .tip{position:fixed;left:50%;top:50%;margin-left:-140px;margin-top:-140px;width:280px;background:#fff;border-top:40px solid #000;text-align:center;line-height:1.25}.featuretip .tip .title{margin:20px auto;font-size:24px;font-weight:700;text-align:center}.featuretip .tip .highlight{font-size:18px}.featuretip .tip .content{font-size:16px;color:#444;text-align:center}.featuretip .tip .button{display:block;margin:20px auto;width:150px;height:30px;font-size:14px;line-height:30px;text-align:center;color:#fff;background:#000;text-decoration:none}", undefined);

__$styleInject(".feature-coin.tip-wrap{position:fixed;top:0;left:0;width:100%;height:100%;z-index:1000;background:rgba(0,0,0,.5)}.feature-coin .tip{position:fixed;left:50%;top:50%;margin-left:-140px;margin-top:-140px;width:280px;background:#fff;text-align:center;line-height:1.25;background-repeat:no-repeat}.feature-coin .tip .tip-close{position:absolute;right:0;top:0;width:25px;height:25px;line-height:25px;text-align:center;font-size:16px;color:#fff;background:#000;cursor:pointer}.feature-coin .tip .title{margin:21px auto;font-size:22px;font-weight:700;text-align:center}.feature-coin .tip .highlight{font-size:18px}.feature-coin .tip .content{padding:4px;font-size:16px;color:#444;text-align:center;height:48px;overflow:hidden}.feature-coin .bottom-button{text-align:center}.feature-coin .tip .button,.feature-coin .tip .coin{display:inline-block;margin:20px auto;width:116px;height:26px;font-size:14px;line-height:26px;text-align:center;color:#fff;background:#000;text-decoration:none;border:2px solid #000}.feature-coin .tip .coin{color:#000;background:#fff}", undefined);

var isMobile = {
    Android: function Android() {
        return navigator.userAgent.match(/Android/i) ? true : false;
    },
    BlackBerry: function BlackBerry() {
        return navigator.userAgent.match(/BlackBerry/i) ? true : false;
    },
    iOS: function iOS() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
    },
    Windows: function Windows() {
        return navigator.userAgent.match(/IEMobile/i) ? true : false;
    },
    any: function any() {
        return isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows();
    }
};
var mycurrency = isMobile.any() ? '//m.yohobuy.com/home/mycurrency' : '//www.yohobuy.com/home/currency';
var $tipTmpl = $('<div class="featuretip tip-wrap"><div class="tip"><div class="title"></div><div class="content"></div><a class="button" href="">返回</a></div></div>'); // eslint-disable-line
var $cointipTmpl = $('<div class="feature-coin tip-wrap"><div class="tip"><div class="tip-close">&times;</div><div class="title"></div><div class="content"></div><div class="bottom-button"><a class="button" href="">去逛逛</a><a class="coin" href=\'' + mycurrency + '?openby:yohobuy={"action":"go.mine"}\'>查看有货币</a></div></div></div>'); // eslint-disable-line

var _queryString = function _queryString() {
    if (!window._jssdkQS) {
        var vars = {},
            hash = void 0,
            i = void 0,
            hashes = window.location.search.slice(1).split('&');

        for (i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars[hash[0]] = hash[1];
        }

        window._jssdkQS = vars;
    }

    return $.extend({}, window._jssdkQS);
};

var _sParamByIframe = function _sParamByIframe() {
    var paramsObj = _queryString();
    var queryArray = [];
    var queryString = '?';

    delete paramsObj['uid'];
    delete paramsObj['app_version'];
    delete paramsObj['client_type'];
    delete paramsObj['session_key'];
    delete paramsObj['client_secret'];

    for (var i in paramsObj) {
        queryArray.push(i + '=' + paramsObj[i]);
    }

    if (!paramsObj['expires']) {
        queryArray.push('expires=' + 7 * 24 * 60 * 60 * 1000);
    }

    queryArray.push('callback=jQueryMktCode');
    queryString += queryArray.join('&');
    $.getScript('//m.yohobuy.com/activity/wechat/1111' + queryString, function () {});
    // $('<iframe style="display:none;" src="//m.yohobuy.com/activity/wechat/1111' + queryString + '"></iframe>').prependTo('body');
};

var _bindEvent = function _bindEvent() {
    var $body = $('body');
    $body.on('click', '.feature-coin .close,.feature-coin .tip-close', function (e) {
        $cointipTmpl.fadeOut();
        e.preventDefault();
    });
    $body.on('click', '.feature-coin.tip-wrap', function (e) {
        if ('feature-coin tip-wrap' === e.target.className) {
            $cointipTmpl.fadeOut();
            e.preventDefault();
        }
    });
    $body.on('click', '.featuretip .close', function (e) {
        $tipTmpl.fadeOut();
        e.preventDefault();
    });
    $body.on('click', '.featuretip .refresh', function () {
        location.reload();
    });
    $body.on('click', '.featuretip.tip-wrap', function (e) {
        if ('featuretip tip-wrap' === e.target.className) {
            $tipTmpl.fadeOut();
            e.preventDefault();
        }
    });
};

var utils = {
    queryString: _queryString,
    init: function init() {
        //发送活动页参数
        _sParamByIframe();

        // 绑定事件
        _bindEvent();
    },
    isApp: function isApp() {
        var qs = _queryString();
        var isApp = !!qs.app_version || qs.openrefer === 'app' && qs.uid;

        return !!isApp;
    },
    image: function image(url, width, height, mode, quality) {
        mode = !isNaN(Number(mode)) ? mode : 2;
        url = url || '';
        url = url.replace(/{width}/g, width).replace(/{height}/g, height).replace(/{mode}/g, mode);
        if (url.indexOf('imageView2') > 0) {
            quality = quality || 90;
            url += '/q/' + quality;
        }
        return url.replace('quality/80', 'quality/60').replace('http:', '');
    },
    sParamByIframe: function sParamByIframe(params) {
        $.getScript('//m.yohobuy.com/activity/wechat/1111' + params, function () {});
        // $('<iframe style="display:none;" src="//m.yohobuy.com/activity/wechat/1111?' + params + '"></iframe>').prependTo('body');
    },
    showTip: function showTip(data) {
        data = data || {
            title: '',
            content: '',
            close: true
        };

        $tipTmpl.find('.title').html(data.title);
        $tipTmpl.find('.content').html(data.content);

        if (data.close) {
            $tipTmpl.find('.button').addClass('close');
        } else {
            $tipTmpl.find('.button').addClass('refresh').html('刷新');
        }

        $('body').append($tipTmpl);
        $tipTmpl.show();
    },
    showCoinTip: function showCoinTip(data) {
        data = data || {
            title: '',
            content: '',
            close: true
        };

        $cointipTmpl.find('.title').html(data.title);
        $cointipTmpl.find('.content').html(data.content);

        if (data.close) {
            $cointipTmpl.find('.button').addClass('close');
        }

        if (data.coin) {
            $cointipTmpl.find('.coin').css('display', 'inline-block');
        } else {
            $cointipTmpl.find('.coin').hide();
        }

        if (data.img) {
            $cointipTmpl.find('.tip').css('background-image', 'url(' + data.img + ')');
        }

        $('body').append($cointipTmpl);
        $cointipTmpl.show();
    }
};

var _noLoginUrl = function _noLoginUrl() {
    var referrer = location.href.split('?')[0];
    return '//m.yohobuy.com/signin.html?refer=' + encodeURIComponent(location.href) + '&openby:yohobuy={"action":"go.weblogin","params":{"jumpurl":{"url":"' + referrer.replace(/\//g, '\\/') + '","param":{"from":"app"}},"requesturl":{"url":"","param":{}},"priority":"N"}}';
};

var user = {
    uid: '',
    noLoginUrl: _noLoginUrl,
    init: function init() {
        var _this = this;
        return jsonp({
            url: '//m.yohobuy.com/passport/login/user?callback=?'
        }).then(function (res) {
            if (res.code === 200) {
                _this.uid = Number(res.data) || 0;
            }
            if (!_this.uid && utils.isApp()) {
                _this.uid = Number(utils.queryString().uid) || 0;
            }
            return $.Deferred().resolve(_this.uid);
        }, function () {
            utils.isApp() && (_this.uid = Number(utils.queryString().uid) || 0);
            return $.Deferred().resolve(_this.uid);
        });
    },
    auth: function auth() {
        if (!this.uid) {
            var noLoginUrl = _noLoginUrl();

            $('a.auth').attr('href', noLoginUrl);
        }
    },
    favout: function favout(skn) {
        if (!skn || !this.uid) {
            return;
        }

        jsonp({
            url: '//service.yoho.cn/activity/favorite/addFavorite?productSkn=' + skn + '&uid=' + this.uid + '&callback=?'
        }).then(function (res) {
            if (res.code === 200) {
                utils.showTip({
                    content: '恭喜您,收藏成功',
                    close: true
                });
            } else {
                utils.showTip({
                    content: res.message,
                    close: true
                });
            }
        }, function () {
            utils.showTip({
                title: '收藏失败<br>请刷新重新领取',
                content: '如多次收藏失败,请联系客服人员<br>带来不便敬请谅解',
                close: false
            });
        });
    },
    getMktCode: function getMktCode() {
        var mkt_code = void 0;

        if (this.uid) {
            if (Number(this.uid) % 1024 >= 512) {
                mkt_code = 100000000000195; // 默认的值
            } else {
                mkt_code = 100000000000193; // 个性化,动态接口数据
            }
        } else {
            mkt_code = 100000000000197; // 访客接口数据
        }
        return mkt_code;
    }
};

var jsApiList = ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'];
var shareData = {
    title: document.title,
    link: location.href,
    desc: 'YOHO!BUY',
    imgUrl: 'http://static.yohobuy.com/m/v1/img/touch/apple-touch-icon-144x144-precomposed-new.png'
};

var _getShareDataById = function _getShareDataById() {
    var shareId = utils.queryString().share_id;
    if (shareId) {
        return jsonp({
            url: '//m.yohobuy.com/activity/share?callback=?',
            data: {
                shareId: shareId
            }
        }).then(function (res) {
            if (res && res.code === 200 && res.data) {
                shareData.title = res.data.title;
                shareData.link = res.data.link || location.href;
                shareData.desc = res.data.content || res.data.title;
                shareData.imgUrl = res.data.pic;
            }
            return $.Deferred().resolve();
        }, function () {
            return $.Deferred().resolve();
        });
    } else {
        var shareTitle = $('#shareTitle').val();
        var shareImg = $('#shareImg').val();
        var shareDesc = $('#shareDesc').val();
        var shareLink = $('#shareLink').val();

        shareData.title = shareTitle ? shareTitle : shareData.title;
        shareData.imgUrl = shareImg ? shareImg : shareData.imgUrl;
        shareData.desc = shareDesc ? shareDesc : shareData.desc;
        shareData.link = shareLink ? shareLink : shareData.link;
        return $.Deferred().resolve();
    }
};

var share = {
    init: function init() {
        if (/QQ/i.test(navigator.userAgent)) {
            $.ajax({
                url: '//qzonestyle.gtimg.cn/qzone/qzact/common/share/share.js',
                dataType: 'script',
                cache: true,
                success: function success() {
                    _getShareDataById().then(function () {
                        window.setShareInfo && window.setShareInfo({
                            title: shareData.title,
                            summary: shareData.desc,
                            pic: shareData.imgUrl,
                            url: shareData.link
                        });
                    });
                }
            });
        }

        if (/MicroMessenger/i.test(navigator.userAgent)) {
            $.ajax({
                url: '//res.wx.qq.com/open/js/jweixin-1.3.2.js',
                dataType: 'script',
                cache: true,
                success: function success() {
                    jsonp({
                        url: '//m.yohobuy.com/activity/wechat/share?callback=?',
                        data: {
                            url: location.href
                        }
                    }).then(function (res) {
                        if (window.wx) {
                            window.wx.config({
                                debug: false,
                                appId: res.appId,
                                timestamp: res.timestamp,
                                nonceStr: res.nonceStr,
                                signature: res.signature,
                                jsApiList: jsApiList
                            });

                            _getShareDataById().then(function () {
                                window.wx.ready(function () {
                                    window.wx.onMenuShareAppMessage(shareData);
                                    window.wx.onMenuShareTimeline(shareData);
                                    window.wx.onMenuShareQQ(shareData);
                                    window.wx.onMenuShareWeibo(shareData);
                                    window.wx.onMenuShareQZone(shareData);
                                });
                            });
                        }
                    });
                }
            });
        }
    }
};

/**
 * 移动端尝试打开 app
 */
var channelMap = {
    'baidu.com': 100000000000055,
    'so.com': 100000000000049,
    'sogou.com': 100000000000053,
    'bing.com': 100000000000057,
    'm.sm.cn': 100000000000059,
    'google.com': 100000000000061
};

var getMktcBySeo = function getMktcBySeo() {
    var mktc,
        rf = document.referrer;

    for (var domain in channelMap) {
        if (rf.indexOf(domain) > -1) {
            mktc = channelMap[domain];
            break;
        }
    }
    return mktc;
};

var getAppPath = function getAppPath() {
    var qs = utils.queryString();
    var ct = qs.mkt_code || qs.union_type || getMktcBySeo() || '100000000000349';

    delete qs.openapp; // 防止重复打开

    var shareParams = qs.share_id ? '"share":"/operations/api/v5/webshare/getShare","shareparam":{"share_id":"' + qs.share_id + '"},' : '',
        appPath = 'yohobuy://yohobuy.com/goapp?ct=' + ct + '&openby:yohobuy={"action":"go.h5",' + shareParams + '"params":{"islogin":"N","url":"http://feature.yoho.cn' + location.pathname + '","param":' + JSON.stringify(qs) + '}}';

    return appPath;
};

var openapp = {
    init: function init() {
        if (utils.queryString().openapp) {
            var u = navigator.userAgent.toLowerCase();
            var isiOS = u.indexOf('os') > -1 || u.indexOf('iphone') > -1 || u.indexOf('mac') > -1 || u.indexOf('ipad') > -1;
            var appPath = getAppPath();

            if (isiOS) {
                window.location.href = appPath;
            } else {
                var ifr = document.createElement('iframe');
                ifr.src = appPath;
                ifr.style.display = 'none';
                document.body.appendChild(ifr);
            }
        }
    }
};

function cookie(name) {
    var re = new RegExp(name + '=([^;$]*)', 'i'),
        matchPattern = '$1';

    return re.test(decodeURIComponent(document.cookie)) ? RegExp[matchPattern] : '';
}

function setCookie(name, value, options) {
    var expires = '',
        path,
        domain,
        secure,
        date;

    if (typeof value !== 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }

        if (options.expires && (typeof options.expires === 'number' || options.expires.toUTCString)) {
            if (typeof options.expires === 'number') {
                date = new Date();
                date.setTime(date.getTime() + options.expires * 24 * 60 * 60 * 1000);
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        path = options.path ? '; path=' + options.path : '';
        domain = options.domain ? '; domain=' + options.domain : '';
        secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    }
}

var cookies = {
    cookie: cookie,
    setCookie: setCookie
};

/* global wx */
// 1. 优惠券领取
// 2. YOHO币领取

var baseUrl = '//activity.yoho.cn';

if (location.hostname === 'm.yohobuy.com') {
    baseUrl = '//m.yohobuy.com/activity';
}

var _getCoin = function _getCoin(data) {
    data.app = utils.queryString();
    data.app.uid = data.uid;

    jsonp({
        url: baseUrl + '/coin/sendCoin?callback=?',
        data: data
    }).then(function (res) {
        if (res.code === 200 && res.data) {
            if (res.data.code === 200) {
                utils.showCoinTip({
                    title: '恭喜您,成功领取有货币!',
                    content: '特殊情况下到账有延时<br>请耐心等待',
                    close: true,
                    coin: true,
                    img: res.data.popupImg
                });
            } else if (res.data.code === 501) {
                utils.showCoinTip({
                    title: '领取失败',
                    content: '哎呀,你来的有点早,活动还没开始呢<br/>稍后再来哦',
                    close: true,
                    img: res.data.popupImg
                });
            } else if (res.data.code === 502) {
                utils.showCoinTip({
                    title: '领取失败',
                    content: '抱歉,活动已结束了,下次要快哟~~',
                    close: true,
                    img: res.data.popupImg
                });
            } else if (res.data.code === 503) {
                utils.showCoinTip({
                    title: '已经领取',
                    content: '贪心会长胖,你已经领取过了啦~~',
                    close: true,
                    img: res.data.popupImg
                });
            } else if (res.data.code === 504) {
                utils.showCoinTip({
                    title: '领取失败',
                    content: '哎呀,你来晚了,有货币已经领完了,<br/>下次早点来哦',
                    close: true,
                    img: res.data.popupImg
                });
            } else if (res.data.msg) {
                utils.showCoinTip({
                    title: '领取失败',
                    content: '抱歉,系统错误,有货君正奋力解决中...请稍后再来',
                    close: true,
                    img: res.data.popupImg
                });
            }
        } else if (res.message) {
            utils.showCoinTip({
                title: '领取失败',
                content: '抱歉,系统错误,有货君正奋力解决中...请稍后再来',
                close: true,
                img: res.data && res.data.popupImg
            });
        }
    }, function () {
        utils.showCoinTip({
            title: '领取失败',
            content: '抱歉,系统错误,有货君正奋力解决中...请稍后再来',
            close: true
        });
    });
};

var _getCoupon = function _getCoupon(data) {
    data.app = utils.queryString();

    data.app.uid = cookies.cookie('app_uid') || data.app.uid;
    data.app.app_version = cookies.cookie('app_version') || data.app.app_version;
    data.app.client_type = cookies.cookie('app_client_type') || data.app.client_type;
    data.app.session_key = cookies.cookie('app_session_key') || data.app.session_key;

    jsonp({
        url: baseUrl + '/feature/couponSend?callback=?',
        data: data
    }).then(function (res) {
        if (res.code === 200) {
            utils.showTip({
                title: '领取成功',
                content: '恭喜您,领取成功',
                close: true
            });
        } else if (res.code === 401) {
            utils.showTip({
                title: '已经领取',
                content: '快去分享给更多<br>喜爱<span class="highlight">潮流</span>的小伙伴吧!',
                close: true
            });
        } else if (res.message) {
            utils.showTip({
                title: '领取失败<br>请刷新重新领取',
                content: res.message + '<br>如多次领取失败,请联系客服人员<br>带来不便敬请谅解',
                close: false
            });
        }
    }, function () {
        utils.showTip({
            title: '领取失败<br>请刷新重新领取',
            content: '如多次领取失败,请联系客服人员<br>带来不便敬请谅解',
            close: false
        });
    });
};

var _initCoin = function _initCoin(uid) {
    if (uid) {
        var cointoken = cookies.cookie('yoho-coin-token');
        if (cointoken) {
            _getCoin({
                token: cointoken,
                uid: uid
            });

            cookies.setCookie('yoho-coin-token', '');
        }
    }

    $('body').on('click', '.yoho-coin', function () {
        var token = $(this).data('token');
        if (user.uid) {
            _getCoin({
                token: token,
                uid: user.uid
            });
        } else {
            cookies.setCookie('yoho-coin-token', token);

            if (window.__wxjs_environment === 'miniprogram' && wx && wx.miniProgram) {
                wx.miniProgram.navigateTo({
                    url: '../bindPhoneNumber/bindPhoneNumber?h5back=' + location.href
                });
                return;
            }

            if ($('#intimacy-link').length <= 0) {
                $('body').append('<a href=\'' + user.noLoginUrl() + '\' style="display:none;" id="intimacy-link"><span class="intimacy-link"></span></a>');
            }
            $('.intimacy-link').click();
            return;
        }
    });
};

var _initCoupon = function _initCoupon(uid) {
    if (uid) {
        var conpontoken = cookies.cookie('yoho-conpon-token');
        if (conpontoken) {
            _getCoupon({
                token: conpontoken,
                uid: uid
            });

            cookies.setCookie('yoho-conpon-token', '');
        }
    }

    $('body').on('click', '.yoho-conpon', function () {
        var token = $(this).data('token');
        if (user.uid) {
            _getCoupon({
                token: token,
                uid: user.uid
            });
        } else {
            cookies.setCookie('yoho-conpon-token', token);

            if (window.__wxjs_environment === 'miniprogram' && wx && wx.miniProgram) {
                wx.miniProgram.navigateTo({
                    url: '../bindPhoneNumber/bindPhoneNumber?h5back=' + location.href
                });
                return;
            }

            if ($('#intimacy-link').length <= 0) {
                $('body').append('<a href=\'' + user.noLoginUrl() + '\' style="display:none;" id="intimacy-link"><span class="intimacy-link"></span></a>');
            }
            $('.intimacy-link').click();
            return;
        }
    });
};

var promotion = {
    init: function init(uid) {
        _initCoin(uid); // 初始化有货币
        _initCoupon(uid); // 初始化优惠券
    }
};

var abTestFlag = false; // ab测试
var _replaceData = function _replaceData(el, cond, data, wh, fp) {
    if (!data) {
        return;
    }

    el.find('.brand-name').html(data.brand_name);
    el.find('.product-detail').attr('href', '//m.yohobuy.com/product/' + data.product_skn + '.html?openby:yohobuy={"action":"go.productDetail","params":{"product_skn":' + data.product_skn + '}}');
    el.find('.product-detail-img').attr('src', utils.image(data.default_images, wh.w, wh.h, 2, 75));
    el.find('.product-name').html(data.product_name);
    el.find('.vip-price-val').html('\xA5' + data.vip_price);
    el.find('.sale-price').html('\xA5' + data.sales_price);
    if (data.sales_price === data.market_price) {
        el.find('.market-price').hide();
    } else {
        el.find('.market-price').html('\xA5' + data.market_price).show();
    }

    var brandDom = el.find('.product-brand');
    if (brandDom) {
        if (data.shop_id) {
            brandDom.attr('href', '//m.yohobuy.com/product/index/brand?domain=' + data.brand_domain + '&openby:yohobuy={"action":"go.shop","params":{"shop_id":' + data.shop_id + ',"shop_template_type":' + (data.shop_template_type || "1") + ',"is_red_shop":' + (data.is_red_shop || 1) + '}}');
        } else {
            brandDom.attr('href', '//m.yohobuy.com/product/index/brand?domain=' + data.brand_domain + '&openby:yohobuy={"action":"go.brand","params":{"brand_id":' + data.brand_id + '}}');
        }
    }

    // 楼层数据
    if (fp) {
        if (!fp.I_INDEX) fp.I_INDEX = 0;

        fp.I_INDEX++;
        el.find('.product-detail').attr('fp', JSON.stringify(fp));
        if (brandDom) {
            fp.I_INDEX++;
            brandDom.attr('fp', JSON.stringify(fp));
        }
    }

    var listDom = el.find('.list-product');
    if (listDom) {
        var sortStr = '',
            gender = cond.gender ? cond.gender : '1,3',
            url = '//list.m.yohobuy.com?gender=' + gender;

        if (listDom.data('sort')) {
            sortStr += ',"sort":' + data.small_sort_id;
            url += '&sort=' + data.small_sort_id;
        }
        if (listDom.data('misort')) {
            sortStr += ',"misort":' + data.middle_sort_id;
            url += '&misort=' + data.middle_sort_id;
        }
        if (listDom.data('msort')) {
            sortStr += ',"msort":' + data.max_sort_id;
            url += '&msort=' + data.max_sort_id;
        }

        url += '&openby:yohobuy={"action":"go.list","params":{"actiontype":1,"gender":' + gender + sortStr + '}}';
        listDom.attr('href', url);
    }
    el.html(el.html());
    return el;
};

var _getProductData = function _getProductData(dataArr) {
    if (!dataArr.length) {
        return;
    }

    var data = dataArr.shift();
    if (!data || !data.default_images) {
        return _getProductData(dataArr);
    }
    return data;
};

var _jsonp = function _jsonp(el, param, cond) {
    var cloneitem = el.attr('cloneitem');
    var loading = el.find('.loading');
    var goods = el.find('.feature-product-info');
    var rowNum = el.data('rownum');

    if (!goods.length) {
        return;
    }

    if (cond.abtest) {
        // ab测试,访客 和 >=512的uid 显示默认推荐
        if (!param.uid || Number(param.uid) % 1024 >= 512) {
            if (cloneitem) {
                $(goods[0]).remove();
            } else {
                goods.removeClass('novisible');
                loading.hide();
            }
            return;
        }
    }

    var imgwh = el.find('.imgwh').val() || ''; // 获取图片宽x高
    imgwh = imgwh.split('x') || [];

    var wh = {
        w: imgwh[0] || 300,
        h: imgwh[1] || 400
    };

    // 楼层数据
    var fp = el.attr('fp');
    fp = fp ? JSON.parse(fp) : '';

    jsonp({
        url: '//m.yohobuy.com/activity/individuation?callback=?',
        data: $.extend({}, param, cond)
    }).then(function (res) {
        if (!res || !res.length) {
            if (cloneitem) {
                $(goods[0]).remove();
            } else {
                goods.removeClass('novisible');
                loading.hide();
            }
            return;
        }

        // 最后商品数量不足一行,截掉
        res.length = res.length - res.length % rowNum;

        if (cloneitem) {
            // 可复制item
            var cnt = isNaN(Number(cloneitem)) ? res.length : Number(cloneitem);
            for (var indx = 0; indx < cnt; indx++) {
                var data = _getProductData(res); // 获取商品数据
                if (indx === 0) {
                    var gel = $(goods[0]);
                    var nel = _replaceData(gel, cond, data, wh, fp);
                    if (nel) {
                        nel.removeClass('novisible');
                    } else {
                        gel.remove();
                    }
                } else {
                    var _nel = _replaceData($(goods[0]).clone(), cond, data, wh, fp);
                    if (_nel) {
                        _nel.removeClass('novisible');
                        _nel.appendTo(el);
                    }
                }
            }
        } else {
            for (var i = 1; i < res.length; i++) {
                goods.last().after(goods.clone());
            }

            var $newGoods = el.find('.feature-product-info');

            $newGoods.each(function (indx, perProduct) {
                var $perProduct = $(perProduct);
                _replaceData($perProduct, cond, _getProductData(res), wh, fp);
            });
            $newGoods.removeClass('novisible');
            loading.hide();
        }
    }, function () {
        if (cloneitem) {
            $(goods[0]).remove();
        } else {
            goods.removeClass('novisible');
            loading.hide();
        }
    });
};

var _abTest = function _abTest() {
    var mkt_code = user.getMktCode();

    // cover覆盖mkt_code
    utils.sParamByIframe('callback=jQueryMktCode&cover=1&mkt_code=' + mkt_code + '&expires=' + 7 * 24 * 60 * 60 * 1000);

    // 上报曝光事件
    var actionUrl = [];
    $('a').each(function () {
        var href = $(this).attr('href');
        if (href && !/^#.*$/.test(href) && !/^javascript.*$/i.test(href)) {
            actionUrl.push(href);
        }
    });

    var cnt = 0;
    var timer = setInterval(function () {
        cnt++;
        if (cnt > 3) {
            clearInterval(timer);
            return;
        }
        if (window._yas && window._yas.sendAppLogs && window.appBaseLogs) {
            clearInterval(timer);
            window._yas.sendAppLogs({
                appop: 'YB_H5_PAGE_AB_OPEN_L',
                param: JSON.stringify({
                    C_ID: utils.queryString().yh_channel || 1,
                    PAGE_URL: window.originUrl,
                    PAGE_NAME: decodeURI(window.qs.title || document.title),
                    ACTION_URL: actionUrl,
                    CROWD_CODE: mkt_code + ''
                })
            }, true);

            $('a').click(function () {
                var furl = $(this).attr('href');
                if (furl && !/^#.*$/.test(furl) && !/^javascript.*$/i.test(furl)) {
                    window._yas.sendAppLogs({
                        appop: 'YB_H5_PAGE_AB_FLR_C',
                        param: JSON.stringify({
                            C_ID: utils.queryString().yh_channel || 1,
                            PAGE_URL: window.originUrl,
                            PAGE_NAME: decodeURI(window.qs.title || document.title),
                            F_URL: furl,
                            CROWD_CODE: mkt_code + ''
                        })
                    }, true);
                }
            });
        }
    }, 1000);
};

var _getProduct = function _getProduct(param) {
    $('.product-source').each(function (i, el) {
        el = $(el);
        var cond = el.attr('condition');
        if (!cond) {
            return;
        }
        cond = JSON.parse(cond);

        var yh_channel = utils.queryString().yh_channel;
        if (cond.abtest) {
            abTestFlag = true;
        }

        if (yh_channel) {
            cond.yh_channel = yh_channel;
        }

        if (i > 3) {
            setTimeout(function () {
                _jsonp(el, param, cond);
            }, 300);
        } else {
            _jsonp(el, param, cond);
        }
    });

    abTestFlag && _abTest();
};

var individuation = {
    init: function init(uid) {
        if (!uid && utils.isApp()) {
            // document.addEventListener('deviceready', function() {
            //     window.yohoInterface.triggerEvent(function(data) {
            //         // 获取个性话数据
            //         _getProduct({
            //             uid: data.uid,
            //             udid: data.udid
            //         });
            //     }, function() {}, {
            //         method: 'get.analyticAppData'
            //     });
            // }, false);

            _getProduct({
                uid: '',
                udid: utils.queryString().udid || ''
            });
        } else {
            // 获取个性话数据
            _getProduct({
                uid: uid,
                udid: cookies.cookie('_yasvd')
            });
        }
    }
};

// app.js

$(function () {
    openapp.init();

    user.init().then(function (uid) {
        individuation.init(uid); // 个性化推荐
        promotion.init(uid); // 促销
        user.auth(); // 权限验证
        share.init(); // 分享
        utils.init();
    });
});

var jssdk = {
    auth: user.auth,
    favout: user.favout,
    getMktCode: function getMktCode() {
        return user.getMktCode();
    },
    getUid: function getUid() {
        return user.uid;
    }
};

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  return typeof obj;
} : function (obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};

(function (factory) {
    /* eslint-disable */
    if ((typeof module === 'undefined' ? 'undefined' : _typeof(module)) === 'object' && _typeof(module.exports) === 'object') {
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) {
        define([], factory);
    } else {
        window._jssdk = factory();
    }
    /* eslint-disable */
})(function () {
    return jssdk;
});

}(jQuery));