import qs from 'qs';
import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';

const pack = require('../../package.json');

export function token({host = '', key, secret, device}) {
  return axios.post(`${host}/store/auth`, qs.stringify({key, secret, device}));
}

export async function refreshToken() {
  const auth = await AsyncStorage.getItem('auth');
  if (auth) {
    try {
      const {refresh_token} = JSON.parse(auth);
      return await axios.get('/auth/refresh', {
        headers: {Authorization: `Bearer ${refresh_token}`},
      });
    } catch (e) {
      return {data: null};
    }
  }
  return {data: null};
}

export function version() {
  return axios.put('/store/version', qs.stringify({version: pack.version}));
}

export function region() {
  return axios.get('/store/region');
}

export function door({userId}) {
  return axios.post('/store/door', qs.stringify({userId}));
}

export function wxdoor({
  userId,
  openid,
  wxtoken,
  nickname,
  alipayUid,
  fToken,
  phone,
  sense,
  orderId,
  authCode,
}) {
  return axios.post(
    '/store/wxdoor',
    qs.stringify({
      userId,
      openid,
      wxtoken,
      nickname,
      alipayUid,
      fToken,
      phone,
      sense,
      orderId,
      authCode,
    }),
  );
}

export function scaleData() {
  return axios.get('/store/scaleData');
}

export function sendsms({phone, faceType}) {
  return axios.post('/store/sendsms', qs.stringify({phone, faceType}));
}

export function verifysms({phone, code, userId, faceType}) {
  return axios.post(
    '/store/verifysms',
    qs.stringify({phone, code, userId, faceType}),
  );
}

export function getAdvertising(action) {
  return axios.get(`/store/advertising?${qs.stringify(action)}`);
}

export function getStore({group}) {
  return axios.get(`/store/setting/${group}`);
}

export function findModuleSetting({group}) {
  return axios.get(`/store/module/setting/${group}`);
}
