import TUIChatEngine, {
  TUIChatService
} from '@tencentcloud/chat-uikit-engine-lite'
import { CHAT_MSG_CUSTOM_TYPE } from '../TUIKit/constant'
import { useAuthUser } from '../composables/useAuthUser'
import { useUserStore } from '../stores/user'

/** 格式化时间显示 */
const formatTime = date => {
  const minutes = Math.floor(date / 60)
  const seconds = date % 60
  return `${minutes.toString().padStart(2, '0')}:${seconds
    .toString()
    .padStart(2, '0')}`
}

/** 通话消息发送 */
export const sendCallMsg = async state => {
  const { resetTime, stopTimer } = useUserStore()
  const { callUserId, callMode, callDuration, tencentUserSig } =
    useAuthUser()
  const to = callUserId.value
  const userID = tencentUserSig.value.userId
  if (to !== userID) {
    let title = ''
    if ([0, 11].includes(state)) {
      title = { 0: '已挂断', 11: '对方已拒绝' }[state]
    } else {
      title = `通话时长 ${formatTime(callDuration.value)}`
    }

    const payload = {
      data: JSON.stringify({
        businessID:
          callMode.value == 0
            ? CHAT_MSG_CUSTOM_TYPE.VOICE_CALL
            : CHAT_MSG_CUSTOM_TYPE.VIDEO_CALL,
        title,
        userID: to
      }),
      description: title,
      extension: title
    }
    const options = {
      to,
      payload,
      conversationType: TUIChatEngine.TYPES.CONV_C2C,
      needReadReceipt: false
    }
    resetTime()
    await TUIChatService.sendCustomMessage(options)
  } else {
    resetTime()
  }
  
  if (callMode.value == 1) {
    stopTimer()
  }
}
