import settingConfig from "@/settings";

export function initPddLog() {
  if (!settingConfig.pddLogEnabled || !window.PDD_OPEN_init) return
  pddIntfHandle();
}

function getPageCode(callback) {
  let that = window.$vueRoot;
  return that.$http({
    url: USER_PREFIX + "/bd_api/intf/pddApiRouter",
    method: 'post',
    data: {"id": "pdd.cloud.isv.page.code"},
    modal: false,
    success: res => {
      if (res.objx?.response) {
        let response = res.objx.response;
        if (!response.success) {
          that.$baseAlert(response.errorMessage)
          return
        }
        let pageCode = response.pageCode
        callback(pageCode)
      }
    }
  });
}

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function handlePati(pati) {
  if (!pati) return;
  handleLoginLog(pati);//登录日志
  let size = getRandomIntInclusive(1, 5);//随机次数
  let time = 0;
  for (let i = 0; i < size; i++) {
    let delay = getRandomIntInclusive(5, 15) * 1000;//随机间隔
    time = time + delay;
    setTimeout(function () {
      handleOrderLog(pati);//订单日志
    }, time)
  }

}

function requestPati(id, pati) {
  return window.$vueRoot.$http({
    url: USER_PREFIX + "/bd_api/intf/pddApiRouter",
    method: 'post',
    data: {id, pati},
    modal: false,
    success: res => {
      if (res.objx?.response) {
        let response = res.objx.response;
        if (!response.success) {
          that.$baseAlert(response.errorMessage)
          return
        }
      }
    }
  });
}

function handleLoginLog(pati) {
  requestPati("pdd.cloud.security.event.tracking.login", pati)
}

function handleOrderLog(pati) {
  requestPati("pdd.cloud.security.event.tracking.batch.order", pati)
}

async function pddIntfHandle() {
  getPageCode(async (pageCode) => {
    if (!pageCode) return
    PDD_OPEN_init({
      code: pageCode
      // 对于获取 code 接口或未登录态，可不传 code：PDD_OPEN_init({}, function () { ... })
    }, function () {
      // 初始化已完成
      window.PDD_OPEN_getPati().then(
        function (pati) {
          // 使用 pati
          handlePati(pati)
        }).catch(error => console.log(error))
    })

  })
}
