<template>
  <!--测试 张三 : 17260625724565   李四: 17260625724123-->
  <div class="live-call-block">
    <live-call-item-home ref="recordLeftRef" :recordObj="recordLeftObj" :headData="leftHeadData" lineName="线路一"/>
    <live-call-item-home ref="recordRightRef" :recordObj="recordRightObj" :headData="rightHeadData" lineName="线路二"/>
  </div>
</template>

<script setup>
import {useAuthStore} from '@/stores/userstore.js'
import {getToken} from '@/utils/auth'
import {usePermisstionStroe} from '@/stores/permisstion'
import {getCurrentContent} from "@/api/workbench";

const permisstionStore = usePermisstionStroe()
const authStore = useAuthStore()
//聊天消息滚动面板dom
const recordLeftRef = ref(null);
const recordRightRef = ref(null);
const leftHeadData = ref({
  // username: '张三',
  // phone: '13546812315',
  // orderName: '张三工单',
})
const rightHeadData = ref({
  // username: '李四',
  // phone: '18246812546',
  // orderName: '李四工单',
})
const recordLeftObj = ref({
  content: []
})
const recordRightObj = ref({
  content: []
})
let socket = reactive("");
let token = getToken();
let send = {
  type: "ping",
};
// if(localStorage.getItem('recordLeftObj')){
//   recordLeftObj.value=JSON.parse(localStorage.getItem('recordLeftObj'))
// }
// if(localStorage.getItem('recordRightObj')){
//   recordRightObj.value=JSON.parse(localStorage.getItem('recordRightObj'))
// }
const getCurrentMsg=(line)=>{
  getCurrentContent(line).then(res=>{
    // console.info("🚀 ~method:res -----", res)
    if(line==1){
      recordLeftObj.value.content=res.data
    }else if(line==2){
      recordRightObj.value.content=res.data
    }
  })
}
getCurrentMsg(1)
getCurrentMsg(2)
//滚动面板自动滑动到底部
const scrollToBottom = (scrollbarRef) => {
  if (scrollbarRef) {
    const container = scrollbarRef.$el.querySelector('.el-scrollbar__wrap');
    container.style.scrollBehavior = 'smooth'; // 添加平滑滚动效果
    container.scrollTop = container.scrollHeight;
  }
};


const setWsUrl = (url) => {
  return (window.location.protocol === 'http:' ? "ws://" : "wss://") + window.location.host + import.meta.env.VITE_BASE_URL + url;
}
const handleLogout = () => {
  authStore.userLogout()
  permisstionStore.removeMenu()
  router.push('/login')
}
const handleShowDeadLine=(recordObj,data)=>{
  let flag=false
  if(recordObj.content&&recordObj.content.length>0){
      flag=recordObj.content[recordObj.content.length-1]?.callIdNumber!=data.callIdNumber
  }
  return flag;
}
const initWebSocket = () => {
  try {
    // const wsUrl=setWsUrl(`/ws/text/${token}`)
    const wsUrl = `ws://frp.feashow.cn:31800/ws/text/${token}`
    // const wsUrl = `ws://112.19.165.99:20002/api/ws/text/${token}`
    socket = new WebSocket(wsUrl)
    // 2. ws.send()给服务器发送信息
    //连接发生错误的回调方法
    socket.onerror = function () {
      console.log("ws连接发生错误");
    };
    //连接成功建立的回调方法
    socket.onopen = function () {
      // let authInfo = {
      //   token: getToken(),
      //   type: "auth",
      //   cluster: "notice"
      // }
      // socket.send(JSON.stringify(authInfo))
      console.log("ws连接成功");
    }
    //接收到消息的回调方法
    socket.onmessage = function (event) {
      let data = JSON.parse(event.data)
      if (data.type !== 'pong') {
        if (data.type === 'error') {
          handleLogout()
          return;
        } else if (data.type === 'failed') {
          initWebSocket()
          return;
        }
        console.log("服务器返回的信息: ", data);
        if (data.type == '1') {
          recordLeftObj.value.name=data.name
          recordLeftObj.value.phone=data.phone
          recordLeftObj.value.type=data.type
          recordLeftObj.value.orderName=data.orderName
          let flag=handleShowDeadLine(recordLeftObj.value,data)
          console.info("🚀 ~method:flag -----", flag)
          if(flag){
            recordLeftObj.value.content.push({
              isLine:true,
              lineMsg: "一轮通话结束~~",
              speaker: data.content.speaker
            })
          }
          recordLeftObj.value.content.push(data.content)
          localStorage.setItem('recordLeftObj',JSON.stringify(recordLeftObj.value))
          // console.info("🚀 ~method:onmessage -----", recordLeftObj.value)
          nextTick(() => {
            scrollToBottom(recordLeftRef.value)
          })
        } else {
          recordRightObj.value.name=data.name
          recordRightObj.value.phone=data.phone
          recordRightObj.value.type=data.type
          recordRightObj.value.orderName=data.orderName
          let flag=handleShowDeadLine(recordRightObj.value,data)
          console.info("🚀 ~method:flag -----", flag)
          if(flag){
            recordRightObj.value.content.push({
              isLine:true,
              lineMsg: "一轮通话结束~~",
            speaker: data.content.speaker
            })
          }
          recordRightObj.value.content.push(data.content)
          // console.info("🚀 ~method:onmessage -----", recordRightObj.value)
          localStorage.setItem('recordRightObj',JSON.stringify(recordRightObj.value))
          nextTick(() => {
            scrollToBottom(recordRightRef.value);
          })
        }
      }
    }
    //连接关闭的回调方法
    socket.onclose = function () {
      // initWebSocket()
      console.log("ws连接关闭");
    }
    setInterval(() => {
      socket.send(JSON.stringify(send))
    }, 5000)
  } catch (e) {
    console.log(e)
    console.log("ws连接失败");
  }
}
initWebSocket()
</script>

<style lang="scss" scoped>
.live-call-block {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-around;
  height: 50vh;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 6px;
  }

  // 滚动条轨道
  &::-webkit-scrollbar-track {
    background: rgb(239, 239, 239);
    border-radius: 2px;
  }

  // 小滑块
  &::-webkit-scrollbar-thumb {
    background: rgba(80, 81, 82, 0.29);
    border-radius: 10px;
  }
}
</style>
