<template>
  <div class="dialplate">
    <div class="plate">
      <!-- 拨号盘 -->
      <el-input
        v-model="telNumber"
        class="tel_input"
        autofocus
        maxlength="12"
        @keyup.native="callOutInput"
        @keyup.enter.native="callOut"
      />
      <i v-show="isShowDelNum" class="del_num" @click="delNum" />
      <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>
      <el-button v-waves class="btn_call" type="success" round @click="callOut">拨打</el-button>
      <!-- 右侧 通话记录和通讯录  -->
      <svg-icon v-popover:popover class="btn_yonghu" icon-class="yonghu" />
      <el-popover
        ref="popover"
        :value="telIsVisCallout"
        visible-arrow
        popper-class="phone_lists"
        placement="right-end"
        width="396"
        trigger="click"
        transition="fade-in-linear"
      >
        <!-- @show="getTelHisList" -->
        <el-tabs v-model="tabActiveName" stretch class="phnoe_tabs" @tab-click="handleClick">
          <el-input v-model="s_keywords" size="mini" placeholder="搜索" prefix-icon="el-icon-search" />
          <el-tab-pane label="历史记录" name="first">
            <div class="h_list_title">
              <span>最近通话</span>
              <el-tooltip effect="dark" content="点击查看是否有工单" placement="right">
                <svg-icon icon-class="eye" @click.native="showOrderIcon" />
              </el-tooltip>
            </div>
            <el-scrollbar
              v-loading="loading1"
              element-loading-background="transparent"
              style="height: 300px;"
            >
              <ul v-if="recentCalls.length" class="recent_calls_lists">
                <li v-for="item in recentCalls" :key="item.id" class="recent_calls_item clearfix">
                  <div class="recent_calls_item_left" @click="recentCallOut(item.tel)">
                    <svg-icon v-show="item.isCallOut" icon-class="huchu" />
                    <p :class="{ name_state: !item.isConect }" class="recent_calls_item_name">
                      <span>{{ item.name }}</span>
                      <span v-if="item.isConect">| {{ item.callTimes | secondToDuring }}</span>
                    </p>
                    <p class="recent_calls_item_tel">{{ item.tel | telFilter }}</p>
                  </div>
                  <div class="recent_calls_item_right">
                    <span class="recent_calls_item_time">{{ item.time | timesAgo }}</span>
                    <el-tooltip
                      v-show="isShowOrderIcon"
                      v-if="item.isOrder"
                      effect="dark"
                      content="点击查看工单"
                      placement="right"
                    >
                      <svg-icon icon-class="xiangmu1" @click.native="goOrderList(item.tel)" />
                    </el-tooltip>
                  </div>
                </li>
              </ul>
              <p v-else class="text_center">没有找到数据···</p>
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane label="通讯录" name="second">
            <el-scrollbar
              v-loading="loading2"
              element-loading-background="transparent"
              style="height: 320px;"
            >
              <ul v-if="phoneLists.length" class="recent_calls_lists">
                <li
                  v-for="(item, index) in phoneLists"
                  :key="index"
                  class="recent_calls_item clearfix"
                >
                  <div class="recent_calls_item_left" @click="recentCallOut(item.tel)">
                    <p class="recent_calls_item_name">{{ item.name }}</p>
                    <p class="recent_calls_item_tel">{{ item.tel | telFilter }}</p>
                  </div>
                </li>
              </ul>
              <p v-else class="text_center">没有找到数据···</p>
            </el-scrollbar>
          </el-tab-pane>
        </el-tabs>
      </el-popover>
    </div>
  </div>
</template>

<script>
import store from '@/store'
import router from '@/router'
import { mapGetters } from 'vuex'
import { Send } from '@/utils/telWebsocket'
import { getCallOutprefix } from '@/api/teloperation'
// import { getOrderLists } from '@/api/memberManagement/memberList'
import { getOrderLists } from '@/api/memberManagement/memberList'
import { getCurentCallRecords } from '@/api/teloperation'
import { secondToDuring, timesAgo } from '@/filters'
import { getNowDate, getPreDate } from '@/utils'

export default {
  name: 'Dialplate',
  filters: {
    telFilter (val) {
      if (!val.includes('-')) {
        if (val.length === 12) {
          val = val.substring(1, 4) + '-' + val.substring(4, 8) + '-' + val.substring(8, 12)
        } else if (val.length === 11) {
          val = val.substring(0, 3) + '-' + val.substring(3, 7) + '-' + val.substring(7, 11)
        }
      }
      return val
    }
  },
  data () {
    return {
      loading1: false,
      loading2: false,
      telNumber: '',
      scoketDatas: '',
      isShowDelNum: false,
      dialNums: [
        ['1', '2', '3'],
        ['4', '5', '6'],
        ['7', '8', '9'],
        ['*', '0', '#']
      ],
      tabActiveName: 'second',
      s_keywords: '',
      pageParams: {
        pageindex: 1, // 当前第几页
        pagesize: Number(this.$store.getters.serverConfig.PAGESIZE), // 每页几条数据
        total: 0 // 总共多少数据
      },
      isShowOrderIcon: false,
      phoneLists: [],
      recentCalls: []
    }
  },
  computed: {
    ...mapGetters([
      'usercode', // 工号
      'extension', // 分机号
      'sidebar',
      'avatar',
      'telCallType', // 通话类型
      'telIsVisCallout' // 外呼面板是否显示
    ])
  },
  watch: {
    telIsVisCallout: function (newVal, oldVal) {
      if (newVal) {
        this.tabActiveName = 'first'
      }
    }
  },
  created () {
    document.onkeyup = (e) => {
      if (e.keyCode === 13) {
        if (this.tabActiveName === 'first') {
          // this.getTelHisList()
        } else if (this.tabActiveName === 'second') {
          this.getMailList()
        }
      }
    }
  },
  methods: {
    // 获取通话历史记录
    getTelHisList () {
      this.loading1 = true
      const stime = getPreDate(3600 * 1000 * 24 * 7) // 不传参数是30天前
      const etime = getNowDate()
      const params = {
        stime, // 开始时间
        etime, // 结束时间
        keyword: this.s_keywords //	否	string	模糊查询（呼叫号码）
      }
      getCurentCallRecords(params).then(res => {
        this.loading1 = false
        this.recentCalls = []
        if (res.state.toLowerCase() === 'success') {
          const resItems = res.data.rows
          if (resItems && resItems.length) {
            resItems.forEach(element => {
              this.recentCalls.push({
                id: element.id,
                name: element.name || '未知', // 姓名 默认 未知
                tel: element.callnumber, // '15235457489' 呼叫号码
                time: element.endtime, // '16:00' 挂机时间
                isCallOut: element.calltype === 1, // 是否是呼出  "calltype": 1,//呼叫类型：0呼入，1呼出
                isOrder: element.existorder !== '无', // 是否有工单
                isConect: element.callstate === 1, // 是否正常接通 //呼叫状态：0未接通，1已接通
                callTimes: element.longs_talk// 通话时长
              })
            })
          }
        }
      })
    },
    // 获取通讯录
    getMailList () {
      this.loading2 = true
      const params = {
        pageindex: this.pageParams.pageindex, // 第几页
        pagesize: this.pageParams.pagesize, // 每页几条信息
        keyword: this.s_keywords // 否	string	模糊查询（姓名，手机号码，固话）
      }
      getOrderLists(params).then(res => {
        this.loading2 = false
        this.phoneLists = []
        if (res.state.toLowerCase() === 'success') {
          if (res.rows) {
            this.pageParams.total = res.rows.Totals
            if (res.rows.Rows && res.rows.Rows) {
              res.rows.Rows.forEach(val => {
                this.phoneLists.push({
                  name: val.F_Name,
                  tel: val.F_Phone
                })
              })
            }
          }
        }
      })
    },
    // 点击拨号键
    dialNumHandler (tnum) {
      this.isShowDelNum = true
      if (this.telNumber.length === 12) {
        this.$message({
          message: '电话号码不能超过12位！',
          type: 'warning'
        })
        return
      }
      this.telNumber += tnum
      // store.dispatch('ChangeCallNum', this.telNumber);
    },
    callOutInput () {
      this.isShowDelNum = true
      if (this.telNumber.length === 0) {
        this.isShowDelNum = false
      }
      if (this.telNumber.length === 12) {
        this.$message({
          message: '电话号码不能超过12位！',
          type: 'warning'
        })
        return
      }
      // store.dispatch('ChangeCallNum', this.telNumber);
    },
    // 删除电话号码
    delNum () {
      this.telNumber = this.telNumber.substr(0, this.telNumber.length - 1)
      if (this.telNumber.length === 0) {
        this.isShowDelNum = false
      }
      // store.dispatch('ChangeCallNum', this.telNumber);
    },
    // 外呼
    callOut () {
      if (this.telNumber) {
        getCallOutprefix(this.telNumber).then(response => {
          if (response.state.toLowerCase() === 'success') {
            const res = response.data
            switch (this.telCallType) {
              case 'MakeCall':
                this.scoketDatas = {
                  'Type': this.telCallType,
                  'AgentID': this.usercode,
                  'AgentExten': this.extension,
                  'Header': res.fix, // 号码前缀 用于截断前缀得到真实号码
                  'DestinationNumber': res.phone //
                }
                break
              case 'Meeting':
                this.scoketDatas = {
                  'Type': this.telCallType,
                  'AgentID': this.usercode,
                  'AgentExten': this.extension,
                  'DestinationNumber': res.phone // 会议目标号码
                }
                break
              case 'Transfer':
                this.scoketDatas = {
                  'Type': this.telCallType,
                  'AgentID': this.usercode,
                  'AgentExten': this.extension,
                  'DestinationNumber': res.phone // 转移目标号码
                }
                break
              // case 'Consult': // 协商呼叫
              //   this.scoketDatas = {
              //     'Type': this.telCallType,
              //     'AgentID': this.usercode,
              //     'AgentExten': this.extension,
              //     'Callee': res.phone, // 对方号码
              //     'Caller': this.extension // 自己的号码(分机号)
              //   }
              //   break
              default:
                break
            }
            store.dispatch('ChangeCallNum', this.telNumber)
            Send(this.scoketDatas)
            store.dispatch('UpdateCalloutScreen', !this.telIsVisCallout)// 关闭外呼面板
            this.telNumber=''
          }
        })
      } else {
        this.$message({
          message: '请先输入电话号码！',
          type: 'warning'
        })
      }
    },
    // tab切换
    handleClick (tab, event) {
      if (tab.name === 'first') {
        // this.getTelHisList()
      } else if (tab.name === 'second') {
        this.getMailList()
      }
    },
    // 点击历史记录通讯录中的号码 外呼
    recentCallOut (tel) {
      if (tel.length === 12) {
        tel = tel.substring(1)
      }
      this.telNumber = tel
      this.callOut()
    },
    // 展示隐藏工单图标
    showOrderIcon () {
      this.isShowOrderIcon = !this.isShowOrderIcon
    },
    // 点击工单图标去 该工单详情页面
    goOrderList (tel) {
      store.dispatch('UpdateCalloutScreen', !this.telIsVisCallout)// 关闭外呼面板
      // 带查询参数，变成 /order/orderSearchHY?tel=xxx
      router.push({ path: '/order/orderSearchHY', query: { tel } })// 工单列表
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.plate {
  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;
  }
}
.phone_lists {
  background-color: #5b6369;
  padding: 0;
  top: 50px !important;
  z-index: 2001 !important;
  box-shadow: none !important;
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 0;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
  border-color: #5b6369;
  color: #ffffff;
}
.phnoe_tabs {
  width: 100%;
  height: 454px;
  border-bottom-right-radius: 10px;
  background-color: #5b6369;
  padding: 15px;
  color: #fff;
  .el-tabs__header {
    .el-tabs__active-bar {
      background-color: #ffffff;
    }
    .el-tabs__nav-wrap::after {
      background-color: #5b6369;
    }
    .el-tabs__item,
    .el-tabs__item.is-active {
      color: #ffffff;
    }
  }
  .el-tabs__content {
    .el-input {
      margin-top: 0px;
      margin-bottom: 20px;
    }
    .el-input__inner {
      border-radius: 14px;
    }
  }
  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
.dialplate {
  .plate {
    width: 100%;
    height: 454px;
    position: relative;
    background-color: #42484d;
    border-bottom-left-radius: 10px;
    padding: 24px 30px;
    text-align: center;
    .del_num {
      position: absolute;
      right: 12px;
      top: 32px;
      width: 31px;
      height: 16px;
      display: inline-block;
      cursor: pointer;
      background: url(../../assets/imgs/del_num.png) left center no-repeat;
    }
    .btn_call {
      margin-top: 22px;
      width: 142px;
      height: 46px;
      background-color: #1bce7d;
      border-radius: 23px;
    }
    .btn_call:hover {
      background-color: #4be59f;
      border-color: #4be59f;
    }
  }
}
.phnoe_tabs {
  .h_list_title {
    position: relative;
    font-size: 14px;
    padding-bottom: 10px;
    width: 100%;
    border-bottom: 1px solid #4b5155;
    .svg-icon {
      position: absolute;
      vertical-align: middle;
      cursor: pointer;
      font-size: 18px;
      right: 7px;
      top: 5px;
    }
  }

  .recent_calls_lists {
    width: 100%;
    padding-left: 30px;
    .recent_calls_item {
      list-style: none;
      border-bottom: 1px solid #4b5155;
      height: 56px;
      line-height: 56px;
      .recent_calls_item_left {
        position: relative;
        float: left;
        font-size: 14px;
        cursor: pointer;
        .svg-icon {
          position: absolute;
          left: -24px;
          top: 19px;
          font-size: 18px;
        }
        .recent_calls_item_name {
          line-height: 18px;
          margin: 6px 0 0 0;
        }
        .recent_calls_item_tel {
          line-height: 18px;
          margin: 4px 0 0 0;
        }
      }
      .recent_calls_item_right {
        float: right;
        position: relative;
        .recent_calls_item_time {
          color: #999999;
          padding-right: 42px;
        }
        .svg-icon {
          position: absolute;
          right: 7px;
          top: 17px;
          cursor: pointer;
          font-size: 20px;
        }
      }
      .name_state {
        color: #fa7171;
      }
    }
  }
}
</style>
