import useNetWork from "./useNetWork.js";
import { useStore } from "vuex";
import { getLogin } from "@/utils/auth.js";

function fetch(method) {
  return function (url, data, otherParams = {}) {
    // if (method === 'POST' || method === 'PUT') {
    //   data = {
    //     param: data,
    //   };
    // }
    const sessionId = uni.getStorageSync("sessionId");
    //定时器
    return new Promise((resolve, reject) => {
      uni.request({
        url,
        method,
        data,
        header: {
          token: sessionId,
        },
        success(data) {
          if (data.statusCode === 200) {
            if (data.data.code === 200) {
              resolve(data.data.data);
            } else if (data.data.code === 2401) {
              uni.showToast({
                title: `登录过期，正在重新登录`,
                icon: "none",
                duration: 2000,
              });
              getLogin();
							resolve(data.data.message);
            } else if (data.data.code === 500 && data.data.message === '您的账号未注册，请先注册' ||
						data.data.code === 2402) {
							resolve('用户未注册');
						} else {
              uni.showToast({
                // title: "系统异常，请稍后再试！",
                title: `${data.data.message}`,
                icon: "none",
                duration: 2000,
              });
              reject(data);
            }
          } else {
            reject(data);
          }
        },
        fail(err) {
          reject(err);
        },
        ...otherParams,
      });
    });
  };
}

export default {
  get: fetch("GET"),
  post: fetch("POST"),
  put: fetch("PUT"),
  delete: fetch("DELETE"),
  connect: fetch("CONNECT"),
  head: fetch("HEAD"),
  options: fetch("OPTIONS"),
  trace: fetch("TRACE"),
};
