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

<script>
import {mapState} from 'vuex'
import fetchApi from "@/services/fetchApi";
export default {
  name: "App",
  computed: {
    ...mapState({
      token: state => state.token
    }),
  },
  data(){
    return {

    }
  },
  mounted() {
    let token = sessionStorage.getItem('token')
    if (token){this.initVoiceCall();}
  },
  methods: {
    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)
        })
        // 呼入事件
        window.tccc.on('callIn', (callback) => {
          // acceptID = callback.id;
          console.log(callback, '---呼入')
        })
      })
    },
    initVoiceCall(){
      // 是否已经创建
      if (this.scriptWithDataSetExists('telephone')){return}
      fetchApi.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();
        }
      }
    }
  }
};
</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>
