<template>
  <div class="app-container">
    <div ref="seatMonitor" class="seat_monitor app-container">
      <el-row :gutter="10">
        <el-col :span="18" class="real_time_statistics">
          <el-card shadow="hover" style="height: 196px;">
            <h3 class="seat_monitor_title">实时统计</h3>
            <div>
              <el-row :gutter="10">
                <el-col :span="4" class="seat_sts_col">
                  <div class="seat_sts_items">
                    <el-text class="total_count_color" size="large"  type="primary">{{count.totalCount}}</el-text>
                    <p class="seat_state_sts">全部坐席</p>
                  </div>
                </el-col>
                <el-col :span="3" class="seat_sts_col">
                  <div class="seat_sts_items">
                    <el-text class="online_count_color" size="large" type="primary">{{count.onlineCount}}</el-text>
                    <p class="seat_state_sts">在线</p>
                  </div>
                </el-col>
                <el-col :span="3" class="seat_sts_col">
                  <div class="seat_sts_items">
                    <el-text class="outline_count_color"  size="large" type="primary">{{count.offlineCount}}</el-text>
                    <p class="seat_state_sts">离线</p>
                  </div>
                </el-col>
                <el-col :span="4" class="seat_sts_col">
                  <div class="seat_sts_items">
                    <el-text class="free_count_color" size="large" type="primary">{{count.freeCount}}</el-text>
                    <p class="seat_state_sts">空闲</p>
                  </div>
                </el-col>
                <el-col :span="4" class="seat_sts_col">
                  <div class="seat_sts_items">
                    <el-text class="calling_count_color" size="large" type="primary">{{count.callingCount}}</el-text>
                    <p class="seat_state_sts">通话中</p>
                  </div>
                </el-col>
                <el-col :span="3" class="seat_sts_col">
                  <div class="seat_sts_items">
                    <el-text class="callbusy_count_color" size="large" type="primary">{{count.busyCount}}</el-text>
                    <p class="seat_state_sts">忙碌</p>
                  </div>
                </el-col>
                <el-col :span="3" class="seat_sts_col">
                  <div class="seat_sts_items">
                    <el-text class="callafter_count_color" size="large" type="primary">{{count.afterCallCount}}</el-text>
                    <p class="seat_state_sts">话后处理</p>
                  </div>
                </el-col>
              </el-row>
              
            </div>
          </el-card>
        </el-col>
        <el-col :span="6" class="state_description">
          <el-card shadow="hover" class="clearfix">
            <template #header>
              <div class="card-header">
                <span>状态说明</span>
              </div>
            </template>
            <div class="clearfix">
              <el-row>
                <!-- <el-col :span="8" class="state_col">
                  <i class="state_icon state_icon_color1" />已签入
                </el-col> -->
                <el-col :span="8" class="state_col">
                  <i class="state_icon state_icon_color2" />离线
                </el-col>
                <el-col :span="8" class="state_col">
                  <i class="state_icon state_icon_color3" />未知
                </el-col>
                <el-col :span="8" class="state_col">
                  <i class="state_icon state_icon_color4" />空闲
                </el-col>
                <el-col :span="8" class="state_col">
                  <i class="state_icon state_icon_color5" />小休
                </el-col>
                <el-col :span="8" class="state_col">
                  <i class="state_icon state_icon_color6" />通话中
                </el-col>
                <el-col :span="8" class="state_col">
                  <i class="state_icon state_icon_color7" />被请求
                </el-col>
                <el-col :span="8" class="state_col">
                  <i class="state_icon state_icon_color8" />话后处理
                </el-col>
              </el-row>
              
            </div>
          </el-card>
        </el-col>
        <!-- 全部坐席 列表展示 -->
        <el-col :lg="24">
          <el-card shadow="hover" class="tab_card">
            <el-button v-show="!isStartMonitor" type="primary" plain class="monitor_btn" @click="startMonitor">开始监控
            </el-button>
            <el-button v-show="isStartMonitor" type="primary" plain class="monitor_btn" @click="cancelMonitor">取消监控
            </el-button>
            <el-tabs v-model="activeName">
              <el-tab-pane label="全部坐席" name="first">
                <div class="tab_body seat_card">
                  <el-row :gutter="10" class="clearfix">
                    <el-col v-for="(item, index) in seatCardLists" :span="4" :key="index" class="seat_cards">
                      <div class="seat_col" @click="oparateBtnShow(item)">
                        <el-row>
                          <el-col :span="12" class="text_center">
                            <el-icon class="seat_avatar"><User /></el-icon>
                            <p :class="seatStateClassFilter(item.ext_state)" class="seat_state">{{item.ext_state}}</p>
                          </el-col>
                          <el-col :span="12" class="seat_detail_right">
                            <h5>{{ item.nickName }}</h5>
                            <p>工号：{{ item.usercode }}</p>
                            <p>分机号：{{ item.extension }}</p>
                          </el-col>
                        </el-row>
                      </div>
                      <ul class="oparate_btn_lists"
                       v-show="item.visible &&
                      (item.ext_state === '小休' ||
                      item.ext_state === '通话中' ||
                      item.ext_state === '振铃' ||
                      item.ext_state === '空闲')">
                        <li class="oparate_btn" v-show="item.ext_state === '小休'" @click="oparateSeats(item,'ForceWorkOn')">
                          <svg-icon class="oparate_icon" icon-class="icon-test" />置闲
                        </li>
                        <li class="oparate_btn" v-show="item.ext_state === '空闲'" @click="oparateSeats(item,'ForceWorkOff')">
                          <svg-icon class="oparate_icon" icon-class="manglu01" />置忙
                        </li>
                        <li class="oparate_btn" v-show="item.ext_state === '通话中'&& (scoketState==='空闲'|| scoketState==='小休')" @click="oparateSeats(item,'Listen')">
                          <svg-icon class="oparate_icon" icon-class="erji" />监听
                        </li>
                        <li class="oparate_btn" v-show="item.ext_state === '振铃' && (scoketState==='空闲'|| scoketState==='小休')"  @click="oparateSeats(item,'Instead')">
                          <svg-icon class="oparate_icon" icon-class="zhuanjie" />代接
                        </li>
                        <li class="oparate_btn oparate_divider" v-show="item.ext_state === '通话中' && (scoketState==='空闲'|| scoketState==='小休')" @click="oparateSeats(item,'Insert')">
                          <svg-icon class="oparate_icon" icon-class="qiangzhixiaxian" />强插
                        </li>
                        <li class="oparate_btn" v-show="item.ext_state === '通话中' && (scoketState==='空闲'|| scoketState==='小休')" @click="oparateSeats(item,'Intercept')">
                          <svg-icon class="oparate_icon" icon-class="saoraolanjie" />拦截
                        </li>
                        <li class="oparate_btn" v-show="item.ext_state === '通话中' && (scoketState==='空闲'|| scoketState==='小休')" @click="oparateSeats(item,'Break')">
                          <svg-icon class="oparate_icon" icon-class="chexiaochaifen" />强拆
                        </li>
                      </ul>
                    </el-col>
                  </el-row>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
  import { onMounted, ref } from 'vue';
  import { getPageListData } from '@/api/main/system/system';
  import { Send, ws } from '@/utils/telWebsocket'
  import useSocketStore from '@/store/modules/socket'

  const count = ref({
    totalCount: 0, // 全部坐席数量
    onlineCount: 0, // 在线数量
    offlineCount: 0, // 离线数量
    freeCount: 0, // 空闲数量
    callingCount: 0, // 通话中数量
    busyCount: 0, // 忙碌数量
    afterCallCount: 0 // 话后处理数量
  })
  const { proxy } = getCurrentInstance();

  const isStartMonitor = ref(false)
  const activeName = ref('first')
  const seatCardLists =ref([])
  const onlineSeatData = ref([])
  const scoketDatas = ref({})
  const scoketState = ref('签出')
  const lineState = computed(() => {
    return useSocketStore().lineState
  })
  // 0离线，1登录中，2空闲，3通话中，4话后处理中，5忙碌，6振铃，7注销
  const stateObj = {
    0:'离线',
    1:'登录中',
    2:'空闲',
    3:'通话中',
    4:'话后处理中',
    5:'小休',
    6:'振铃',
    7:'注销',
  }
  watch(lineState, (newValue, oldValue) => {
    console.log(newValue);
    scoketState.value = newValue
  })
  onMounted( () => {
    scoketState.value = useSocketStore().lineState
    ws.addEventListener('message', function (evt) {
      const telWSData = JSON.parse(evt.data)
      if (telWSData) {
        switch (telWSData.Type.toLowerCase()) {
          case 'agentstate': // 来电 Incoming
            monitorBack(telWSData)
            break
        }
      }
    })
    getSeatList()
  })
  
  function oparateSeats(item,Type,targetAgentState) {
    // {"Type":"Break","AgentId":"8001","AgentExten":"1001","TargetAgentId":"8000"}
    const socketObj ={
      AgentId: useSocketStore().accountNumber,
      AgentExten: useSocketStore().extensionNumber,
      TargetAgentId:item.usercode,
      Type,
    }
    if (Type === 'ForceAgentState') {
      socketObj.TargetAgentState = targetAgentState
    }

    Send(socketObj)
    item.visible = !item.visible
    // {"Type":"Break","AgentId":"8001","AgentExten":"1001","TargetAgentId":"8000"}
  }
  function monitorBack(data) {
    console.log(data);
    
    const newArray = []
    initCalCount()
    seatCardLists.value.forEach(ele => {
      if (data.AgentId) {
        if (ele.usercode === data.AgentId) {
          ele.ext_state =stateObj[data.State]
        }
        calculatCount(ele.ext_state)
        newArray.push(ele)
        seatCardLists.value = newArray
      }
      console.log(onlineSeatData.value)
      count.value.offlineCount = count.value.totalCount - count.value.onlineCount
      
    });
    console.log(newArray);
  }
  function getSeatList() {
    getPageListData('/UserExtension/userextension').then((res)=>{
      seatCardLists.value = []
      if (res.data.length>0) {
        count.value.totalCount = res.data.length
        res.data.forEach((ele)=>{
          seatCardLists.value.push({
            ext_state: '未知', // 线路状态
            username: ele.username,
            usercode: ele.usercode,
            extension: ele.extension, // 分机号
            isListen: false, // 是否监听
            isCalling: false, // 是否通话中
            isCallout: null, // 是否是呼出(初始是这类 !isCallout 为false 的值)
            call_type: null, // 通话类型
            call_num: null, // 通话号码
            visible: false // 是否可以操作
          })
        })
      }
    })
  }
  function oparateBtnShow(item) {
    item.visible = !item.visible
    seatCardLists.value.forEach((v, i) => {
      if (item.usercode !== v.usercode) {
        v.visible = false
      }
    })
  }
  function startMonitor() {
    console.log(scoketState.value)
    if (scoketState.value !=='签出') {
      isStartMonitor.value = true
      
      console.log(useSocketStore().accountNumber);
      console.log(useSocketStore().extensionNumber);
      scoketDatas.value = {
        AgentId: useSocketStore().accountNumber,
        AgentExten: useSocketStore().extensionNumber,
        Type: 'SubScribeOn',
      }
      Send(scoketDatas.value)
    }else{
      proxy.$modal.msgSuccess('当前状态不能监控');
    }
    
  }
  // 取消监控
  function cancelMonitor() {
      isStartMonitor.value = false // 是否开始监控
      
      scoketDatas.values = {
        AgentId: useSocketStore().accountNumber,
        AgentExten: useSocketStore().extensionNumber,
        Type: 'SubScribeOff',
      }
      Send(scoketDatas.values)
      initCalCount() // 初始化 实时状态数量
      getSeatList()
  }
  // 计算 实时状态的数量
  function calculatCount(stateCode) {
    switch (stateCode) {
      case '离线':
        count.value.offlineCount++ // 离线数量
        break
      case '空闲':
        count.value.freeCount++ // 空闲数量
        break
      case '通话中':
        count.value.callingCount++ // 通话中数量
        break
      case '话后处理':
        count.value.afterCallCount++ // 话后处理
        break
      case '小休': // 小休
        count.value.busyCount++
        break
      default:
        break
    }
    count.value.onlineCount =
        count.value.freeCount +
        count.value.callingCount +
        count.value.afterCallCount +
        count.value.busyCount // 在线数量
  }
  function initCalCount() {
    // onlineSeatData.value = []
    count.value.offlineCount = 0 // 离线数量
    count.value.freeCount = 0 // 空闲数量
    count.value.callingCount = 0 // 通话中数量
    count.value.afterCallCount = 0 // 话后处理
    count.value.busyCount = 0
    count.value.onlineCount = 0
  }
  function seatStateClassFilter(status) {
    const statusMap = {
      未知: 'seat_state_color0',
      已签入: 'seat_state_color1',
      空闲: 'seat_state_color2',
      通话中: 'seat_state_color3',
      话后处理: 'seat_state_color4',
      小休: 'seat_state_color5',
      被请求: 'seat_state_color6',
      离线: 'seat_state_color7'
    }
    return statusMap[status]
    
  }
</script>

<style lang="scss" scoped>
.seat_monitor {
    .el-col {
      margin-bottom: 20px;
    }

    .state_description {
      .el-card__header {
        background-color: #f5f5f6;
        height: 40px;
        line-height: 40px;
        padding: 0 15px;
        margin: 0;
        font-size: 14px;
        color: #666666;
      }
    }

    .tab_card {
      .el-card__body {
        padding: 0;

        .el-tabs__content {
          overflow: inherit;
        }
      }

      .el-tabs__header {
        padding: 0px 20px;
        background-color: #f5f5f6;

        .el-tabs__item {
          font-size: 14px;
          height: 40px;
          line-height: 40px;
        }
      }
    }
  }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  :deep( .el-text--large){
    font-size: 22px;
  }
  .seat_monitor {
    .real_time_statistics {
      .seat_monitor_title {
        font-size: 14px;
        color: #333;
        margin-top: 0;
        margin-bottom: 16px;
        font-weight: normal;
        padding-left: 7.5px;
      }

      .seat_sts_col {
        height: 100px;
        text-align: center;

        .seat_sts_items {
          background-color: #f5f5f6;
          padding-top: 15px;
          width: 100%;
          height: 100%;
        }

        .seat_total_count {
          font-size: 24px;
          padding-top: 18px;
          line-height: 34px;
          margin: 0;
          display: inline-block;
        }

        .seat_state_sts {
          padding-top: 12px;
          font-size: 1rem;
          margin: 0;
          color: #333333;
        }
      }
    }

    .state_description {
      .state_col {
        font-size: 1rem;
        color: #333744;
        margin-bottom: 21px;

        .state_icon {
          display: inline-block;
          width: 16px;
          height: 16px;
          margin-right: 12px;
          vertical-align: text-bottom;
        }
      }
    }

    .tab_card {
      position: relative;
      overflow: inherit;

      .monitor_btn {
        position: absolute;
        right: 30px;
        top: 4px;
        z-index: 2;
      }
    }

    .seat_card {
      padding: 10px 20px 0 20px;

      .seat_cards {
        position: relative;
      }

      .seat_card_item {
        color: #bebebe;
      }

      .seat_col {
        width: 100%;
        border: 1px solid #e1e6eb;
        border-radius: 2px;
        font-size: 1rem;
        overflow: hidden;
        cursor: pointer;
        transition: all 0.38s ease-out;

        &:hover {
          border-color: #409eff;
        }

        .seat_avatar {
          font-size: 75px;
          display: block; 
          width: 80px;
          height: 80px;
          border-radius: 50%;
          margin: 15px auto 0 auto;
          /* display: block;
          width: 80px;
          height: 80px;
          border-radius: 50%;
          margin: 15px auto 0 auto; */
        }

        .seat_state {
          margin: 10px 0 0 0;
          padding: 0;
          text-align: center;
        }

        .seat_detail_right {
          position: relative;
        }

        .call_direction {
          display: inline-block;
          width: 22px;
          height: 22px;
          line-height: 22px;
          border-radius: 50%;
          text-align: center;
          color: #ffffff;
          vertical-align: baseline;
          margin-right: 5px;
        }

        .call_out {
          background-color: #409eff;
        }

        .call_in {
          background-color: #44af3d;
        }

        .call_num {
          font-size: 14px;
        }

        .seat_listen {
          position: absolute;
          right: 15px;
          top: 10px;
          color: #00c1de;
          font-size: 20px;
        }
      }

      .oparate_btn_lists {
        z-index: 1600;
        left: 80%;
        top: 40px;
        margin: 0;
        padding: 0;
        width: 100px;
        background: #fff;
        border: 1px solid #eee;
        position: absolute;
        list-style-type: none;
        border-radius: 4px;
        font-size: 12px;
        color: #676a6c;
        font-weight: 400;
        box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);

        .oparate_btn {
          margin: 0;
          padding: 0 15px;
          line-height: 36px;
          cursor: pointer;

          &:hover {
            background: #eee;
          }

          .oparate_icon {
            margin-right: 8px;
          }
        }

        .oparate_divider {
          border-bottom: 1px solid #e9e9e9;
        }
      }
    }

    .tab_table {
      padding: 0 20px 15px 20px;
    }

    .total_count_color {
      color: #30a8d8;
    }

    .online_count_color {
      color: #009900;
    }

    .outline_count_color {
      color: #666666;
    }

    .free_count_color {
      color: #1296db;
    }

    .calling_count_color {
      color: #d81e06;
    }

    .callafter_count_color {
      color: #f4bd2a;
    }

    .callbusy_count_color {
      color: #1297da;
    }

    .state_icon_color1 {
      background-color: #3acaa6;
    }

    .state_icon_color2 {
      background-color: #707070;
    }

    .state_icon_color3 {
      background-color: #bebebe;
    }

    .state_icon_color4 {
      background-color: #44af3d;
    }

    .state_icon_color5 {
      background-color: #1297da;
    }

    .state_icon_color6 {
      background-color: #d81e06;
    }

    .state_icon_color7 {
      background-color: #fd7c78;
    }

    .state_icon_color8 {
      background-color: #f8c11b;
    }

    .seat_state_color0 {
      color: #bebebe;
    }

    .seat_state_color1 {
      color: #3acaa6;
    }

    .seat_state_color2 {
      color: #44af3d;
    }

    .seat_state_color3 {
      color: #d81e06;
    }

    .seat_state_color4 {
      color: #f8c11b;
    }

    .seat_state_color5 {
      color: #1297da;
    }

    .seat_state_color6 {
      color: #fd7c78;
    }

    .seat_state_color7 {
      color: #707070;
    }
  }
</style>