/**
 利用chrome的fetch来避免跨域
 **/
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type == 'api') {
    new Promise((resolve) => {
      let headers = {};
      if (request.needMallId) {
        headers.Mallid = request.mallId;
      }
      if (request.anti) {
        headers["Anti-Content"] = request.anti
      }
      headers['Content-Type'] = 'application/json';
      headers.cookie = getCookie();
      Promise.resolve().then(() => fetch(request.url, {
        'headers': headers,
        'method': 'POST',
        'referrerPolicy': 'no-referrer',
        'credentials': 'include',
        'body': JSON.stringify(request.data),
        'mode': 'cors'
      })).then((res) => {
        resolve(res.json());
      });
    }).then(sendResponse);
  } else if (request.type == 'notify') {
    chrome.notifications.create(
        "" + Math.random(), {
          type: "basic",
          title: "TEMU助手",
          message: "您店铺【" + request.mallName + "】的商品【" + request.productName + "】成功加入发货台，请尽快处理",
          iconUrl: "./icons/48.png"
        }, null
    )
  }

  return true;
});

chrome.action.onClicked.addListener(function () {
  chrome.tabs.create({
    url: "./popup.html"
  }, function (tab) {
    console.log('tab is:' + tab);
  });
});

chrome.webRequest.onSendHeaders.addListener(details => {
  if (details.url && (details.url.indexOf('joinDeliveryGoodsOrderPlatform')  != -1)) {
    details.requestHeaders.push({
      name: 'Referer',
      value: 'https://kuajing.pinduoduo.com/main/order-manage'
    })
    for (let i = 0 ; i < details.requestHeaders.length; i++) {
      if (details.requestHeaders[i].name == 'Origin') {
        details.requestHeaders[i].value = 'https://kuajing.pinduoduo.com'
        break;
      }
    }
  } else if (details.url && (details.url.indexOf('mms/userInfo')  != -1)) {
    details.requestHeaders.push({
      name: 'Referer',
      value: 'https://kuajing.pinduoduo.com/main/order-manage'
    })
    for (let i = 0 ; i < details.requestHeaders.length; i++) {
      if (details.requestHeaders[i].name == 'Origin') {
        details.requestHeaders[i].value = 'https://kuajing.pinduoduo.com'
        break;
      }
    }
  }
},
{urls: ["<all_urls>"]},["requestHeaders", "extraHeaders"]);


function getCookie() {
  const url = new URL("https://kuajing.pinduoduo.com/");
  let cStr = '';
  chrome.cookies.getAll({domain: url.host}, (cookie) => {
    cookie.map((c) => {
      cStr += c.name + '=' + c.value + ';';
    });
  });
  return cStr;
}
