/** 云律视频咨询：iframe / web-view 内通知云律后端结束通话，并通知父页面（律师 PC 浮窗）释放状态 */

export function getCloudLawApiBase(explicitBase) {
  const base = String(explicitBase || '').trim().replace(/\/+$/, '')
  if (base) return base
  if (typeof window !== 'undefined' && window.location && window.location.origin) {
    return window.location.origin
  }
  return ''
}

export function resolveCloudLawApiUrl(path, apiBase) {
  const base = getCloudLawApiBase(apiBase)
  const normalizedPath = path.startsWith('/') ? path : `/${path}`
  return `${base}${normalizedPath}`
}

/**
 * 通知云律后端结束通话。
 * - 律师端：/api/law/voiceCall/{callId}/end（PC 同域，带登录态）
 * - 用户端：/api/applet/voiceConnection/publicEnd/{callId}?roomCode=xxx
 *   web-view 跨域调带登录态的 /{callId}/end 会被浏览器 CORS 拦截、根本到不了后端，
 *   导致「挂断后 status 一直 accepted、律师端不结束、用户端不跳转」。
 *   publicEnd 是 @CrossOrigin 公开端点，以 callId+roomCode 配对为凭证，可靠收尾。
 */
export function notifyCloudLawBackendEnd(callId, role = 'law', apiBase = '', token = '', roomCode = '') {
  if (!callId) return Promise.resolve(false)
  const isLaw = String(role).toLowerCase() === 'law'
  if (isLaw) {
    const url = resolveCloudLawApiUrl(`/api/law/voiceCall/${encodeURIComponent(callId)}/end`, apiBase)
    const header = { 'Content-Type': 'application/json' }
    if (token) {
      header.token = token.startsWith('Bearer') ? token : `Bearer ${token}`
    }
    return new Promise(resolve => {
      uni.request({ url, method: 'POST', data: {}, header, timeout: 8000, complete: () => resolve(true) })
    })
  }

  // 用户端：publicEnd（@CrossOrigin 公开端点）。凭证是 URL 里的 callId+roomCode，无需 token/body。
  // 关键：不能带 application/json 或自定义头，否则触发 CORS 预检；预检失败时浏览器会直接
  // 掐掉真正的 POST，表现为「按钮触发了但没有请求发到后端」。
  // 因此优先用 navigator.sendBeacon（简单 POST、无预检、跨域也能到达服务器）。
  const query = roomCode ? `?roomCode=${encodeURIComponent(roomCode)}` : ''
  const url = resolveCloudLawApiUrl(`/api/applet/voiceConnection/publicEnd/${encodeURIComponent(callId)}${query}`, apiBase)
  console.log('[cloudLawVoiceCall] publicEnd ->', url)
  // #ifdef H5
  try {
    if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
      const ok = navigator.sendBeacon(url)
      console.log('[cloudLawVoiceCall] sendBeacon publicEnd result:', ok)
      if (ok) return Promise.resolve(true)
    }
  } catch (e) {
    console.warn('[cloudLawVoiceCall] sendBeacon failed', e)
  }
  // #endif
  // 兜底：uni.request 不带任何自定义头 / body，尽量保持「简单请求」避免预检。
  return new Promise(resolve => {
    uni.request({
      url,
      method: 'POST',
      timeout: 8000,
      complete: (res) => {
        console.log('[cloudLawVoiceCall] publicEnd request done:', res && res.statusCode)
        resolve(true)
      }
    })
  })
}

/** PC 律师端 iframe 会议结束时，通知父页面（outbound 浮窗）清除「会议进行中」状态 */
export function notifyCloudLawParentCallEnded(callId = '') {
  if (typeof window === 'undefined') return false
  try {
    if (window.parent && window.parent !== window) {
      window.parent.postMessage({
        type: 'cloudLawCallEnded',
        action: 'cloudLawCallEnded',
        callId: String(callId || '')
      }, '*')
      return true
    }
  } catch (e) {
    console.warn('[cloudLawVoiceCall] parent postMessage failed', e)
  }
  return false
}

export function isCloudLawLawRoleInMeeting(role) {
  if (String(role || '').toLowerCase() === 'law') return true
  try {
    return typeof window !== 'undefined'
      && window.sessionStorage
      && window.sessionStorage.getItem('echo_cloud_law_meeting_role') === 'law'
  } catch (e) {
    return false
  }
}

export function isCloudLawPcIframe() {
  return typeof window !== 'undefined' && !!(window.parent && window.parent !== window)
}

/** 查询云律通话状态（律师端 /api/law/voiceCall，用户端 /api/applet/voiceConnection） */
export function queryCloudLawCallStatus(callId, role = 'law', apiBase = '', token = '') {
  if (!callId) return Promise.resolve(null)
  const endBase = String(role).toLowerCase() === 'law' ? '/api/law/voiceCall' : '/api/applet/voiceConnection'
  const url = resolveCloudLawApiUrl(`${endBase}/${encodeURIComponent(callId)}/status`, apiBase)
  const header = { 'Content-Type': 'application/json' }
  if (token) {
    header.token = token.startsWith('Bearer') ? token : `Bearer ${token}`
  }
  return new Promise(resolve => {
    uni.request({
      url,
      method: 'GET',
      header,
      timeout: 8000,
      success: (res) => {
        const body = res?.data || {}
        const payload = body.data !== undefined ? body.data : body
        resolve(payload && typeof payload === 'object' ? payload : null)
      },
      fail: () => resolve(null)
    })
  })
}

const CLOUD_LAW_HANGUP_QUERY = 'cloudLawHangup'

/** 小程序 web-view 内挂断：改 URL 触发原生页 @load，立即调 /end（不依赖 web-view 销毁） */
export function notifyNativeMiniProgramHangup() {
  // #ifdef H5
  if (typeof window === 'undefined') {
    console.warn('[cloudLawVoiceCall] bridge skip: window undefined')
    return false
  }
  try {
    const href = String(window.location.href || '')
    if (href.includes(`${CLOUD_LAW_HANGUP_QUERY}=1`)) {
      console.log('[cloudLawVoiceCall] bridge: URL 已含 cloudLawHangup=1，跳过重复重载')
      return true
    }
    const url = new URL(href)
    url.searchParams.set(CLOUD_LAW_HANGUP_QUERY, '1')
    console.log('[cloudLawVoiceCall] bridge: location.replace ->', url.toString())
    window.location.replace(url.toString())
    return true
  } catch (e) {
    console.warn('[cloudLawVoiceCall] native hangup bridge failed', e)
  }
  // #endif
  return false
}

export function isCloudLawHangupBridgeUrl(url) {
  return String(url || '').includes(`${CLOUD_LAW_HANGUP_QUERY}=1`)
}
