const API_BASE = process.env.VUE_APP_API_URL.replace('/api', '');
const API_GAME = process.env.VUE_APP_GAME_URL.replace('/api', '');
// import axios from 'axios'
import store from '@/store'

const toJson = res => res.json();

const httpPost = async (url, data,token) => {
  // const token = store.state.wallet.token;
  token = token || localStorage.getItem('token');
  let headers = {"Content-Type": "application/json"};
  // let token = token;
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  return fetch(url, {
    method: "POST",
    body: JSON.stringify(data),
    headers
  }).then(toJson);
}

const httpGet = async (url, data, token) => {
  token = token || store.state.wallet.token;
  let headers = {"Content-Type": "application/json"};
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  url = url + (url.indexOf('?') > -1 ? "&" : "?" )+ new URLSearchParams(data).toString()
  return fetch(url, {
    method: "GET",
    headers
  }).then(toJson);
}

// 邮箱校验
export const isEmail = (email) => {
  const reg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
  return reg.test(email)
}

// 验证码校验
export const isValiedCode = (code) => {
  return /^\d{6}$/.test(code)
}

// 解析邮箱
export const getEmail = (token) => {
  let emailToken = token.split(".")
  let getEmail = emailToken[1]
  let email = JSON.parse(atob(getEmail)).email
  return email
}

// 获取验证码
export const apiSend = async (email) => {
  const url = `${API_BASE}/api/bigget/send_code`;
  return httpPost(url, {email})
}

// 校验验证码
export const apiVerifyEmail = async (email, code) => {
  const url = `${API_BASE}/api/bigget/verify_email`;
  return httpPost(url, {email, code})
}

// 充值
export const apiPreRecharge = async (data,token) => {
  const url = `${API_GAME}/api/recharge/buy_with_email`;
  return httpPost(url, data,token)
}

// 任务进度
export const apiProgress = async (email) => {
  const url = `${API_GAME}/api/activity/bitget/mission/newuser/progress?email=${email}`;
  return httpGet(url)
}


// https://market-test.kingsome.cn/api/recharge/goods?net_id=13473
export const apiGoods = async (net_id, account_address) => {
  const url = `${API_GAME}/api/recharge/goods?net_id=${net_id}&account_address=${account_address}`;
  return httpGet(url)
}