function guid() {
  return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    return v.toString(16);
  });
}
function doExchange(arr){
	var len = arr.length;
	if(len >= 2){
		var len1 = arr[0].length;
		var len2 = arr[1].length;
		var lenBoth = len1 * len2;
		var items = new Array(lenBoth);
		var index = 0;
		for(var i = 0; i < len1; i++){
			for(var j = 0; j < len2; j++){
				items[index] = arr[0][i] + "|" + arr[1][j];
				index++;
			}
		}
		var newArr = new Array(len -1);
		for(var i = 2;i < arr.length; i++){
			newArr[i - 1] = arr[i];
		}
		newArr[0] = items;
		return doExchange(newArr);
	}else{
		return arr[0];
	}
}

var portTranslate = chrome.runtime.connect({name: "translate"});
var portTranslateAli = chrome.runtime.connect({name: "translateAli"});
var portTranslateToonies = chrome.runtime.connect({name: "translateToonies"});
var portTranslateText = chrome.runtime.connect({name: "translateText"});

window.addEventListener("message", function(e){
	if(e.data.fun == "translateText"){
		var content = e.data.content;
		var tcode = e.data.tcode;
		var mark = e.data.mark;
		portTranslateText.postMessage({data:content, tcode:tcode, mark:mark});
	}
	if(e.data.fun == "translateToniesGoods"){
		var goods = e.data.goods;
		portTranslateToonies.postMessage({data:goods});
	}
	if(e.data.fun == "callPlug"){
		var temp = document.createElement('script');
		temp.setAttribute('type', 'text/javascript');
		temp.innerHTML = "if(typeof plugAnswer != 'undefined'){plugAnswer();}";
		temp.onload = function(){
			this.parentNode.removeChild(this);
		};
		document.head.appendChild(temp);
	}
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){ 
	if(request.cmd == 'reload'){
		var data = request.data;
		window.location.href = data.split('##')[1];
	}
	if(request.cmd == 'getpagedata'){
		var data = request.data;
		syn1688ProductFinal($('html').html(), data.split('##')[0], 0);
	}
	if(request.cmd == 'getpageproduct'){
		if(window.location.href.indexOf('https://detail.1688.com/') == 0){
			$('body').append("<div id='plugwaiting'><div style='position:fixed;width:100%;height:100%;z-index:9999;background:#000;opacity:0.3;top:0px;left:0px;'></div><div style='position:fixed;left:50%;top:30%;width:300px;height:120px;background:#fff;margin-left:-150px;margin-top:-60px;text-align:center;font-size:14px;font-weight:bold;z-index:10000;border:1px solid #aaa;border-radius:5px;'><table style='height:100%;width:100%'><tr><td style='padding:0 10px;vertical-align:middle;font-size:13px' id='sun-s-p-info'>文件生成中，请继续操作其他页面，不用一直在这里等待</td></tr><table></div></div>");
			syn1688ProductFinal($('html').html(), "", 1);
		}
	}
	if(request.cmd == 'productsuccess'){
		$('#plugwaiting').remove();
		$('body').append("<div><div style='position:fixed;width:100%;height:100%;z-index:9999;background:#000;opacity:0.3;top:0px;left:0px;'></div><div style='position:fixed;left:50%;top:30%;width:300px;height:120px;background:#fff;margin-left:-150px;margin-top:-60px;text-align:center;font-size:14px;font-weight:bold;z-index:10000;border:1px solid #aaa;border-radius:5px;'><div style='position:absolute;right:5px;top:5px;border:1px solid #999;height:25px;width:25px;line-height:25px;text-align:center;background:#fdfdfd;cursor:pointer' id='sun-s-p-info-close'>X</div><table style='height:100%;width:100%'><tr><td style='padding:0 10px;vertical-align:middle;font-size:13px' id='sun-s-p-info'>同步成功，请点击 <b style='color:blue;text-decoration:underline;cursor:pointer'>这里</b> 下载文件包。</td></tr><table></div></div>");
		$('#sun-s-p-info').click(function(){
			window.open("http://sunsky-admin.com:8080/oaken/Base/Excel/HKMallProduct/"+request.data);
		});
		$('#sun-s-p-info-close').click(function(){
			$(this).parent().parent().remove();
		});
	}
});

function syn1688ProductFinal(bodyObj, platfromProductId, mark){
	if(bodyObj.indexOf("var iDetailConfig = {") == -1){
		if(bodyObj.indexOf("window.__INIT_DATA") == -1){
			return;
		}else{
			eval('var init_data = ' + bodyObj.split('window.__INIT_DATA=')[1].split('</script>')[0]);
			var goods = {};
			goods['BuyLink'] = window.location.href;
			goods['PlatformProductLink'] = window.location.href;
			goods['PlatformProductId'] = init_data.globalData.offerBaseInfo.offerId+"";
			goods['PlatformProductDetailImages'] = [];
			
			bodyObj = bodyObj.substring(bodyObj.indexOf('<body '));
			bodyObj = bodyObj.substring(0, bodyObj.indexOf('</body>') + 7);
			bodyObj = bodyObj.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "");
			bodyObj = bodyObj.replace(/[\r\n]/g, ""); 
			bodyObj = bodyObj.replace(/\s+/g, " "); 
			bodyObj = $(bodyObj);
			
			goods['productCNName'] = bodyObj.find('.title-first-column').text();

			for(var i = 0; i < init_data.globalData.images.length; i++){
				goods.PlatformProductDetailImages.push(init_data.globalData.images[i].fullPathImageURI);
			}

			var attributeList = [];
			var tempAttributes = [];
			var goodsSpecAttributesForTranslate = [];
			console.log(init_data);
			if(typeof init_data.globalData.skuModel.skuProps != 'undefined' && init_data.globalData.skuModel.skuProps.length > 1){
				alert('该产品为二维属性产品，暂不支持上传到 HKTVMall');
				return;
			}
			if(typeof init_data.globalData.skuModel != 'undefined'){
				if(typeof init_data.globalData.skuModel.skuProps != 'undefined'){
					init_data.globalData.skuModel.skuProps.forEach(function(m, j){
						var thisTempAttributes = [];
						var thisAttributeName = m.prop;
						goodsSpecAttributesForTranslate[j] = [];
						goodsSpecAttributesForTranslate[j][0] = thisAttributeName;
						goodsSpecAttributesForTranslate[j][1] = [];
						m.value.forEach(function(n, i){
							var goodsAttribute = {};
							goodsAttribute['id'] = guid();
							goodsAttribute['cnAttributeName'] = thisAttributeName;
							goodsAttribute['cnAttributeValue'] = n.name;
							goodsSpecAttributesForTranslate[j][1][i] = n.name;
							if(typeof n.imageUrl != 'undefined'){
								goodsAttribute['attributeImageId'] = guid();
								goodsAttribute["attributeImage"] = n.imageUrl;
								goodsAttribute["attributeThumbImage"] = n.imageUrl;
							}
							attributeList.push(goodsAttribute);
							thisTempAttributes.push(goodsAttribute.id);
						});
						tempAttributes.push(thisTempAttributes);
					});
				}
			}
			goods['goodsSpecAttributesForTranslate'] = goodsSpecAttributesForTranslate;

			var FPackageWeight = "0";
			var FPackageHeight = "0";
			var FPackageLength = "0";
			var FPackageWidth = "0";
			
			for(var i = 0; i < Object.keys(init_data.data).length; i++){
				var data = init_data.data[Object.keys(init_data.data)[i]];
				if(data.componentType == '@ali/tdmod-od-pc-offer-logistics'){
					if(typeof data.data.unitWeight != 'undefined'){
						FPackageWeight = data.data.unitWeight+"";
					}
				}
			}
			
			if(bodyObj.find('.od-pc-offer-cross').length > 0){
				bodyObj.find('.od-pc-offer-cross').find('.offer-attr-item-name').each(function(i, n){
					if($(n).text() == '产品体积'){
						var volarray = $(n).next().text().replace(/cm/g, '').split(' * ');
						FPackageLength = volarray[0];
						FPackageWidth = volarray[1];
						FPackageHeight = volarray[2];
					}
					if($(n).text() == '跨境包裹重量'){
						if(FPackageWeight == "0"){
							FPackageWeight = $(n).next().text().replace(/kg/g, '');
						}
					}
				});
			}
			goods['FPackageWeight'] = FPackageWeight;
			goods['FPackageHeight'] = FPackageHeight;
			goods['FPackageLength'] = FPackageLength;
			goods['FPackageWidth'] = FPackageWidth;
			
			goods['PurchasePrice'] = "0";
			for(var i = 0; i < Object.keys(init_data.data).length; i++){
				var data = init_data.data[Object.keys(init_data.data)[i]];
				if(data.componentType == '@ali/tdmod-od-pc-offer-price'){
					goods['PurchasePrice'] = data.data.priceModel.currentPrices[0].price;
				}
			}
					
			goods['platformProductSpecs'] = [];
			if(tempAttributes.length > 0){
				var productAttributes = doExchange(tempAttributes);
				for(var i = 0; i < productAttributes.length; i++){
					var platformProductSpec = {};
					platformProductSpec['FPackageWeight'] = FPackageWeight;
					platformProductSpec['FPackageHeight'] = FPackageHeight;
					platformProductSpec['FPackageLength'] = FPackageLength;
					platformProductSpec['FPackageWidth'] = FPackageWidth;
					
					var productAttributesIds = productAttributes[i].split('|');
					var goodsAttributesArray = [];
					var attrNameArray = [];
					var PlatformProductSpecPicture = "";
					for(var j = 0; j < attributeList.length; j++){
						for(var k = 0; k < productAttributesIds.length; k++){
							if(productAttributesIds[k] == attributeList[j].id){
								attrNameArray.push(attributeList[j].cnAttributeValue);
								var goodsAttributeObj = {};
								goodsAttributeObj['PlatformProductAttrNameCN'] = attributeList[j].cnAttributeName;
								goodsAttributeObj['PlatformProductAttrValueCN'] = attributeList[j].cnAttributeValue;
								goodsAttributeObj['PlatformProductAttrName'] = attributeList[j].cnAttributeName;
								goodsAttributeObj['PlatformProductAttrValue'] = attributeList[j].cnAttributeValue;
								goodsAttributesArray.push(goodsAttributeObj);
								if(typeof attributeList[j].attributeImage != 'undefined' && attributeList[j].attributeImage.length > 0){
									PlatformProductSpecPicture = attributeList[j].attributeImage;
								}
							}
						}
					}
					
					var specId = "";
					var specPrice = "0";
					var skuId = "";
					for(var j in init_data.globalData.skuModel.skuInfoMap){
						var thisAttrValueArray = j.split('&gt;');
						var specMark = 1;
						for(var k = 0; k < goodsAttributesArray.length; k++){
							if(jQuery.inArray(goodsAttributesArray[k].PlatformProductAttrValueCN, thisAttrValueArray) == -1){
								specMark = 0;
							}
						}
						if(specMark == 1){
							specId = init_data.globalData.skuModel.skuInfoMap[j].specId;
							if(typeof init_data.globalData.skuModel.skuInfoMap[j].price == 'undefined'){
								if(typeof init_data.globalData.skuModel.skuPriceScale == 'undefined'){
									specPrice = goods['PurchasePrice'];
								}else{
									specPrice = init_data.globalData.skuModel.skuPriceScale;
								}
							}else{
								specPrice = init_data.globalData.skuModel.skuInfoMap[j].price;
							}
							
							skuId = init_data.globalData.skuModel.skuInfoMap[j].skuId;
						}
					}
					for(var m = 0; m < Object.keys(init_data.data).length; m++){
						var data = init_data.data[Object.keys(init_data.data)[m]];
						if(data.componentType == '@ali/tdmod-od-pc-offer-logistics'){
							if(typeof data.data.skuWeight != 'undefined'){
								platformProductSpec['FPackageWeight'] = data.data.skuWeight[skuId+''];
							}
						}
					}
					platformProductSpec["price"] = specPrice;
					platformProductSpec["specId"] = specId;
					platformProductSpec["skuId"] = skuId+"";
					platformProductSpec['PlatformProductAttrs'] = goodsAttributesArray;
					platformProductSpec['PlatformProductSpecPicture'] = PlatformProductSpecPicture;
					
					goods.platformProductSpecs.push(platformProductSpec);
				}
			}
			var goodsDescAttribute = [];
			bodyObj.find('.od-pc-attribute .offer-attr-item').each(function(i, n){
				if($(n).find('.offer-attr-item-name').text() != "建议零售价"){
					var goodsAttribute = {};
					goodsAttribute['cnAttributeName'] = $(n).find('.offer-attr-item-name').text();
					goodsAttribute['cnAttributeValue'] = $(n).find('.offer-attr-item-value').text();
					goodsDescAttribute.push(goodsAttribute);
				}
			});
			goods['goodsDescAttribute'] = goodsDescAttribute;
			console.log(goods);
			portTranslate.postMessage({data:goods, mark:mark});
		}
	}
}