<template>
  <div ref="seatMonitor" class="seat_monitor app-container">
    <el-row :gutter="10">
      <el-col :lg="18" class="real_time_statistics">
        <el-card shadow="hover">
          <h3 class="seat_monitor_title">实时统计</h3>
          <div class="clearfix">
            <el-col :md="4" class="seat_sts_col">
              <div class="seat_sts_items">
                <count-to
                  :start-val="0"
                  :end-val="count.totalCount"
                  :duration="2600"
                  class="seat_total_count total_count_color"
                />
                <p class="seat_state_sts">全部坐席</p>
              </div>
            </el-col>
            <el-col :md="3" class="seat_sts_col">
              <div class="seat_sts_items">
                <count-to
                  :start-val="0"
                  :end-val="count.onlineCount"
                  :duration="2600"
                  class="seat_total_count online_count_color"
                />
                <p class="seat_state_sts">在线</p>
              </div>
            </el-col>
            <el-col :md="3" class="seat_sts_col">
              <div class="seat_sts_items">
                <count-to
                  :start-val="0"
                  :end-val="count.offlineCount"
                  :duration="2600"
                  class="seat_total_count outline_count_color"
                />
                <p class="seat_state_sts">离线</p>
              </div>
            </el-col>
            <el-col :md="4" class="seat_sts_col">
              <div class="seat_sts_items">
                <count-to
                  :start-val="0"
                  :end-val="count.freeCount"
                  :duration="2600"
                  class="seat_total_count free_count_color"
                />
                <p class="seat_state_sts">空闲</p>
              </div>
            </el-col>
            <el-col :md="4" class="seat_sts_col">
              <div class="seat_sts_items">
                <count-to
                  :start-val="0"
                  :end-val="count.callingCount"
                  :duration="2600"
                  class="seat_total_count calling_count_color"
                />
                <p class="seat_state_sts">通话中</p>
              </div>
            </el-col>
            <el-col :md="3" class="seat_sts_col">
              <div class="seat_sts_items">
                <count-to
                  :start-val="0"
                  :end-val="count.busyCount"
                  :duration="2600"
                  class="seat_total_count callbusy_count_color"
                />
                <p class="seat_state_sts">忙碌</p>
              </div>
            </el-col>
            <el-col :md="3" class="seat_sts_col">
              <div class="seat_sts_items">
                <count-to
                  :start-val="0"
                  :end-val="count.afterCallCount"
                  :duration="2600"
                  class="seat_total_count callafter_count_color"
                />
                <p class="seat_state_sts">话后处理</p>
              </div>
            </el-col>
          </div>
        </el-card>
      </el-col>
      <el-col :lg="6" class="state_description">
        <el-card shadow="hover" class="clearfix">
          <div slot="header" class="state_des_title">
            <span>状态说明</span>
          </div>
          <div class="clearfix">
            <!-- <el-col :xl="8" :lg="12" :md="8" :sm="8" :xs="12" class="state_col">
              <i class="state_icon state_icon_color1" />已签入
            </el-col>-->
            <el-col :xl="8" :lg="12" :md="8" :sm="8" :xs="12" class="state_col">
              <i class="state_icon state_icon_color2" />离线
            </el-col>
            <el-col :xl="8" :lg="12" :md="8" :sm="8" :xs="12" class="state_col">
              <i class="state_icon state_icon_color3" />未知
            </el-col>
            <el-col :xl="8" :lg="12" :md="8" :sm="8" :xs="12" class="state_col">
              <i class="state_icon state_icon_color4" />空闲
            </el-col>
            <el-col :xl="8" :lg="12" :md="8" :sm="8" :xs="12" class="state_col">
              <i class="state_icon state_icon_color5" />小休
            </el-col>
            <el-col :xl="8" :lg="12" :md="8" :sm="8" :xs="12" class="state_col">
              <i class="state_icon state_icon_color6" />通话中
            </el-col>
            <!-- <el-col :xl="8" :lg="12" :md="8" :sm="8" :xs="12" class="state_col">
              <i class="state_icon state_icon_color7" />被请求
            </el-col>-->
            <el-col :xl="8" :lg="12" :md="8" :sm="8" :xs="12" class="state_col">
              <i class="state_icon state_icon_color8" />话后处理
            </el-col>
          </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 in seatCardLists"
                    :xl="4"
                    :lg="6"
                    :md="8"
                    :sm="12"
                    :key="item.id"
                    :class="{seat_card_item: !isStartMonitor}"
                    class="seat_cards"
                  >
                    <div class="seat_col" @click="oparateBtnShow(item)">
                      <el-col :md="10" :sm="10" :xs="10" class="text_center">
                        <img :src="item.head_small_img" alt="头像" class="seat_avatar" />
                        <p
                          :class="item.ext_state | seatStateClassFilter"
                          class="seat_state"
                        >{{ item.ext_state}}</p>
                      </el-col>
                      <el-col :md="14" :sm="14" :xs="14" class="seat_detail_right">
                        <h5>{{ item.username }}</h5>
                        <p>工号：{{ item.usercode }}</p>
                        <p>分机号：{{ item.seat_ext }}</p>
                        <p v-show="item.isCalling">
                          <b
                            :class="[{call_out: item.isCallout, call_in: !item.isCallout }]"
                            class="call_direction"
                          >{{ item.call_type }}</b>
                          <span class="call_num">{{ item.call_num }}</span>
                        </p>
                        <svg-icon
                          v-show="item.isListen"
                          icon-class="weibiaoti3"
                          class="seat_listen el-icon-view"
                        />
                      </el-col>
                    </div>
                    <ul
                      v-show="item.visible && ((item.ext_state === '小休')|| (item.ext_state === '通话中') || (item.ext_state === '来电振铃'))"
                      class="oparate_btn_lists"
                    >
                      <li
                        v-show="item.ext_state === '小休'"
                        class="oparate_btn"
                        @click="oparateSeats(item, 'ForceAgentState')"
                      >
                        <svg-icon class="oparate_icon" icon-class="icon-test" />置闲
                      </li>
                      <li
                        v-show="item.ext_state === '通话中'"
                        class="oparate_btn"
                        @click="oparateSeats(item, 'Listen')"
                      >
                        <svg-icon class="oparate_icon" icon-class="erji" />监听
                      </li>
                      <li
                        v-show="item.ext_state === '来电振铃'"
                        class="oparate_btn"
                        @click="oparateSeats(item, 'Instead')"
                      >
                        <svg-icon class="oparate_icon" icon-class="zhuanjie" />代接
                      </li>
                      <li
                        v-show="item.ext_state ===  '通话中'"
                        class="oparate_btn oparate_divider"
                        @click="oparateSeats(item, 'Insert')"
                      >
                        <svg-icon class="oparate_icon" icon-class="qiangzhixiaxian" />强插
                      </li>
                      <li
                        v-show="item.ext_state ===  '通话中'"
                        class="oparate_btn"
                        @click="oparateSeats(item, 'Intercept')"
                      >
                        <svg-icon class="oparate_icon" icon-class="saoraolanjie" />拦截
                      </li>
                      <li
                        v-show="item.ext_state ===  '通话中'"
                        class="oparate_btn"
                        @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>
</template>

<script>
import CountTo from 'vue-count-to'
import { Send } from '@/utils/telWebsocket'
import { getSeatGroup } from '@/api/commonAPI'
import { getSeatLists, getSeatRealStates } from '@/api/telCall/seatMonitor'
import { mapGetters } from 'vuex'
import store from '@/store'
import { timestampToTime } from '@/utils'

export default {
  name: 'SeatMonitor',
  components: {
    CountTo
  },
  filters: {
    seatStateFilter (status) {
      const statusMap = {
        0x00: '未知',
        0x01: '已签入',
        0x02: '空闲',
        0x03: '通话中',
        0x04: '话后处理',
        0x05: '小休',
        0x06: '被请求',
        0x07: '离线'
      }
      return statusMap[status]
    },
    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]
      // console.log()
      // if (status === "空闲") {
      //   return 'seat_state_color2'
      // }
    },
    // 坐席类型
    agentTypeFilter (status) {
      const statusMap = {
        0: '班长坐席',
        1: '普通坐席'
      }
      return statusMap[status]
    }

  },
  data () {
    return {
      seatRealSateTimer: null, // 定时器
      monitorListBoole: false,
      seatGroups: [], // 坐席组数据
      seatCardLists: [], // 坐席card列表数据
      monitorList: [], // socket坐席监控数据
      monitorAgoList: [], // 坐席监控的前一条数据
      postSeatsLists: [], // 请求数据
      areaDataRemove: {},
      dataLists: [], // 表格数据
      isStartMonitor: false, // 是否开始监控
      count: {
        totalCount: 0, // 全部坐席数量
        onlineCount: 0, // 在线数量
        offlineCount: 0, // 离线数量
        freeCount: 0, // 空闲数量
        callingCount: 0, // 通话中数量
        busyCount: 0, // 忙碌数量
        afterCallCount: 0 // 话后处理数量
      },
      activeName: 'first',
      scoketDatas: {} // 发送的 websocket数据
    }
  },
  computed: {
    ...mapGetters([
      'telIsLogin', // 是否签入
      'usercode', // 坐席工号
      'extension', // 分机号
      'telLineState', // 线路状态
      'telMonitor', // 监控操作是否成功
      'monitorState', //坐席状态
      'monitorAgent' //坐席工号
    ]),
    groupFilter () {
      return function (id) {
        for (let i = 0; i < this.seatGroups.length; i++) {
          if (this.seatGroups[i].id === id) {
            return this.seatGroups[i].name
          }
        }
      }
    }
  },
  watch: {
    // 如果 `telMonitor` 发生改变，这个函数就会运行
    telMonitor: function (newT, oldT) {
      if (newT) {
        this.monitorSeatState()
      }
    }

  },
  created () {
    this.getSeatGroupList()
      .then(() => {
        this.getLists()
      })
  },
  methods: {
    // 初始化 坐席card 和 表格 列表
    getLists () {
      getSeatLists().then(response => {
        if (response.state.toLowerCase() === 'success') {
          this.seatCardLists = []
          this.postSeatsLists = []
          this.dataLists = []
          if (response.data && response.data.length > 0) {
            this.count.totalCount = response.data.length // 全部坐席数量
            // 计算 实时状态的数量

            this.calculatCount()
            response.data.forEach((v, i) => {
              // 初始化 card 数据
              this.seatCardLists.push({
                id: v.id,
                head_small_img: !v.head_small_img ? '/static/img/user.png' : v.head_small_img,
                ext_state: '未知', // 线路状态
                username: v.F_UserName,
                usercode: v.F_UserCode,
                seat_ext: '未知', // 分机号
                isListen: false, // 是否监听
                isCalling: false, // 是否通话中
                isCallout: null, // 是否是呼出(初始是这类 !isCallout 为false 的值)
                call_type: null, // 通话类型
                call_num: null, // 通话号码
                visible: false // 是否可以操作
              })
            })
          }
        }
      })
    },
    // 开始监控
    startMonitor () {

      // this.monitorList = []
      this.isStartMonitor = true // 是否开始监控
      this.scoketDatas = {
        'AgentID': this.usercode,
        'AgentExten': this.extension,
        'Type': 'Monitor'
      }
      Send(this.scoketDatas)


    },
    // 取消监控
    cancelMonitor () {
      this.isStartMonitor = false // 是否开始监控
      this.scoketDatas = {
        'AgentID': this.usercode,
        'AgentExten': this.extension,
        'Type': 'MonitorCancel'
      }
      Send(this.scoketDatas)
      this.initCalCount() // 初始化 实时状态数量
      this.getLists()

    },
    // 监测坐席状态 坐席实时状态
    monitorSeatState () {
      this.initCalCount() // 初始化 实时状态数量
      store.dispatch('ChangeMonitor', false)// 修改监听操作的返回值
      this.isStartMonitor = true // 是否开始监控      
      if (this.monitorList.length > 0) {
        this.monitorList.forEach((v, i) => {
          if (Number(v.agent_id) === Number(this.monitorAgent)) {
            v.ext_state = this.monitorState
            this.monitorListBoole = true
          }
        })
        if (!this.monitorListBoole) {
          this.monitorList.push({
            agent_id: this.monitorAgent,
            ext_state: this.monitorState
          })
        }
      } else {
        this.monitorList.push({
          agent_id: this.monitorAgent,
          ext_state: this.monitorState
        })
      }
      console.log(this.monitorAgent)
      // this.seatCardLists.forEach((m, k) => {
      //   if (Number(m.usercode) === Number(this.monitorAgent)) {
      //     // 更新 card 视图
      //     this.getCardList(m)
      //     //return
      //   }
      // })
      this.seatCardLists.forEach((m, k) => {
        if (Number(m.usercode) === Number(this.monitorAgent)) {
          // 更新 card 视图
          this.getCardList(m)

          //return
        }
        this.monitorList.forEach((v, i) => {
          if (Number(m.usercode) === Number(v.agent_id)) {
            // 计算 实时状态的数量
            this.calculatCount(m.ext_state)
            //return
          }
        })
      })

      this.count.offlineCount = this.count.totalCount - this.count.onlineCount
    },
    /**
       * 获取 card表格数据
       * @m 当前坐席数据
       * @v 获取的数据 this.getCardList(m, this.monitorAgent, this.monitorState)
       */
    getCardList (m, v) {
      if (Number(m.usercode) === Number(this.monitorAgent)) {
        m.ext_state = this.monitorState // 线路状态
        // 通话中,获取电话号码
        // m.isCalling = false
        // // console.log('被监听状态:.............' + v.mon_state);
        // // 被监听状态
        // if (v.mon_state === 1) {
        //   m.isListen = true
        // } else {
        //   m.isListen = false
        // }
      }
    },
    // 初始化 实时状态数量
    initCalCount () {
      this.count.offlineCount = 0 // 离线数量
      this.count.freeCount = 0 // 空闲数量
      this.count.callingCount = 0 // 通话中数量
      this.count.afterCallCount = 0 // 话后处理
      this.count.busyCount = 0
      this.count.onlineCount = 0
    },
    // 计算 实时状态的数量
    calculatCount (stateCode) {
      switch (stateCode) {
        case '离线':
          this.count.offlineCount++ // 离线数量
          break
        case '空闲':
          this.count.freeCount++ // 空闲数量
          break
        case '通话中':
          this.count.callingCount++ // 通话中数量
          break
        case '话后处理':
          this.count.afterCallCount++ // 话后处理
          break
        case '小休': // 小休
          this.count.busyCount++
          break
        default:
          break
      }
      this.count.onlineCount = this.count.freeCount + this.count.callingCount + this.count.afterCallCount + this.count.busyCount // 在线数量

    },

    // 获取坐席组数据
    getSeatGroupList () {
      return new Promise(resolve => {
        getSeatGroup().then(response => {
          if (response.state.toLowerCase() === 'success') {
            const res = response.data
            if (res && res.length > 0) {
              for (let i = 0; i < res.length; i++) {
                this.seatGroups.push({
                  id: res[i].id,
                  name: res[i].zxzname
                })
              }
            }
          }
        })
        resolve()
      })
    },

    // 操作坐席
    oparateBtnShow (item) {
      if (!this.isStartMonitor) {
        this.$message.warning('您还没有开始监测,请点击开始监测后再操作!')
        return
      }

      if (!this.telIsLogin) {
        this.$message.warning('您还没有签入,请签入后再操作!')
        return
      }

      if (item.usercode === this.usercode) {
        this.$message.warning('您不能在坐席监控中对自己进行操作!')
        return
      }
      if (this.telLineState === 6) {
        this.$message.warning('您当前在通话中不能对坐席进行操作!')
        return
      }
      console.log(item.ext_state)
      if ((item.ext_state === '小休') ||
        (item.ext_state === '通话中') ||
        (item.ext_state === '来电振铃')) {
        item.visible = !item.visible
        this.seatCardLists.forEach((v, i) => {
          if (item.id !== v.id) {
            v.visible = false
          }
        })
      } else {
        this.$message.warning('当前坐席无需操作!')
      }
    },

    // 置闲 监听 代接 强插 拦截 强拆
    oparateSeats (item, angenttype) {
      // if (angenttype === 'Instead') {
      //   item.usercode = '8001'
      // }

      this.scoketDatas = {
        'AgentID': this.usercode,
        'AgentExten': this.extension,
        'Type': angenttype,
        'TargetAgentID': item.usercode // 目标座席工号
      }
      Send(this.scoketDatas)
      item.visible = !item.visible
    }
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    if (this.isStartMonitor) {
      this.cancelMonitor()
    }
    next()
  }
}

</script>

<style rel="stylesheet/scss" lang="scss">
.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>
.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;
        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: 12px;
        margin: 0;
        color: #333333;
      }
    }
  }

  .state_description {
    .state_col {
      font-size: 14px;
      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: 12px;
      height: 136px;
      overflow: hidden;
      cursor: pointer;
      transition: all 0.38s ease-out;
      &:hover {
        border-color: #409eff;
      }
      .seat_avatar {
        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>
