import * as constants from '@js/constants';
import { getNetworkType, getUrlParameter } from '@js/utils';
import axios from 'axios';
import qs from 'qs';

const handleResult = (res, errorInfo) => {
  let { data, success, desc, code } = res.data;

  if (success && code === '0000000') {
    return data;
  } else {
    console.error(errorInfo || 'getTuiaApi error', code, desc);
  }
};

/**
 * 获取token
 */
const getToken = userId => {
  return axios({
    method: 'post',
    url: constants.TUIA_IP + '/viewAdvert/getToken',
    data: qs.stringify({
      appKey: constants.TUIA_APP_KEY,
      slotId: constants.TUIA_SLOT_ID,
      deviceId: userId,
    }),
    headers: { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' },
  })
    .then(res => {
      return handleResult(res, 'getTuiaToken error');
    })
    .catch(err => {
      console.error(err);
    });
};

/**
 * 获取广告
 * @param {*} token
 * @param {*} ip
 */
const getAdvert = (token, ip) => {
  return axios({
    method: 'post',
    url: constants.TUIA_IP + '/viewAdvert/getAdvert',
    data: qs.stringify({
      token: token,
      userAgent: navigator.userAgent,
      ip: ip,
      networkType: getNetworkType(),
    }),
    headers: { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' },
  })
    .then(res => {
      let { data, success, code } = res.data;
      // res中塞入token
      if (success && code === '0000000') {
        data && Object.assign(data, { token: token });
      }
      return handleResult(res, 'getTuiaAdvert error');
    })
    .catch(err => {
      console.error(err);
    });
};

/**
 * 发送tuia埋点
 * @param {*} token
 * @param {*} orderId
 * @param {*} event
 */
const eventReport = (token, orderId, event) => {
  return axios({
    method: 'post',
    url: constants.TUIA_IP + '/viewAdvert/eventReport',
    data: qs.stringify({
      token: token,
      orderId: orderId,
      event: event,
      userAgent: navigator.userAgent,
    }),
    headers: { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' },
  })
    .then(res => {
      return handleResult(res, 'getTuiaToken error');
    })
    .catch(err => {
      console.error(err);
    });
};

const getTuiaAdvert = (ip, userId) => {
  return getToken(userId)
    .then(data => {
      console.log(data);
      return getAdvert(data, ip);
    })
    .then(data => {
      return data;
    });
};

export { getToken, getAdvert, eventReport, getTuiaAdvert };
