<template>
    <div class="flex text-sm  flex-col text-gray-900  m-auto  sm:max-w-screen-sm
    md:border-x-2 chat-container"  v-loading.fullscreen.lock="loading"  :element-loading-text="connectionTips"
    id="chat-container">
        <ChatHeader ref="chatHeaderRef"/>
        <ChatContent ref="chatContentRef" @onSendSuccess="onSendSuccess" @onStatusChange="onStatusChange"/>
        <ChatFooter @send-message="sendMessage" ref="chatFooterRef"/>
    </div>
  <el-dialog v-model="dialogVisible" center align-center width="70%">
    <template #default>
      <div>
        <span >Connection to online customer service failed. Please close this page and re-enter.</span>
      </div>
    </template>
    <template #footer>
      <div>
        <button
                class="flex w-full justify-center rounded-md bg-[#F96825] px-3 py-1.5
            text-sm font-semibold leading-6 text-white shadow-sm
            hover:bg-[#F96825] focus-visible:outline focus-visible:outline-2
            focus-visible:outline-offset-2 focus-visible:outline-indigo-600" @click="closeDialog">Confirm</button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import ChatHeader from './components/ChatHeader.vue'
import ChatContent from './components/ChatContent.vue'
import ChatFooter from './components/ChatFooter.vue';
import {getAnonymousUserInfo, getUserInfo} from '@/api/user'
import * as AuthUtils from '@/utils/auth'
import { nextTick, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router'
import { useUserInfoStore } from '@/stores/message';
import type { Message } from '@/types/global';

const chatContentRef = ref()
const chatFooterRef = ref()
const chatHeaderRef = ref()

const userInfoStore = useUserInfoStore()
const route = useRoute()
const userInfo = ref({})
const loading = ref(false)
const dialogVisible = ref(false)
const connectionTips = ref('Connecting to support...')
const fetchUserInfo = async () => {
  loading.value = true
  try {
    const res = await getUserInfo()
    userInfo.value = res.data
    userInfoStore.setUserInfo(userInfo.value)
    loading.value = false
    await chatContentRef.value.initConnect()
  }catch (error) {
    dialogVisible.value = true
  }finally {
    connectionTips.value = 'Connect failed, please close this page and re-enter.'
  }
}

const fetchAnonymousUserInfo = async () => {
  loading.value = true
  try {
    const key = route.query.k as string
    const res = await getAnonymousUserInfo(encodeURIComponent(key))
    userInfo.value = res.data
    userInfoStore.setUserInfo(userInfo.value)
    const accessToken  = res.data.accessToken
    const refreshToken = res.data.refreshToken
    AuthUtils.setToken({ accessToken, refreshToken})
    loading.value = false
  }catch (error) {
    dialogVisible.value = true
  } finally {
    connectionTips.value = 'Connect failed, please close this page and re-enter.'
  }
}


const sendMessage = (message:Message) => {
  chatContentRef.value.sendMessage(message)
  chatContentRef.value.payAudio()
}

const onSendSuccess = () => {
  chatFooterRef.value.onSendSuccess()
  chatContentRef.value.scrollToBottom()
}

const closeDialog = () => {
   dialogVisible.value = false
}

// 修改连接状态
const onStatusChange = (status: boolean) => {
  chatHeaderRef.value.changeOnlineStatus(status)
  loading.value = !status
}

// js设置高度
const initHeight = () => {
  const chatContainer = document.getElementById("chat-container")
  if (chatContainer) {
    console.log('window.innerHeight', window.innerHeight)
    chatContainer.style.height = `${window.innerHeight}px`;
  }
}

onMounted(async () => {
  initHeight()
  const key = route.query.k as string
  if (!key) {
    const accessToken = route.query.t as string
    if (!accessToken) {
      dialogVisible.value = true
      return
    }
    const refreshToken = route.query.r as string
    AuthUtils.setToken({ accessToken, refreshToken})
    await fetchUserInfo()
  } else {
    // 直接链接
    await fetchAnonymousUserInfo()
    await chatContentRef.value.initConnect()

  }

})
</script>


<style lang="css" scoped>
</style>
