export default function getOrigin(urlStr: string = '', type: string = 'http') {
  const origin = import.meta.env.VITE_SERVER_ORIGIN 
  const nginxProxy = import.meta.env.VITE_NGINX_PROXY
  const suffixUrl = import.meta.env.VITE_API_SUFFIX_URL
  const url = nginxProxy + suffixUrl + urlStr
  if (type === 'ws') {
    if (origin.includes('https://')) {
      return origin.repalce('https://', 'wss://') + url
    } else if (!origin) {
      if (window.location.protocol === 'https:') {
        return `wss://${window.location.host}${url}`
      } else {
        return `ws://${window.location.host}${url}`
      }
    }
    return origin.repalce('http://', 'ws://') + url
  }

  // 如果配置的第三方服务直接是http开头的，就直接使用即可
  if (urlStr.includes('http')) {
    return urlStr
  } else if (origin) {
    return `${origin}${url}`
  } else {
    return `${window.location.origin}${url}`
  }
}

// 如果 modbus服务  ice104协议网关服务 指数管理服务
export function getOtherServersOrigin(urlStr: string = '') {
  const origin = import.meta.env.VITE_SERVER_ORIGIN || window.location.origin
  const nginxProxy = import.meta.env.VITE_NGINX_PROXY
  return origin + nginxProxy + urlStr
}

// 规则引擎
export function getRuleServerOrigin(urlStr: string = '') {
  return getOnlyPartOrigin(import.meta.env.VITE_RULE_SERVER_URL) + urlStr
}

// 流媒体服务
export function getMediaOrigin(urlStr: string = '') {
  const origin = import.meta.env.VITE_SERVER_ORIGIN || window.location.origin
  const VITE_MEDIA_SERVER_URL = import.meta.env.VITE_MEDIA_SERVER_URL
  if (VITE_MEDIA_SERVER_URL.startsWith('http')) {
    return VITE_MEDIA_SERVER_URL + urlStr
  } else if (VITE_MEDIA_SERVER_URL.startsWith(':')) {
    return getOnlyPartOrigin(VITE_MEDIA_SERVER_URL) + urlStr
  } else {
    return origin + VITE_MEDIA_SERVER_URL + urlStr
  }
}

export function getSSEOrigin(urlStr: string = '') {
  const origin = import.meta.env.VITE_SERVER_ORIGIN || window.location.origin
  const nginxProxy = import.meta.env.VITE_NGINX_PROXY
  return origin + nginxProxy + urlStr
}

export function getOnlyPartOrigin(baseUrl: string = '') {
  // 兼容只有端口号不一样的情况
  if (baseUrl?.startsWith(':')) {
    return window.location.protocol + '//' + window.location.hostname + baseUrl
  }
  return baseUrl || window.location.origin
}