//  配置请求根路径
// <!-- <l-painter-text text="好好的美食" css="width:100%;height:128rpx;background:#FFFFFF;textAlign:center;color:#3D3D3D;fontSize:32rpx;borderRadius:0 0 32rpx 32rpx;"></l-painter-text> -->
const BASE_URL = process.env.UNI_BASE_URL;
import { showToast } from "@/utils/index";

const request = (requesUrl, data, method = "GET") => {
  // console.log("走进来了");
  let url = `${BASE_URL}${requesUrl}`;
  return new Promise((resolve, reject) => {
    let header = {
      "Content-Type": "application/json; charset=UTF-8",
      "Authorization-Business": uni.getStorageSync("storage_key"),
    };
    uni.request({
      url: url,
      data: data,
      method: method,
      header: header,
      success: (res) => {
        const { data } = res;
        // console.log(res);
        if (data.code !== "") {
          //  判断是不是 token 过期了
          const tokenerr = [20003, "20003", 20004, "20004", 20005, "20005"];
          if (tokenerr.includes(data.code)) {
            //  清除本地缓存所有的数据
            uni.clearStorageSync();
            setTimeout(() => {
              //  跳转回登陆页面
              uni.redirectTo({
                url: "/pages/login/index"
              });
            }, 1000);

            showToast("登陆超时，请重新登陆", "none", 1000);
            return;
          }
          showToast(data.message || "系统突然出差了，请稍后再试","none",2000)
          return resolve(data);
        }
        return resolve(data);
      },

      fail: (res) => {
        reject(res);
        showToast("系统突然出差了，请稍后再试", "none", 2000);
      },
    });
  });
};
//不带token接口请求，
const request1 = (requesUrl, data, method = "GET") => {
  let url = `${BASE_URL}${requesUrl}`;
  return new Promise((resolve, reject) => {
    let header = {
      "Content-Type": "application/json; charset=UTF-8",
    };
    uni.request({
      url: url,
      data: data,
      method: method,
      header: header,
      success: (res) => {
        const { data } = res;
        if (data.code !== "") {
          //  判断是不是 token 过期了
          const tokenerr = [20003, "20003", 20004, "20004", 20005, "20005"];
          if (tokenerr.includes(data.code)) {
            //  清除本地缓存所有的数据
            uni.clearStorageSync();
            setTimeout(() => {
              //  跳转回登陆页面
              uni.redirectTo({
                url: "/pages/login/index",
              });
            }, 1000);

            showToast("登陆超时，请重新登陆", "none", 1000);
            return;
          }
          // showToast(data.message || "系统突然出差了，请稍后再试","none",2000)
          return resolve(data);
        }
        return resolve(data);
      },

      fail: (res) => {
        reject(res);
        showToast("系统突然出差了，请稍后再试", "none", 2000);
      },
    });
  });
};

export { request, request1 };
