import Taro from "@tarojs/taro"
import { pageToLogin } from "./utils"
import { HTTP_STATUS } from './config'

const customInterceptor = (chain) => {
  const requestParams = chain.requestParams
  // pageToLogin();
  return chain.proceed(requestParams).then(res => {
    // 只要请求成功，不管返回什么状态码，都走这个回调
    if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
      Taro.setStorageSync("token", "");
      Taro.setStorageSync('userInfor', "");
      pageToLogin()
      // TODO 根据自身业务修改
      return {
        error: [
          {
            message:'请求资源不存在,请重新登录',
            start: 404
          }
        ]
      };

    } else if (res.statusCode === HTTP_STATUS.SERVER_ERROR) {
      return {
        error: [
          {
            message:'系统错误,请稍后再试',
            start: 500
          }
        ]
      }

    } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
      return Promise.reject("服务端出现了问题")

    } else if (res.statusCode === HTTP_STATUS.FORBIDDEN || res.statusCode === HTTP_STATUS.NO_PERMISSION) {
      Taro.setStorageSync("token", "");
      Taro.setStorageSync('userInfor', "");
      pageToLogin()
      // TODO 根据自身业务修改
      return;

    } else if (res.statusCode === HTTP_STATUS.AUTHENTICATE) {
      Taro.setStorageSync("Authorization", "")
      pageToLogin()
      return Promise.reject("需要鉴权")

    } else if (res.statusCode === HTTP_STATUS.SUCCESS) {
      if(res.data.error && res.data.error.length !== 0 && res.data.error[0].field === '403'){
        Taro.setStorageSync("token", "");
        Taro.setStorageSync('userInfor', "");
        pageToLogin()
      }
      return res.data
    }
  })
}

const interceptors = [customInterceptor, Taro.interceptors.logInterceptor]

export default interceptors
