<template>
  <div class="home">
    <h3 style="margin-bottom: 10px;margin-top: 10px">实时通话</h3>
    <div class="real-time-call">
      <LiveCall />
    </div>
    <div class="call-history">
      <h3>历史通话记录</h3>
      <fvTable ref="tableIns" :tableConfig="tableConfig" :data="currentHistoryData" :total="currentHistoryTotal" :isLoading="isLoading"></fvTable>
      <voice ref="voiceRef" title="语音详情" :rowUrl="rowUrl" />
      <infoLiveCall ref="infoLiveCallRef" v-model:value="historyData" />
    </div>
  </div>
</template>

<script setup lang="jsx">
import {useAuthStore} from '@/stores/userstore.js'
import {getToken} from '@/utils/auth'
import {usePermisstionStroe} from '@/stores/permisstion'
import LiveCall from '@/components/liveCall/index.vue'
import Voice from '@/components/voice/index.vue'
import InfoLiveCall from '@/components/infoLiveCall/index.vue'
import {orderGetList} from "@/api/order/order";
const permisstionStore = usePermisstionStroe()
const authStore = useAuthStore()
const currentHistoryData = ref([])
const historyData = ref({})
const orderNumber = ref('')
const currentHistoryTotal = ref('')
const rowUrl = ref()
const infoLiveCallRef = ref()
const isLoading = ref(true)
const voiceRef = ref()
const tableIns = ref()
let socket = reactive("");
let token = getToken();
let send = {
  type: "ping",
};
const auths = reactive({
  record: ['order:dialogue:list'],
})
const tableConfig = reactive({
  columns: [
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width: 80,
    },
    {
      prop: 'orderNumber',
      label: '工单号',
      align: 'center',
    },
    {
      prop: 'orderName',
      label: '工单名称',
      align: 'center'
    },
    {
      prop: 'orderContent',
      label: '工单内容',
      align: 'center'
    },
    {
      prop: 'operationUser',
      // prop: 'destinationName',
      label: '处理人',
      align: 'center'
    },
    // {
    //   prop: 'knotter',
    //   // prop: 'destinationName',
    //   label: '关单人',
    //   align: 'center'
    // },
    {
      prop: 'destinationName',
      // prop: 'workOrderNumber',
      label: '用户名',
      align: 'center'
    },
    {
      prop: 'destinationNumber',
      label: '电话号码',
      align: 'center'
    },
    {
      prop: 'callState',
      label: '电话拨打状态',
      align: 'center',
      width: 120,
      showOverflowTooltip: false,
      currentRender: ({ row, index }) => {
        if (row.callState !== null) {
          return (<PointTag dictType={'call_status'} value={row.callState} />)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'createdTime',
      // prop: 'workOrderTime',
      label: '拨打时间',
      align: 'center',
      width: 200
    }, {
      prop: 'oper',
      label: '操作',
      align: 'center',
      fixed: 'right',
      width: 200,
      showOverflowTooltip: false,
      currentRender: ({ row, index }) => {
        // console.log(row);
        let btn = []
        btn.push({ label: '播放语音',  func: () => handleVoice(row), type: 'primary' })
        btn.push({ label: '通话记录', prem: auths.record, func: () => handleInfo(row), type: 'primary' })
        return (
          <div style={{ width: '100%' }}>
            {
              btn.map(item => (
                  item.prem?
                  <el-button
                    type={item.type}
                    v-perm={item.prem}
                    onClick={() => item.func()}
                    link>
                    {item.label}
                  </el-button>
                  : <el-button
                    type={item.type}
                    onClick={() => item.func()}
                    link>
                  {item.label}
                </el-button>
              ))
            }
          </div >
        )
      }
    }
  ],
  // api: '/order/list',
  params: {
  }
})
const getOrder=()=>{
  // isLoading.value=true
  orderGetList({
    pageNum: 1,
    pageSize: 10
  }).then(res=>{
    currentHistoryData.value=res.data.rows
    currentHistoryTotal.value=res.data.total
    // isLoading.value=false
  })
}
getOrder()
const handleVoice = (row) => {
  if (row.recordUrl !== null) {
    voiceRef.value.open(true)
    rowUrl.value = row.recordUrl
  }else{
    ElMessage({
      message: '暂无语音',
      type: 'warning',
    })
  }

}
const handleInfo = (row) => {
  historyData.value=row
  orderNumber.value = row.orderNumber
  infoLiveCallRef.value.open()
}
// window.setInterval(() => {
//   setTimeout(tableIns.value.refresh(), 0)
// }, 2000)

const handleLogout = () => {
  authStore.userLogout()
  permisstionStore.removeMenu()
  router.push('/login')
}
const initWebSocket = () => {
  try {
    // const wsUrl=setWsUrl(`/ws/text/${token}`)
    // const wsUrl = `ws://frp.feashow.cn:31800/ws/history/${token}`
    const wsUrl = `ws://192.168.1.71:88/ws/history/${token}`
    socket = new WebSocket(wsUrl)
    // 2. ws.send()给服务器发送信息
    //连接发生错误的回调方法
    socket.onerror = function () {
      console.log("ws连接发生错误");
    };
    //连接成功建立的回调方法
    socket.onopen = function () {
      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);
        let historyDataObj=JSON.parse(data)
        console.log("historyDataObj: ", historyDataObj);
        currentHistoryData.value=historyDataObj.rows
        currentHistoryTotal.value=historyDataObj.total
        // historyDataObj.rows?.forEach(item=>{
        //   currentHistoryData.value.push(item)
        // })
      }
    }
    //连接关闭的回调方法
    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>
:deep(.el-table--fit){
  min-height: 180px;
}
.home {
  .real-time-call {
    width: 100%;
    height: 50vh;
    // background-color: red;
  }

  .call-history {
    width: 100%;
    //height: 50vh;
    // background-color: blue;
  }
}
</style>
