import store from '../store'
import { env } from '../static/config'
export function requestApi (reqUrl, type = 'POST', data = {}, auth = '', multipart = false, arraybuffer = false) {
  if (!reqUrl) { return }
  let headers = {}

  if (auth === 'seller') {
    headers['X-DS-KEY'] = store.state.seller.token
  }
  type = type.toUpperCase()
  reqUrl = env.API_HOST + reqUrl
 
   return new Promise((resolve, reject) => {
     function returnData(res) {
       if(arraybuffer){
         resolve(res.data)
       }else{
         if (res.data.code === 10000) {
           resolve(res.data)
         } else if (res.data.code === 13001) {
           uni.navigateTo({
             url: '/pages/home/sellerlogin/Login?clear=1'
           }) // token过期，需要删除
         } else {
           reject(res.data)
         }
       }
       
     }
     if (multipart) {
       var filePath = data.filePath
       var name = data.name
       delete data.filePath
       uni.uploadFile({
         url: reqUrl,
         filePath: filePath,
         name: name,
         formData: data,
         header: headers,
         success: (res) => {
           res.data = JSON.parse(res.data)
           returnData(res)
         },
         fail: (error) => {
           reject(error)
         }
       })
     } else {
       uni.request({
         url: reqUrl,
         data: data,
         header: headers,
         method: type,
         withCredentials: true,
         responseType:arraybuffer?'arraybuffer':'text',
         success: (res) => {
           returnData(res)
         },
         fail: (error) => {
           reject(error)
         },
       })
     }
 
   })
 }
 export function requestRaw(reqUrl, type = 'POST', data = {}) {
   type = type.toUpperCase()
 
   return new Promise((resolve, reject) => {
     uni.request({
       url: reqUrl,
       data: data,
       method: type,
       withCredentials: true,
       success: (res) => {
         resolve(res.data)
       },
       fail: (error) => {
         reject(error)
       }
     })
 
   })
 }