import globalConfig from '@/common/config/global';
import cache from '@/common/utils/cache';
import { useUserStore } from '@/pinia/user';

const request = (options) => {
  const defaultOptions = {
    url: '',
    method: 'GET',
    data: {},
    header: { 'Content-Type': 'application/json' },
    timeout: globalConfig.api.timeout
  };

  const opts = { ...defaultOptions, ...options };
  let token = '';
  try {
    const userStore = useUserStore();
    token = userStore.token || cache.get(globalConfig.cache.tokenKey);
  } catch (err) {
    token = cache.get(globalConfig.cache.tokenKey);
  }

  if (token) {
    opts.header['Authorization'] = `Bearer ${token}`;
  }

  opts.url = globalConfig.api.baseUrl + opts.url;

  return new Promise((resolve, reject) => {
    uni.request({
      ...opts,
      success: (res) => {
        if (res.statusCode === 200) {
          const { code, data, msg } = res.data;
          if (code === 0) {
            resolve(data);
          } else if (code === 401) {
            const userStore = useUserStore();
            userStore.logout();
            uni.showToast({ title: msg || '登录过期', icon: 'none' });
            reject(res.data);
          } else {
            uni.showToast({ title: msg || '请求失败', icon: 'none' });
            reject(res.data);
          }
        } else {
          uni.showToast({ title: `错误：${res.statusCode}`, icon: 'none' });
          reject(res);
        }
      },
      fail: (err) => {
        uni.showToast({ title: '网络失败', icon: 'none' });
        reject(err);
      }
    });
  });
};

export const get = (url, data = {}, options = {}) => request({ url, method: 'GET', data, ...options });
export const post = (url, data = {}, options = {}) => request({ url, method: 'POST', data, ...options });
export const put = (url, data = {}, options = {}) => request({ url, method: 'PUT', data, ...options });
export const del = (url, data = {}, options = {}) => request({ url, method: 'DELETE', data, ...options });

export default request;