import { useGlobalStore } from "@/store/useStore"
import { hLoading, sLoading, toast } from "./util"

export const baseUrl = "/k3cloud"
// 部署到iis上用的
// export const baseUrl = "https://weixin3.lingqingkeji.com/k3cloud"
// export const baseUrl = "/XiBU"

const globalStore = useGlobalStore()

// 封装公共申请办法
function request(
  url: string,
  method: "GET" | "POST" | "PUT" | "DELETE",
  data?: object | any,
  responseType?: string
) {
  return new Promise<any>(function (resolve, reject) {
    let header: any
    sLoading()
    let pages = getCurrentPages()
    let page = pages[pages.length - 1] // 当前页面
    if (
      page.route !== "pages/login/index" &&
      page.route !== "pages/login/register" &&
      JSON.stringify(globalStore.infoData) === "{}"
    ) {
      uni.reLaunch({ url: "/pages/login/index" })
    }
    header = { "Content-Type": "application/json" }
    url = baseUrl + url

    uni.request({
      url,
      method,
      data,
      header,
      responseType,
      success(res: any) {
        hLoading()
        if (res.data.code == 200) {
          resolve(res)
        } else if (res.data.code == 500 || res.data.code === 401) {
          toast(res.data.msg)
          reject(res)
        } else if (res.data.code == 501 || res.data.code == 911) {
          uni.reLaunch({
            url: "/pages/login/index",
            success() {
              uni.showToast({
                title: "请登录",
                icon: "none",
              })
            },
          })
        } else {
          console.log(res, "非200错误")
          //其余异样
          reject(res)
        }
      },
      fail(err: any) {
        hLoading()
        //申请失败
        uni.showToast({
          title: "连接服务器失败",
          icon: "none",
        })
        reject(err)
      },
    })
  })
}

export default request
