<template>
  <el-card class="drawerPhoneInter">
    <div class="phoneList">
      <div class="tabBox">
        <el-radio-group v-model="radio2" @change="aaaa">
          <el-radio-button label="通话记录" />
          <el-radio-button label="通讯录" />
        </el-radio-group>
      </div>

      <div class="contentBox" ref="scrollDivUser" v-if="radio2==='通讯录'" @scroll="handleScrollUser">
        <el-input
          v-if="radio2==='通讯录'"
          v-model="addressBookSearch"
          @change="changeBookSearch"
          style="width: 240px;margin: 8px 0px 0px 8px;"
          placeholder="请输入姓名"
          :suffix-icon="Search"
        />
        <div class="contentList" v-for="item in addressBookData">
          
          <div class="leftBox">
            <div class="telPhoneBox">
              <span>{{item.dept.deptName}} -- </span>
              <span>{{item.nickName}}</span>
              <!-- <span>({{item.nickName}})</span> -->
              <!-- {{
                item.callType
                  ? getUnprefixNuber(item.callee)
                  : getUnprefixNuber(item.caller)
              }} -->
            </div>
            <div class="remarkBox">
              <span style="margin-right: 15px">{{ item.phonenumber }}</span>
              <!-- <span>{{ getCallSate(item.callType, item.endTime) }}</span> -->
            </div>
          </div>
          <div class="rightBox">
            <el-icon
              color="#409EFC"
              class="no-inherit"
              @click="phoneIconHandle(item)"
            >
              <Phone />
            </el-icon>
          </div>
        </div>
      </div>
      
      <div class="contentBox" ref="scrollDivCall" v-if="radio2==='通话记录'" @scroll="handleScrollCall">
        <div class="contentList" v-for="item in tableData" v-if="radio2==='通话记录'">
          <div class="leftBox">
            <div class="telPhoneBox">
              {{
                item.callType
                  ? getUnprefixNuber(item.callee)
                  : getUnprefixNuber(item.caller)
              }}
            </div>
            <div class="remarkBox">
              <span style="margin-right: 15px">{{ item.createTime }}</span>
              <span>{{ getCallSate(item.callType, item.endTime) }}</span>
            </div>
          </div>
          <div class="rightBox">
            <el-icon
              color="#409EFC"
              class="no-inherit"
              @click="phoneIconHandle(item)"
            >
              <Phone />
            </el-icon>
          </div>
        </div>
        <div class="contentList" v-for="item in addressBookData" v-if="radio2==='通讯录'">
          
          <div class="leftBox">
            <div class="telPhoneBox">
              <span>{{item.dept.deptName}} -- </span>
              <span>{{item.nickName}}</span>
            </div>
            <div class="remarkBox">
              <span style="margin-right: 15px">{{ item.phonenumber }}</span>
            </div>
          </div>
          <div class="rightBox">
            <el-icon
              color="#409EFC"
              class="no-inherit"
              @click="phoneIconHandle(item)"
            >
              <Phone />
            </el-icon>
          </div>
        </div>
      </div>

    </div>

    <div v-show="callOrListState">

      <div class="plate" v-show="getCallState === '2'">
        <el-input
          ref="inputFocus"
          v-model="telNumber"
          placeholder="请输入号码3"
          class="tel_input"
          autofocus
          maxlength="12"
        />
        <el-row v-for="(item, index) in dialNums" :gutter="20" :key="index">
          <el-col v-for="(tnum, index) in item" :span="8" :key="index">
            <el-button
              class="btn_nums"
              type="info"
              circle
              @click="dialNumHandler(tnum)"
              >{{ tnum }}</el-button
            >
          </el-col>
        </el-row>
      </div>

      <div class="inComing" v-show="getCallState === '1'">
        <div class="numberText">{{ getCallData.Number }}</div>
        <div class="clientText">未知</div>
        <div v-show="callType==='VIOCE'&& sipInCall" class="audioEle">
          <audio ref="audioElement" controls="controls" autoplay="autoplay"></audio>
        </div>
        <div v-show="callType==='VIDEO'&& sipInCall" class="videoEle">
          <video ref="videoElement" class="videoYou" autoplay="autoplay"></video>
          <video ref="videoElement2" class="videoMy" autoplay="autoplay"></video>
        </div>

        <div class="phoneOperation">
          <el-row>
            <el-col :span="8" class="elCol">
              <el-button
                size="large"
                type="primary"
                :icon="Switch"
                circle
                :disabled="btnState"
                class="buttonStyle"
                @click="transferCall"
              ></el-button>
              <div>转移</div>
            </el-col>
            <el-col :span="8" class="elCol">
              <el-button
                size="large"
                type="primary"
                :icon="UserFilled"
                circle
                :disabled="btnState"
                class="buttonStyle"
                @click="meetingCall"
              ></el-button>
              <div>会议</div>
            </el-col>
            <el-col :span="8" class="elCol">
              <div v-show="scoketState !== '通话保持中'">
                <el-button
                  size="large"
                  type="primary"
                  :icon="VideoPause"
                  circle
                  :disabled="btnState"
                  class="buttonStyle"
                  @click="holdBack"
                />
                <div>保持</div>
              </div>
              <div v-show="scoketState === '通话保持中'">
                <el-button
                  size="large"
                  type="primary"
                  :icon="VideoPlay"
                  circle
                  :disabled="btnState"
                  class="buttonStyle"
                  @click="retrieveBack"
                />
                <div>取消保持</div>
              </div>
            </el-col>
            <!-- <el-col :span="8" class="elCol">
              <el-button
                size="large"
                type="primary"
                :icon="Finished"
                circle
                :disabled="btnState"
                class="buttonStyle"
                @click="btn_IVR"
              ></el-button>
              <div>满意度</div>
            </el-col> -->
          </el-row>
        </div>
      </div>

      <div class="btnBox">
        <el-button
          size="large"
          type="danger"
          :icon="Phone"
          circle
          v-if="getCallState === '1'"
          :disabled="dropCallState"
          class="btnHangUp"
          @click="dropCall"
        />
        <el-button
          size="large"
          type="success"
          :icon="Phone"
          circle
          v-if="getCallState === '2'"
          class="btnCall"
          @click="btnCallType"
        />
        <el-button
          size="large"
          :icon="Edit"
          circle
          type="primary"
          class="btnCut"
          @click="btnTellState"
        />
        <el-button
          size="large"
          :icon="ArrowDownBold"
          circle
          type="primary"
          class="btnPage"
          @click="btnCutPage"
        />
      </div>
      
    </div>

    <div v-if="sipPhoneFlag" class="sipPhonePop">
        <div class="videoBtn" v-if="videoBtnFlag">
          <div style="display: flex;">
            <div class="videoAnswer">
              <el-image @click="answerCallSip" style="width: 50px; height: 50px" :src="videoInCall" fit="fill" />
            </div>
            <div class="videoDrop">
              <el-image @click="dropCallSip" style="width: 50px; height: 50px" :src="videoOutCall" fit="fill" />
            </div>
          </div>
          <div class="videoText">
            您有电话进入请注意接听
          </div>
        </div>
    </div>

    <el-button
      v-if="!callOrListState"
      size="large"
      :icon="Fold"
      circle
      type="primary"
      class="btnPage"
      @click="btnCutPage"
    />
  </el-card>
</template>
<script setup>
  import videoInCall from '@/assets/images/videoInCall.png'
  import videoOutCall from '@/assets/images/videoOutCall.png'
import {
  Switch,
  UserFilled,
  VideoPause,
  VideoPlay,
  Finished,
  Phone,
  ArrowDownBold,
  Fold,
  Edit
} from '@element-plus/icons-vue'
import { getPageListData } from '@/api/main/system/system'
import { getCallSate, getUnprefixNuber } from '@/utils'
import { getPhoneFix } from '@/api/main/main'

import { Send, ws } from '@/utils/telWebsocket'
import useSocketStore from '@/store/modules/socket'
import useSelectStore from '@/store/commonSelect/common';
import { Search } from '@element-plus/icons-vue'
import { onMounted, ref, watch, nextTick } from 'vue';
import { answerSip,hangUp,sipCall } from '@/utils/jsSip'

const { proxy } = getCurrentInstance()
const scrollDivUser = ref(null)
const scrollDivCall = ref(null)

const sipPhoneFlag = ref(false)
const videoBtnFlag = ref(false)
const audioElement = ref(null)
const videoElement = ref(null)
const videoElement2 = ref(null)

const radio2 = ref('通话记录')
const scoketDatas = ref({})
const scoketState = ref('签出')
const dropCallState = ref(true)
const callDirection = ref(1)
const btnState = ref(true)
const callOrListState = ref(true)
const telNumber = ref('')
const getCallState = ref('')
const getCallData = ref({})

const pageSize4 = ref(15)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const tableData = ref([])
const tableRecordCount = ref(0)
const addressBookSearch = ref('')
const addressBookCount = ref(0)
const addressBookData = ref([]) 
const tableCount = ref(0)
const paramsSearch = ref({})
const phoneType = import.meta.env.VITE_APP_PHONE_TYPE
const callType = ref(import.meta.env.VITE_APP_CALL_TYPE)
const sipInCall = ref(false)

const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  paramsSearch.value.pageNum = val
  if (radio2.value === '通话记录') {
    getCustomeData()
  }else if(radio2.value === '通讯录'){
    getUserData()
  }
  
}

const dialNums = ref([
  ['1', '2', '3'],
  ['4', '5', '6'],
  ['7', '8', '9'],
  ['*', '0', '#']
])

const props = defineProps({
  callState: {
    type: String,
    default: ''
  },
  callData: {
    type: Object,
    default: () => ({})
  }
})

function aaaa(e) {
  // if (e == '通话记录') {
  //   paramsSearch.value.pageNum = 1
  //   getUserData()
  // } else if(e == '通讯录'){
  //   paramsSearch.value.pageNum = 1
        // getCustomeData()
  // }
}
watch(
  () => props.callData,
  (newValue) => {
    console.log(newValue.IncomintType)
    if (newValue.IncomintType !== 2) {
      getCallData.value = newValue
    }
  }
)
function dialNumHandler(tnum) {
  if (telNumber.value.length === 12) {
    return
  }
  telNumber.value += tnum
}
function inCommingSip(res,direction) {
  mediaStream()
  if (direction === 1) {
    sipPhoneFlag.value = true
    videoBtnFlag.value = true
  }
  
  
  res.session.on("confirmed", function(data) {
    if(res.session.connection.getReceivers) {
      let remoteStream = new MediaStream();
			res.session.connection.getReceivers().forEach(element => {
				// track可能一个音轨或者视频轨迹
        console.log(element)
				remoteStream.addTrack(element.track)
			})
      if (callType.value === 'VIOCE') {
        audioElement.value.srcObject = remoteStream
        audioElement.value.onloadedmetadata = function() {
          audioElement.value.play();
          audioElement.value.muted = false;
          sipPhoneFlag.value = false
          console.log('接听成功，通话中')
        }
      } else if(callType.value === 'VIDEO'){
        videoElement.value.srcObject = remoteStream
        videoElement.value.onloadedmetadata = function() {
          videoElement.value.play();
          videoElement.value.muted = false;
          sipPhoneFlag.value = false
          console.log('接听成功，通话中')
        }
      }
      
    }
  })

}
function mediaStream() {
  navigator.getUserMedia({
		video: true,
		audio: false
	}, function(stream) {
		videoElement2.value.srcObject = stream
    videoElement2.value.onloadedmetadata = function() {
      videoElement2.value.play();
      console.log('本地摄像头打开')
    }
	}, function(e) {
		if(e.name != "NotReadableError") {
			console.log('getUserMedia() error: ' + e.name);
		}
	});
}
function inComingHandle (){
  if (phoneType === 'SIP') {
    sipInCall.value = true
  }
  getCallState.value = '1'
  if (callDirection.value === 1) {
    btnState.value = false
  }
  dropCallState.value = false
}
function answerCallSip(data) {
  console.log('接听');
  answerSip(callType.value)
  inComingHandle()
}
function dropCallSip() {
  console.log('挂断');
  hangUp()
}
window.addEventListener("sipInComming", (e) => {
  console.log(e.detail);
  inCommingSip(e.detail,1)
});
window.addEventListener("sipCallOut", (e) => {
  console.log(e.detail);
  inCommingSip(e.detail,2)
});

ws.addEventListener('message', function (evt) {
  const telWSData = JSON.parse(evt.data)
  if (telWSData) {
    switch (telWSData.Type.toLowerCase()) {
      case 'linestate': // 来电 Incoming
        linestateBack(telWSData.Result)
        break
      case 'state': // 来电 Incoming
      stateBack(telWSData.State)
        break
      case 'incoming': // 来电
        incomingBack(telWSData)
        break
      case 'asr': // 来电
        // incomingBack(telWSData)
        asrMessageEvent(telWSData)
        break
    }
  }
})

const asrMessageEvent = (msg) => {
  console.log('asrMessageEvent', msg)
  const event = new CustomEvent("AsrMessageEvent", { detail: msg });
  window.dispatchEvent(event);
}

// 0离线，1登录中，2空闲，3通话中，4话后处理中，5忙碌，6振铃，7注销
const stateObj = {
  0:'离线',
  1:'登录中',
  2:'空闲',
  3:'通话中',
  4:'话后处理中',
  5:'忙碌',
  6:'振铃',
  7:'注销',
}
function stateBack(Result) {
  scoketState.value = stateObj[Result]
  if (scoketState.value === '通话中') {
    inComingHandle ()
  } else {
    getCallState.value = '2'
    btnState.value = true
    dropCallState.value = true
  }
  useSocketStore().setLineState(stateObj[Result])
}
function linestateBack(Result) {
  scoketState.value = Result
  if (scoketState.value === '通话中') {
    inComingHandle ()
  } else {
    getCallState.value = '2'
    btnState.value = true
    dropCallState.value = true
  }
  useSocketStore().setLineState(Result)
}
function incomingBack(data) {
  useSocketStore().setIncomingData(data)
}
function btnTellState() {
  if (getCallState.value === '1') {
    getCallState.value = '2'
  } else if (getCallState.value === '2') {
    getCallState.value = '1'
  }
}
function btnCutPage() {
  callOrListState.value = !callOrListState.value
}
//转移
function transferCall() {
  getCallState.value = '2'
  scoketState.value = '转移'
}
//会议
function meetingCall() {
  getCallState.value = '2'
  scoketState.value = '会议'
}
function phoneIconHandle(item) {
  if (radio2.value === '通话记录') {
    telNumber.value = item.callType
    ? getUnprefixNuber(item.callee)
    : getUnprefixNuber(item.caller)
  }else if(radio2.value === '通讯录'){
    telNumber.value = item.phonenumber
  }
 
  btnCallType()
}
function btnCallType() {
  if (!telNumber.value) {
    return
  }
  getCallData.value.Number = telNumber.value
  scoketDatas.value = {
    AgentId: useSocketStore().accountNumber,
    AgentExten: useSocketStore().extensionNumber
  }
  if (scoketState.value === '转移') {
    scoketDatas.value.Type = 'Transfer'
  } else if (scoketState.value === '会议') {
    scoketDatas.value.Type = 'Meeting'
  } else {
    scoketDatas.value.Type = 'MakeCall'
    callDirection.value = 2
  }
  getPhoneFix(telNumber.value).then((data) => {
    if (data.state === 'success') {
      if (data.data[0].length>11) {
        if (data.data[0][0] === '9') {
          scoketDatas.value.DestinationNumber = data.data[0].substr(1)
        }
      }else{
        scoketDatas.value.DestinationNumber = data.data[0]
      }

      if (phoneType !== 'SIP') {
        Send(scoketDatas.value, (data) => {
          if (data.Type === 'MakeCall') {
            if (data.Result) {
              scoketState.value === '外呼成功'
              proxy.$modal.msgSuccess('外呼成功')
              getCallState.value = '1'
              delete scoketDatas.value.DestinationNumber
            } else {
              proxy.$modal.msgSuccess('外呼失败')
            }
          }
        })
      } else {
        if (data.Type === 'MakeCall') {
          sipCall(scoketDatas.value.DestinationNumber,callType.value)
        } else {
          Send(scoketDatas.value, (data) => {
            if (data.Type === 'Meeting') {
              inComingHandle ()
            }
          })
        }
        
      }
    }
  })
}
onMounted(() => {
  getCallState.value = props.callState
  paramsSearch.value.pageNum = 1
  paramsSearch.value.pageSize = pageSize4.value
  getCustomeData()
  getUserData()
 

})
const handleScrollUser = () => {
  const container = scrollDivUser.value
  if (container.scrollTop + container.clientHeight >= container.scrollHeight) {
    // loadMore()
    console.log('通讯录到底了');
    paramsSearch.value.pageNum +=1
    getUserData()
    
  }
}
const handleScrollCall = () => {
  const container = scrollDivCall.value
  if (container.scrollTop + container.clientHeight >= container.scrollHeight) {
    // loadMore()
    console.log('通话记录到底了');
    paramsSearch.value.pageNum +=1
    getCustomeData()
  }
}
function getCustomeData() {
  delete paramsSearch.value.nickName
  getPageListData('/call/calllog', paramsSearch.value).then(
    ({ data, total }) => {
      const newArray = data
      tableData.value =  tableData.value.concat(newArray)
      tableRecordCount.value = total
    }
  )
}
function changeBookSearch(val) {
  paramsSearch.value.nickName = val
  getUserData()
}

function getUserData() {
 
  getPageListData('/system/user', paramsSearch.value).then(
    ({ data, total }) => {
      const newArray = data
      addressBookData.value =  addressBookData.value.concat(newArray)
      addressBookCount.value = total
      
    }
  )
}
//ivr-满意度
function btn_IVR() {
  scoketDatas.value = {
    Type: 'TurnIvr',
    AgentId: useSocketStore().accountNumber,
    AgentExten: useSocketStore().extensionNumber
  }
  Send(scoketDatas.value, (data) => {
    console.log('ivr-满意度成功')
  })
}
//挂断
function dropCall() {
  scoketDatas.value = {
    Type: 'DropCall',
    AgentId: useSocketStore().accountNumber,
    AgentExten: useSocketStore().extensionNumber
  }
  Send(scoketDatas.value, (data) => {
    console.log('挂断成功')
  })
}

//保持
function holdBack() {
  scoketDatas.value = {
    Type: 'HoldOn',
    AgentId: useSocketStore().accountNumber,
    AgentExten: useSocketStore().extensionNumber
  }
  Send(scoketDatas.value, (data) => {
    console.log('通话保持中成功')
    scoketState.value = '通话保持中'
    useSocketStore().setLineState('通话保持中')
  })
}
//取消保持
function retrieveBack() {
  scoketDatas.value = {
    Type: 'HoldOff',
    AgentId: useSocketStore().accountNumber,
    AgentExten: useSocketStore().extensionNumber
  }
  Send(scoketDatas.value, (data) => {
    console.log('取消保持成功')
    scoketState.value = '通话中'
    useSocketStore().setLineState('通话中')
  })
}
</script>

<style lang="scss" scoped>
.tel_input {
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color))
      inset;
    cursor: default;

    .el-input__inner {
      cursor: default !important;
    }
  }
}

:deep(.el-card__body) {
  padding: 0;
}
.no-inherit {
  cursor: pointer;
}

.drawerButton {
  position: fixed;
  right: 0px;
  bottom: 300px;
  padding: 3px;
  z-index: 3;
  box-shadow: -1px -1px 1px #b6b6b6;
}

.drawerPhoneInter {
  padding: 0;
  width: 100%;
  height: 100%;
  background: #fff;
  z-index: 3;
  box-shadow: -1px -1px 1px #b6b6b6;
  position: relative;

  .phoneList {
    height: 100%;

    .tabBox {
      width: 162px;
      margin: 0 auto;
    }
    .contentBox::-webkit-scrollbar {
      display: none; /* Chrome Safari */
    }
    .contentBox {
      border-top: 1px solid #999;
      margin-top: 15px;
      height: 590px;
      overflow-y: auto;

      .contentList {
        width: 100%;
        display: flex;
        padding: 8px;
        border-bottom: 1px solid #ddd;

        .leftBox {
          text-align: left;
          width: 80%;
          line-height: 20px;

          .telPhoneBox {
            font-size: 14px;
            font-weight: bold;
          }

          .remarkBox {
            font-size: 12px;
          }
        }

        .rightBox {
          text-align: right;
          line-height: 40px;
          width: 20%;
        }
      }
    }
  }

  .buttonStyle {
    margin: 8px;
  }

  .btnCall {
    position: absolute;
    bottom: 30px;
    left: 50%;
    margin-left: -20px;
    z-index: 2;
  }

  .btnCut {
    position: absolute;
    bottom: 30px;
    left: 30px;
    z-index: 2;
  }

  .btnPage {
    position: absolute;
    bottom: 30px;
    right: 30px;
    z-index: 2;
  }
  .btnBox{
    width: 100%; 
    height: 60px; 
    background-color: #ffffff;
    position: absolute;
    bottom: 0px;
    right: 0px;
  }
  .btnHangUp {
    position: absolute;
    bottom: 30px;
    left: 50%;
    margin-left: -20px;
    z-index: 2;
  }

  .scoketStateText {
    font-weight: bold;
    color: #67c23a;
    position: absolute;
    top: 15px;
    right: 15px;
  }

  .inComing {
    position: absolute;
    bottom: 0px;
    height: 100%;
    width: 100%;
    margin-left: -20px;
    z-index: 1;
    background: #fff;

    .numberText {
      text-align: center;
      font-size: 28px;
      margin-top: 50px;
      width: 100%;
    }

    .clientText {
      text-align: center;
      margin-top: 15px;
    }

    .phoneOperation {
      width: 100%;
      text-align: center;
      position: absolute;
      bottom: 100px;

      .elCol {
        margin: 20px 0;
      }
    }
  }

  .plate {
    text-align: center;
    margin-top: 20px;
    position: absolute;
    bottom: 70px;
    background: #fff;
    width: 100%;
    margin-left: -20px;

    .bottomBtn {
      margin-top: 20px;
    }

    div.tel_input {
      font-size: 26px;
      margin-bottom: 22px;
      width: 186px;

      .el-input__inner {
        background-color: #42484d;
        color: #ffffff;
        font-size: 26px;
        // border-color: transparent;

        width: 100%;
      }
    }

    .btn_nums {
      background-color: #1f2129;
      width: 63px;
      height: 63px;
      font-size: 28px;
      border-color: transparent;
      margin-bottom: 8px;
    }

    .btn_nums:hover {
      box-shadow: 0px 0px 20px #7e7e7e;
    }

    .btn_nums:active {
      background-color: #409eff;
    }

    .btn_yonghu {
      position: absolute;
      right: 12px;
      bottom: 12px;
      color: #ffffff;
      cursor: pointer;
    }
  }

  .sipPhonePop{
    position: absolute;
    bottom: 0px;
    height: 100%;
    width: 100%;
    margin-left: -20px;
    z-index: 2;
    background: #fff;
    .videoBtn{
      position: absolute;
      top: 40%;
      width: 100%;
     
      text-align: center;
     .videoAnswer{
        width: 50%;
        
      }
      .videoDrop{
        width: 50%;
      }
      .videoText{
        text-align: center;
        width: 100%;
        font-size: 20px;
        color: #008000;
        margin-top: 30px;
        
      }
    }
    
  }
  .audioEle{
      text-align: center;
      position: relative;
      margin-top: 50px;
       video {
        position: absolute;
        background-color: #333333;
        /* border: 1px solid blue; */
        padding: 0px;
        width: 100%;
        object-fit:fill;
        left: 0px;
        right: 0px;
        top: 100px;
        bottom: 0px;
        margin: auto;
      }

    }
    .videoEle{
      position: absolute;
      width: 100%;
      height: 100%;
      top: 160px;
      height: 268px;
      .videoYou {
        position: absolute;
        background-color: #333333;
        padding: 0px;
        width: 100%;
        height: 100%;
        object-fit:fill;
        margin: auto;
      }
      .videoMy {
        position: absolute;
        bottom: 0px;
        right: 0px;
        background-color: #333333;
        padding: 0px;
        width: 20%;
        height: 20%;
        object-fit:fill;
        margin: auto;
      }
    }
}
</style>
