import Bridge from '@/utils/jsBridge2'
import { Toast } from 'vant'
import { enableLive } from '@/service/StaffService/index'
import { getCurrentUserAvatarUrl, getUserMsg } from './userMsg'
import { eRole } from '@/types/roleType'

export const sendLive = () => {
  const avatarUrl = getCurrentUserAvatarUrl()
  const finalAvatarUrl =
    window.location.protocol + '//' + window.location.host + avatarUrl

  const USER_MSG = window.localStorage.getItem('USER_MSG')
  let allow = false
  let time_section = ''

  if (!USER_MSG) {
    Toast('请先登录')
    return
  } else if (getUserMsg()?.role === eRole.user) {
    new Bridge().bridge_live({
      phone: JSON.parse(window.localStorage.getItem('USER_MSG') as string)
        ?.userInfo.phone,
      avatar: finalAvatarUrl,
      allow,
      time_section,
    })
    return
  }

  enableLive()
    .then((res) => {
      if (res.code === 200) {
        allow = res.data.allow
        time_section = res.data.time_section
      }
      new Bridge().bridge_live({
        phone: JSON.parse(window.localStorage.getItem('USER_MSG') as string)
          ?.userInfo.phone,
        avatar: finalAvatarUrl,
        allow,
        time_section,
      })
    })
    .catch(() => {
      new Bridge().bridge_live({
        phone: JSON.parse(window.localStorage.getItem('USER_MSG') as string)
          ?.userInfo.phone,
        avatar: finalAvatarUrl,
        allow,
        time_section,
      })
    })
}
