function RL(a, b) {
    var t = "a";
    var Yb = "+";
    for (var c = 0; c < b.length - 2; c += 3) {
        var d = b.charAt(c + 2),
            d = d >= t ? d.charCodeAt(0) - 87 : Number(d),
            d = b.charAt(c + 1) == Yb ? a >>> d : a << d;
        a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d
    }
    return a
}
function token(a) {
    var k = "";
    var b = 406644;
    var b1 = 3293161072;
    var jd = ".";
    var sb = "+-a^+6";
    var Zb = "+-3^+b+-f";
    for (var e = [], f = 0, g = 0; g < a.length; g++) {
        var m = a.charCodeAt(g);
        128 > m ? e[f++] = m : (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023), e[f++] = m >> 18 | 240, e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224, e[f++] = m >> 6 & 63 | 128), e[f++] = m & 63 | 128)
    }
    a = b;
    for (f = 0; f < e.length; f++) a += e[f],
        a = RL(a, sb);
    a = RL(a, Zb);
    a ^= b1 || 0;
    0 > a && (a = (a & 2147483647) + 2147483648);
    a %= 1E6;
    return a.toString() + jd + (a ^ b)
};
function escapeJquery(srcString) {
    srcString = srcString.replace(/\r\n/g, "\\\\n");
	srcString = srcString.replace(/\"/g, "\\\\\\\"");
    return srcString;
};
$.ajaxSetup({async:false}); 
var clientId = guid();
var userName = "";
function translateAli(content){
	var tk = token(content);
	var turl = "https://translate.yunkuerp.cn/_/TranslateWebserverUi/data/batchexecute?rpcids=MkEWBc&f.sid=-7444794976357286854&bl=boq_translate-webserver_20210913.10_p0&hl=zh-CN&soc-app=1&soc-platform=1&soc-device=1&_reqid=3137469&rt=c";
	var result = "";
	headers = {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "accept-language": "en,zh-CN;q=0.9,zh;q=0.8",
    "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
  }
	$.ajax({
    type: "POST",
    url: turl,
    headers: headers,
		dataType: "text",
		data: {"f.req": "[[[\"MkEWBc\",\"[[\\\""+escapeJquery(content)+"\\\",\\\"auto\\\",\\\"zh-CN\\\",true],[null]]\",null,\"generic\"]]]"},
        success: function(res) {
			res = "[[\"wrb.fr\",\"MkEWBc\"," + res.split("[[\"wrb.fr\",\"MkEWBc\",")[1];
			res = res.split(",null,null,null,\"generic\"]]")[0] + ",null,null,null,\"generic\"]]";	
			var obj = JSON.parse(res);
			var obj2 = JSON.parse(obj[0][2]);
			for(var i = 0; i < obj2[1][0][0][5].length; i++){
				result += obj2[1][0][0][5][i][0];
			}
		}
	});
	return result;
}
function translate(content, goods, mark){
	var turl = "https://translate.yunkuerp.cn/_/TranslateWebserverUi/data/batchexecute?rpcids=MkEWBc&f.sid=-7444794976357286854&bl=boq_translate-webserver_20210913.10_p0&hl=zh-CN&soc-app=1&soc-platform=1&soc-device=1&_reqid=3137469&rt=c";
	headers = {
		"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "accept-language": "en,zh-CN;q=0.9,zh;q=0.8",
    "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
  }
	$.ajax({
      type: "POST",
      url: turl,
      headers: headers,
			dataType: "text",
			data: {"f.req": "[[[\"MkEWBc\",\"[[\\\""+escapeJquery(content)+"\\\",\\\"auto\\\",\\\"en\\\",true],[null]]\",null,\"generic\"]]]"},
      success: function(res) {
			var result = "";
			res = "[[\"wrb.fr\",\"MkEWBc\"," + res.split("[[\"wrb.fr\",\"MkEWBc\",")[1];
			res = res.split(",null,null,null,\"generic\"]]")[0] + ",null,null,null,\"generic\"]]";	
			var obj = JSON.parse(res);
			var obj2 = JSON.parse(obj[0][2]);
			for(var i = 0; i < obj2[1][0][0][5].length; i++){
				result += obj2[1][0][0][5][i][0];
			}
			var array1 = result.split("\n567\n");
			goods['PlatformProductName'] = array1[0].trim();
			
			var PlatformProductDescCN = "";
			for(var i = 0; i < goods.goodsDescAttribute.length; i++){
				PlatformProductDescCN += goods.goodsDescAttribute[i].cnAttributeName+": "+goods.goodsDescAttribute[i].cnAttributeValue+"；";
			}
			
			var PlatformProductDesc = "";
			var array2 = array1[1].trim().split("\n");
			if(array2.length > 1){
				for(var i = 0; i < array2.length; i+=2){
					PlatformProductDesc += array2[i].trim()+": "+array2[i+1].trim()+"; ";
				}
			}
			
			goods['PlatformProductDesc'] = PlatformProductDesc;
			goods['PlatformProductDescCN'] = PlatformProductDescCN;
			
			if(array1.length > 2){
				var array3 = array1[2].trim().split("\n678\n");
				for(var i = 0; i < array3.length; i++){
					var array4 = array3[i].trim().split("\n234\n");
					var thisPlatformProductAttrNameEn = array4[0];
					var thisPlatformProductAttrValueEnArray = array4[1].split("\n456\n");
					
					for(var j = 0; j < thisPlatformProductAttrValueEnArray.length; j++){
						var equaltimes = 1;
						for(var k = 0; k < thisPlatformProductAttrValueEnArray.length; k++){
							if(thisPlatformProductAttrValueEnArray[j] == thisPlatformProductAttrValueEnArray[k]){
								if(j != k){
									thisPlatformProductAttrValueEnArray[k] = thisPlatformProductAttrValueEnArray[k]+(""+equaltimes);
									equaltimes ++;
								}
							}
						}
					}
					
					var thisPlatformProductAttrNameCN = goods.goodsSpecAttributesForTranslate[i][0];
					var thisPlatformProductAttrValueCNArray = goods.goodsSpecAttributesForTranslate[i][1];
					for(var j = 0; j < thisPlatformProductAttrValueCNArray.length; j++){
						for(var k = 0; k < goods.platformProductSpecs.length; k++){
							for(var m = 0; m < goods.platformProductSpecs[k].PlatformProductAttrs.length; m++){
								if(thisPlatformProductAttrNameCN == goods.platformProductSpecs[k].PlatformProductAttrs[m].PlatformProductAttrNameCN){
									goods.platformProductSpecs[k].PlatformProductAttrs[m]["PlatformProductAttrName"] = thisPlatformProductAttrNameEn;
								}
								if(thisPlatformProductAttrValueCNArray[j] == goods.platformProductSpecs[k].PlatformProductAttrs[m].PlatformProductAttrValueCN){
									goods.platformProductSpecs[k].PlatformProductAttrs[m]["PlatformProductAttrValue"] = thisPlatformProductAttrValueEnArray[j];
								}
							}
						}
					}
				}
			}
			
			goods['PlatformName'] = "1688";
			
			var newGoods = {};
			newGoods['AddUser'] = userName;
			newGoods['PlatformName'] = "1688";
			newGoods['BuyLink'] = goods.BuyLink;
			newGoods['FPackageHeight'] = goods.FPackageHeight;
			newGoods['FPackageLength'] = goods.FPackageLength;
			newGoods['FPackageWeight'] = goods.FPackageWeight;
			newGoods['FPackageWidth'] = goods.FPackageWidth;
			newGoods['PlatformProductDesc'] = goods.PlatformProductDesc;
			newGoods['PlatformProductDescCN'] = goods.PlatformProductDescCN;
			newGoods['PlatformProductDetailImages'] = goods.PlatformProductDetailImages;
			newGoods['PlatformProductId'] = goods.PlatformProductId;
			newGoods['PlatformProductLink'] = goods.PlatformProductLink;
			newGoods['PlatformProductName'] = goods.PlatformProductName;
			newGoods['productCNName'] = goods.productCNName;
			newGoods['platformProductSpecs'] = goods.platformProductSpecs;
			newGoods['PurchasePrice'] = goods.PurchasePrice;
			newGoods['PlatformBigType'] = "";
			newGoods['PlatformType'] = "";
			newGoods['PlatformDetailType'] = "";
			newGoods['FOrderNumber'] = goods.FOrderNumber;

			if(newGoods.PlatformProductLink.indexOf(newGoods.PlatformProductId) > -1){
				console.log(newGoods);
				jQuery.post('http://sunsky-admin.com:8080/oaken/Base/1688Product_DownloadForHKMall.jsp', {productData: JSON.stringify(newGoods)}, function(res){
					var resdata = res.split("@@")[1];
					chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
						chrome.tabs.sendMessage(tabs[0].id, {cmd:'productsuccess', data:resdata});
					});
				});
			}
		}
	});
}

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 synClick(){
	chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
		chrome.tabs.sendMessage(tabs[0].id, {cmd:'getpageproduct'});
	});
}
chrome.contextMenus.create({"title": "生成HKTVMall文件包", "onclick": synClick});

chrome.runtime.onConnect.addListener(function(port) {
	port.onMessage.addListener(function(request) {
		if(port.name == "translate"){
			var goods = request.data;
			var mark = request.mark;
			var translateContent = [];
			var descAttributeArray = [];
			var specArray = [];
			translateContent.push(goods.productCNName.replace(/&.*?;/g, ''));
			for(var i = 0; i < goods.goodsDescAttribute.length; i++){
				descAttributeArray.push(goods.goodsDescAttribute[i].cnAttributeName.replace(/&.*?;/g, '') + "\r\n" + goods.goodsDescAttribute[i].cnAttributeValue.replace(/&.*?;/g, ''));
			}
			translateContent.push(descAttributeArray.join("\r\n"));
			
			for(var i = 0; i < goods.goodsSpecAttributesForTranslate.length; i++){
				specArray.push(goods.goodsSpecAttributesForTranslate[i][0] + "\r\n234\r\n" + goods.goodsSpecAttributesForTranslate[i][1].join("\r\n456\r\n"));
			}
			if(specArray.length > 0){
				translateContent.push(specArray.join("\r\n678\r\n"));
			}

			var translateContentStr = translateContent.join("\r\n567\r\n");
			console.log(translateContentStr);
			translate(translateContentStr, goods, mark);
		}
	})
})



