import Taro from '@tarojs/taro'
import { baseUrl } from '../config'
import { setItem, getItem, removeItem } from './index'
interface Options {
  url: string,
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
}

export default (options: Options) => {
  const url = Taro.getEnv() === 'WEAPP' ? `${baseUrl}${options.url}` : options.url
  const token = getItem('token')
  const header = Taro.getEnv() === 'WEAPP' ? {
    token,
    'Content-Type': 'application/json'
  } : {
      'Content-Type': 'application/json'
    }
  return Taro.request({
    url,
    data: {
      ...options.data,
    },
    header,
    method: options.method || 'GET',
    credentials: "include"
  }).then((res: any) => {
    const { data } = res;
    if (res.statusCode === 401) {
      removeItem("token")
      Taro.redirectTo({ url: '/pages/login/index' })
      Taro.showToast({ title: res.data.message, icon: "none" })
    }
    if (data.content && data.content.sessionId) {
      setItem({ key: 'token', data: data.content.sessionId })
    }
    return data
  }).catch(re => {
    try {
      re.json().then(({ status, message }) => {
        if (status === 401) {
          removeItem("token")
          Taro.redirectTo({ url: '/pages/login/index' })
        }
        Taro.showToast({ title: message, icon: "none" })
        throw re;
      })
    } catch (e) {
      Taro.showToast({ title: "系统出错，请稍后重试", icon: "none" })
      throw re;
    }
  })
};
