<template>
  <div id="app">
    <router-view></router-view>

    <VoiceCallDialog v-if="acceptDialog" :acceptDialog.sync="acceptDialog" />
  </div>
</template>

<script>
import {mapState} from 'vuex'
import voiceCall from "@/services/voiceCall";
export default {
  components: {
    VoiceCallDialog: () => import('./components/VoiceCallDialog'),
  },
  name: "App",
  computed: {
    ...mapState({
      token: state => state.token
    }),
  },
  data(){
    return {
      acceptDialog: null,
    }
  },
  mounted() {
    let token = sessionStorage.getItem('token')
    if (token){this.initVoiceCall();}
    let brokerEndpoint = sessionStorage.getItem('brokerEndpoint')
    if (brokerEndpoint){this.$stompSocket.initStomp(brokerEndpoint,a => this.socketSucc(a), b => this.socketErr(b));}
  },
  methods: {
    socketSucc(frame) {
      console.log(frame, '---初始化成功app')
      // '/user/'+userId+'/queue/video'
      let userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
      let url = `/user/${userInfo.phone}/queue/video`
      // console.log(url, '---订阅地址')
      this.$stompSocket.subscription(url, this.receivePush)
    },
    socketErr(frame) {
      console.log(frame, '---初始化失败app')
    },
    receivePush(message) {
      console.log(message, '---接收订阅消息')
      this.$store.commit('setVideoReminder', message.body)
    },
    scriptWithDataSetExists(dataId) {
      const scriptElement = document.querySelector(`script[data-telephone="${dataId}"]`);
      return scriptElement !== null;
    },
    injectTCCC ({ token, sdkAppId, userId, sdkUrl }) {
      const scriptDom = document.createElement('script')
      scriptDom.setAttribute('crossorigin', 'anonymous')
      scriptDom.dataset.token = token
      scriptDom.dataset.sdkAppId = sdkAppId
      scriptDom.dataset.userid = userId
      scriptDom.src = sdkUrl
      scriptDom.dataset.telephone = 'telephone'
      // 集成UI Dom
      // script.dataset.renderDomId = "renderDom";
      document.body.appendChild(scriptDom)
      scriptDom.addEventListener('load', () => {
        // 隐藏UI
        window.tccc.UI.hide();
        // ready事件必须监听，否则容易发生tccc不存在的错误，所有呼入呼出的逻辑必须在ready事件触发后才可以调用
        window.tccc.on('ready', () => {
          // 以下为Demo逻辑，非业务必须。业务代码主要实现都在这个部分
          console.log('---初始化成功')
        })
        // 失败事件
        window.tccc.on('tokenExpired', ({message}) => {
          console.error('---初始化失败', message)
        })

        // this.acceptDialog = {
        //   "sessionId": "32cca051-dcae-4269-ae12-e8eca5e02146",
        //   "calleePhoneNumber": "008605305343323",
        //   "callerPhoneNumber": "008613882832314",
        //   "protectedCallee": "008605305343323",
        //   "protectedCaller": "008613882832314",
        //   "ivrPath": [
        //     {
        //       "key": "1",
        //       "label": "分支内容1"
        //     }
        //   ],
        //   "callerLocation": "四川达州移动",
        //   "timeout": 30,
        //   "type": "phone",
        //   "serverType": "staffSeat",
        //   "aiEnabled": false,
        //   "id": "32cca051-dcae-4269-ae12-e8eca5e02146",
        //   "phone": "008613882832314",
        //   "direction": "0",
        //   "startCallTime": 1736923493486
        // };
        // 呼入事件

        window.tccc.on('callIn', (data) => {
          this.acceptDialog = data;
          // this.acceptID = data.id;
          console.log(data, '---语音呼入')
        })
        // 会话结束事件
        window.tccc.on('sessionEnded', (data) => {
          this.$message.error('通话已结束！')
          this.acceptDialog = null;
          console.log(data, '---语音会话结束')
        })
      })
    },
    initVoiceCall(){
      // 是否已经创建
      if (this.scriptWithDataSetExists('telephone')){return}
      voiceCall.webCalling().then(res => {
        const {agent, token, sdkAppId, agentId, sdkURL} = res;
        // console.log(res, '---res')
        if (agent){
          let userId = agentId;
          let sdkUrl = sdkURL;
          this.injectTCCC({token, sdkAppId, userId, sdkUrl})
        }
      }).catch(err => {
        console.log(err, '---err')
      })
    },
  },
  watch: {
    token: {
      deep: true,
      handler: function (val) {
        if (val){
          // console.log(val, '---监听token1')
          this.initVoiceCall();
        }
      }
    }
  },
  beforeDestroy() {
    this.$stompSocket.deactivate();
  }
};
</script>

<style lang="scss">
@import "./assets/style/flex.scss";
@import "./assets/style/common.scss";
body,
html {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}
#app {
  width: 100vw;
  height: 100vh;
  /* font-size: 3vw; */
}
#app button {
  -webkit-tap-highlight-color: transparent;
}
.el-scrollbar__wrap{
  overflow: hidden;
}
</style>
