import config from '../ver.config';
import { getToken, Toast } from './tool';
import { getStorage, setStorage } from "./storage"
import { useUserStore, useLoadingStore, useSystemStore } from '@/store';
import { storeToRefs } from "pinia";

let useUser = null;
let loadingStore = null;
let useSystem = null
export const BaseUrl = config.newUrl;
let pendingRequests = 0;
function openLoading(isLoading) {
  useUser = useUserStore()
  loadingStore = useLoadingStore()
  if (isLoading == undefined || isLoading == false) {
    if (pendingRequests == 0) {
      loadingStore.show()
    }
    pendingRequests++;
    useUser.setloadingNum(pendingRequests);
  }
}
function hideLoading() {
  useUser = useUserStore()
  loadingStore = useLoadingStore()
  if (pendingRequests > 0) {
    pendingRequests--;
  }
  if (pendingRequests == 0) {
    loadingStore.hide();
  }
}

const request = (url, method, { header, data }) => new Promise((resolve, reject) => {
  const { isLoading, ...newheader } = header;
  openLoading(isLoading);
  useUser = useUserStore()
  uni.request({
    url: BaseUrl + '/api' + url,
    header: {
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json;charset=UTF-8',
      'X-Requested-With': 'XMLHttpRequest',
      "authId": useUser.getAuthId,
      ...newheader,
    },
    data: { ...data },
    method,
    timeout: 600000,
    responseType: 'json',
    success: res => {
      hideLoading();
      if (res.statusCode == 200) {
        const { ret } = res.data;
        if (ret === -1) {
          const pages = getCurrentPages();
          const currentPage = pages[pages.length - 1];
          const path = currentPage.route;
          if (path === 'pages/login/login') {
            return;
          }
          const query = currentPage.options || {};
          const queryStr = Object.keys(query).map(key => `${key}=${query[key]}`).join('&');
          const fullPath = queryStr ? `/${path}?${queryStr}` : `/${path}`;
          setStorage('beforeLoginPage', fullPath);
          uni.navigateTo({
            url: "/pages/login/login"
          })
          return
        }
        useUser.setloadingNum(pendingRequests);
        resolve(res)
      }
    },
    fail: err => {
      hideLoading();
      useUser.setloadingNum(pendingRequests);
      useSystem = useSystemStore()
      const { isConnected } = storeToRefs(useSystem);
      isConnected.value && Toast(err.errMsg);
    }
  });
})
export const $get = (url, params, other) => {
  return request(url, "GET", {
    data: params,
    header: {
      'token': getToken(),
      "lang": getStorage(config.langName) || config.lang,
      ...other,
    }
  })
}
export const $post = (url, data, other) => {
  return request(url, 'POST', {
    data,
    header: {
      'token': getToken(),
      "lang": getStorage(config.langName) || config.lang,
      ...other
    }
  });
}
export const $upload = (filePath, option = {}) => new Promise((resolve, reject) => {
  openLoading();
  let { ...formData } = option
  const url = BaseUrl + '/api/users/upload';
  return uni.uploadFile({
    url,
    filePath,
    name: 'image',
    header: {
      'token': getToken(),
      "lang": getStorage(config.langName) || config.lang,
    },
    success: (e) => {
      hideLoading()
      let res = JSON.parse(e.data);
      const { ret } = res;
      if (ret == 1) {
        resolve(res)
      } else {
        if (ret === -1) {
          const pages = getCurrentPages();
          const currentPage = pages[pages.length - 1];
          const path = currentPage.route;
          if (path === 'pages/login/login') {
            return;
          }
          const query = currentPage.options || {};
          const queryStr = Object.keys(query).map(key => `${key}=${query[key]}`).join('&');
          const fullPath = queryStr ? `/${path}?${queryStr}` : `/${path}`;
          setStorage('beforeLoginPage', fullPath);
          uni.navigateTo({
            url: "/pages/login/login"
          })
          return
        }
        Toast(res.msg);
      }
      reject(res)
    }, fail: (err) => {
      hideLoading()
      reject(err)
    }
  })
})

export function $uploadFile({ filePath, name, onProgress }) {
  openLoading();
  return new Promise((resolve, reject) => {
    const url = BaseUrl + '/api/users/video';
    const uploadTask = uni.uploadFile({
      url,
      filePath,
      name,
      header: {
        'token': getToken(),
        "lang": getStorage(config.langName) || config.lang,
      },
      success: (e) => {
        hideLoading()
        let res = JSON.parse(e.data);
        const { ret } = res;
        if (ret == 1) {
          resolve(res)
        } else {
          if (ret === -1) {
            const pages = getCurrentPages();
            const currentPage = pages[pages.length - 1];
            const path = currentPage.route;
            if (path === 'pages/login/login') {
              return;
            }
            const query = currentPage.options || {};
            const queryStr = Object.keys(query).map(key => `${key}=${query[key]}`).join('&');
            const fullPath = queryStr ? `/${path}?${queryStr}` : `/${path}`;
            setStorage('beforeLoginPage', fullPath);
            uni.navigateTo({
              url: "/pages/login/login"
            })
            return
          }
          Toast(res.msg);
        }
        reject(res)
      }, fail: (err) => {
        hideLoading()
        reject(err)
      }
    })

    // 监听进度
    uploadTask.onProgressUpdate((e) => {
      onProgress && onProgress(e)
    })
  })
}