<template>
  <div class="ys-float-btn" v-show="userInfo.extNo!=null" :style="{'width':'500px','height':'50px','left':left+'px','top':top+'px'}"
       ref="div"> 
       <el-row>
         <el-col :span="2">
           <div class="status" @click="handle_Cti_Login(false)">
           <svg-icon :icon-class='status_icon'></svg-icon>
           </div>
         </el-col>
         <el-col class="title" :span="10">
           <span>{{title}}</span>
           <span class="span">{{status}}{{title_timer|durationFilter}}</span>
         </el-col>
          <el-col :span="7"> 
            <el-input id='txt_callout' v-model="call.mobile" v-show="status=='空闲'" type="text" size="mini" placeholder="请输入拨打号码">
              <el-button  style="padding-right:10px" size="mini" slot="suffix" type="text" @click="handle_Cti_DialOut(null)">拨打</el-button>
            </el-input>
         </el-col>
          <el-col :span="2"> 
            <div class="div" @click="handle_Cti_Hold" v-show="status=='通话中'||status=='保持'"> 
               <svg-icon class="svg" :icon-class="ctiHold.icon"></svg-icon> 
               <span class="span">{{ctiHold.title}}</span> 
            </div>
         </el-col>
          <el-col :span="3">
            <!-- <div class="div" id='callRest' v-show="status=='空闲'||status=='小休'" @click="handle_Cti_Rest"> 
               <svg-icon class="svg" :icon-class="ctiRest.icon"></svg-icon> 
            </div>  -->
            <el-dropdown class="avatar-container right-menu-item" v-show="status=='空闲'||status=='小休'" trigger="click">
               <div class="div">  
                  <svg-icon class="svg svg-rest" :icon-class="ctiRest.icon"></svg-icon>
                  <span class="span">{{ctiRest.title}}</span>  
               </div> 
               <el-dropdown-menu slot="dropdown">  
                  <el-dropdown-item >
                     <div  @click="handle_Cti_Rest(0)" v-show="status=='小休'">
                     <svg-icon class="svg svg-rest" icon-class="call-ready"></svg-icon> 示闲
                     </div>
                  </el-dropdown-item> 
                   <el-dropdown-item >
                     <div  @click="handle_Cti_Rest(2)"  v-show="status=='空闲'">
                     <svg-icon class="svg svg-rest" icon-class="call-rest"></svg-icon> 午休
                     </div>
                  </el-dropdown-item> 
                  <el-dropdown-item> 
                    <div  @click="handle_Cti_Rest(3)"  v-show="status=='空闲'">
                      <svg-icon class="svg svg-rest" icon-class="call-meeting"></svg-icon> 会议
                     </div>
                  </el-dropdown-item> 
                  <el-dropdown-item> 
                    <div  @click="handle_Cti_Rest(4)"  v-show="status=='空闲'">
                     <svg-icon class="svg svg-rest" icon-class="call-training"></svg-icon> 培训
                    </div>
                  </el-dropdown-item> 
              </el-dropdown-menu>
             </el-dropdown>
            
            <div class="div" @click="handle_Cti_Hangup" v-show="status=='通话中'||status=='响铃中'||status=='呼叫中'"> 
               <svg-icon class="svg" icon-class="call-hangup"></svg-icon> 
               <span class="span">挂断</span> 
            </div>

         </el-col>
       </el-row>  
  </div>
</template>
 
<script>  

 import { readAdmin } from '@/api/admin'  
 import { createCallRecord,updateCallRecord,createRest,addRelation,updateCallRecords } from '@/api/cti'  
 import { findOrAdd } from '@/api/customer'  
 import { formatDate } from '@/utils/date'  
 import { status } from 'nprogress'

  export default {
    name: "cti",
    filters: {
      durationFilter(value){
        if(value==null) 
           return " 00:00"

        let m=parseInt(value/60)
        let s=parseInt(value%60)

        m=m.toString().length<2?"0"+m.toString():m.toString();
        s=s.toString().length<2?"0"+s.toString():s.toString();

        return " "+m+":"+s  
      }
     },
    props:{  
      gapWidth:{
        type:Number,
        default:10
      } 
    }, 
    mounted() { 
      this.timer = setInterval(this.handleTimer, 1000);
    }, 
    created(){ 
      this.left = (document.documentElement.clientWidth - 500-20 )/2;
      this.top =5;// this.clientHeight*this.coefficientHeight; 

      //开始注册cti
      this.handle_Cti_Login(true); 
      //this.handleIB();
    },
    data(){
      return{
        timer:null,  
        left:0,
        top:0, 
        userInfo:{},//坐席
        ctiRest:{title:'小休',icon:'call-rest',type:0,duration:0,start:undefined},
        ctiHold:{title:'保持',icon:'call-hold'},
        call:{//外呼电话内容 source:ib campaign ticket toolbar
          builtId:0,
          ticketId:0,
          customerId:0,
          mobile:'',
          name:'',
          type:'OB',//ob ib
          source:''},
        status_login:false,//是否登录成功
        status:'未登录',//坐席状态:拨打、响铃中、通话中、话后、空闲、小休、通话保持
        status_icon:'call-signout',//状态栏图标
        status_timer:false,//timer计数器状态 true计数 false停止
        status_active:'',//重来防止重复命令
        title:'未设置分机号，登录失败',//状态栏显示内容 
        title_timer:0,//状态栏计数器
        records:[],
        record:{//当前通话记录
          id:0,
          callId:undefined,
          ringingtime:0,
          talktime:0, 
          mobile:''
        }//各状态持续时间 
      }
    },
    methods:{
      handle_Cti_Login(_init){//0 初始化登录 1点击按钮登录

        if(this.status_login) return

        //将被动函数委托给global
        hollyglobal.msgEvent=this.handle_Cti_Msg; 
        //hollyglobal.hangupEvent=this.handle_Cti_Hangup; 
        hollyglobal.ringEvent=this.handle_Cti_Ringing; 
        hollyglobal.talkingEvent=this.handle_Cti_Talking; 
        hollyglobal.loginSuccessCallback=this.handle_Cti_Login_Success; 
        hollyglobal.loginFailureCallback=this.handle_Cti_Login_Failure; 
        hollyglobal.actionEvent=this.handle_Cti_Action_Result
        hollyglobal.dialoutEvent=this.handle_Cti_DialOut
        hollyglobal.saveRecordEvent=this.handleReset
        //获取分机并注册
       readAdmin().then(res=>{ 
         this.userInfo=res.data.data  
         if(this.userInfo.extNo) {
            this.title='话机注册中'
            this.status_timer=true 
            if(_init)
               hollyglobal.login(this.userInfo.extNo);
            else 
              hollyglobal.reLogin();
         }
       })
      },
      handle_Cti_Msg(msg,id){ 
        this.$notify.error({
              title: '提醒',
              message: msg
          })
      },
      handle_Cti_DialOut(call){//开始拨打 
         
         if (!holly.phone.phone_isAllowDialout()) {
             this.handle_Cti_Msg('话机状态不对，无法外呼')
             this.handleStatus('unregister',null)
             return
           }  
           if(call!=null) this.call=call 
           else {
             this.call.source='toolbar';//工具条外呼
             this.call.type='OB'
           }

          //console.info(call) 
          if(this.call.mobile==null||this.call.mobile.length<8){
             this.$notify.error({
              title: '提醒',
              message: '请输入正确的电话号码'
             })
            return
          }

         if(holly.phone.phone_dialout(this.call.mobile)){//执行拨打成功 
           this.handleStatus('呼叫中',this.call.mobile);
           this.handleCreateRecord();
         } 
         
      }, 
      handle_Cti_Hangup(value){//挂断 
        holly.phone.phone_hangup();  
      }, 
      handle_Cti_Ringing(event){//响铃
       
        if(this.status=='响铃中') return;

         //console.info(event) 
         this.record.recordId=event.Data.CallSheetID;//通话id

         if(event.ChannelType=='dialout'){
           this.call.type='OB'
           this.call.mobile=event.FromDid;
           this.title=event.FromDid+'('+event.CalleeCity+')'; 
           this.handleUpdateRecord(0);
         }
         else {
            this.call.type='IB'  
            this.call.mobile=event.FromCid;
            this.title=event.FromCid+'('+event.CallerCity+')'; 
            this.call.source='IB'
            this.handleIB();
         }
         this.handleStatus('响铃中',null)
      },
      handle_Cti_Talking(value){//通话中
          if(this.status=='通话中') return;
          this.handleStatus('通话中',null) 

          this.record.connected=true;//接通
          this.handleUpdateRecord(0);
      },
      handle_Cti_Hold(){//通话保持或接回
       if(this.ctiHold.title=="保持")
         holly.phone.phone_hold()
       else
         holly.phone.phone_unhold()
      },
      handle_Cti_Login_Failure(_result){//登录失败
          //console.info(_result)  
          this.handleStatus('未登录',_result) 
      },
      handle_Cti_Login_Success(value){//登录成功
       //console.info(holly.phone._phone_currentState)
       //console.info(value)
       //if(holly.phone._phone_currentState!=1) return;//1状态空闲
       this.status_login=true  
       this.handleStatus('空闲','注册成功')   
      },
      handle_Cti_Rest(_type){//小休设置  type:0 示闲 1 午休 2meeting 3training  
         console.info('holly.phone.phone_setBusy:'+_type) 
         if(_type==0){ 
            this.handleCreateRest()
            this.ctiRest.type=_type;
            holly.phone.phone_setBusy(false,0)  
         } 
         else { 
           this.ctiRest.type=_type;
           holly.phone.phone_setBusy(true,_type)   
         }
         
      }, 
      handle_Cti_Action_Result(state,result){ //执行结果 1小休设置 2挂断 3保持 
        //console.info('active:'+state+' result:'+result) 
        if(this.status_active==state&&state!='busy') return;
        this.status_active=state; 

       //console.info('active1:'+state+' result:'+result) 

        if(state=='busy'){
           if(result) {//致忙 
            var desc="休息中，勿扰"
            if(this.ctiRest.type==3) desc='会议中'
            else if(this.ctiRest.type==4) desc='培训中'
            else if(this.ctiRest.type==2) desc='午休中，请勿打扰' 
            this.handleStatus('小休',desc)  
           }
           else { 
             this.handleStatus('空闲','空闲') 
           }
        } 
         else if(state=="hangup"||state=="hold"||state=='unhold'||state=='unregister'){  
            this.handleStatus(state,null)
         }  
      },
      handleStatus(_status,_title){//状态变更   
         if(this.status==(_status=='unhold'?'通话中':(_status=='unregister'?'未登录':_status))) return;//重复状态 不处理  

         this.status=_status
         if(_title!=null) this.title=_title

         if(_status=='unhold')//保持接回时 从上次通话时间 开始计时
           this.title_timer=this.record.talktime;
         else
           this.title_timer=0;
 
         //console.info(this.title_timer) 
         this.title_timer=true 
         console.info(_status)


        if(_status=='空闲'){ 
           this.status_icon='call-ready' 
           this.ctiRest.title='小休'
           this.ctiRest.icon='call-rest' 
        }
        else if(_status=='小休'){
           this.status_icon='call-locked' 
           this.ctiRest.title='示闲'
           this.ctiRest.icon='call-ready' 
           this.ctiRest.start=new Date();
        }
        else if(_status=='呼叫中'){
           this.status_icon='call-out'  
        }
        else if(_status=='响铃中'){
           this.status_icon='call-ringing'  
        } 
        else if(_status=='通话中'){
           this.status_icon='call-talking'  
        }
        else if(_status=='话后'){
           this.status_icon='call-acw'  
        }
        else if(_status=='未登录'){
          this.status_icon='call-signout'
        }
        else if(_status=='hangup'){//挂断  呼出时 如果builtid=0 表示非非任务外呼 不进入话后  
          this.handleUpdateRecord(0); 
          if(this.call.type=='OB'&&this.call.builtId==0) { 
            //非任务发起的外拨 挂断后 直接初始化工具栏
            this.handleReset(0); 
           }
           else {
             this.status_icon='call-acw'  
             this.status='话后'
             this.title='话后处理中'
           } 
        }
        else if(_status=='hold'){
          this.status='保持'
          this.status_icon='call-hold' 
          this.ctiHold.title='接回'
          this.ctiHold.icon='call-talking'
        }
        else if(_status=='unhold'){
          this.status='通话中'
          this.status_icon='call-talking' 
          this.ctiHold.title='保持'
          this.ctiHold.icon='call-hold'
        }
        else if(_status=='unregister'){
          this.status='未登录'
          this.title="注册失败点击图标重新登录"
          this.status_icon='call-signout' 
          this.status_login=false
        }  

      }, 
      handleIB(){
        findOrAdd(this.call.mobile).then(res=>{
          this.call.customerId=res.data.data
          this.$store.commit('showPanel',{customerId:this.call.customerId,panelType:'IB',startTime:formatDate(new Date(),'yyyy-MM-dd hh:mm:ss')});
          this.$store.dispatch('CUSTOMER_DETAIL',{id:this.call.customerId});
          //保存话务记录
          this.handleCreateRecord(0);

        }) 
      },
      handleCreateRecord(){//新增话务记录
        //console.info(this.call) 
        this.record.mobile=this.call.mobile
        this.record.customerId=this.call.customerId;
        this.record.callType=this.call.type;
        this.record.callSource=this.call.source 
           //console.info(this.record)
        createCallRecord(this.record).then(res=>{ 
           this.record.id=res.data.data;
           //如果ticketId》0表示是按工单外拨 需要关联此话务id
           if(this.call.ticketId>0){
             var data={
               ticketId:this.call.ticketId,
               type:1,
               fId:this.record.id,
               deleted:false
             }; 
             addRelation(data);
           }
           else if(this.call.builtId>0) {//任务外呼 才将话务信息记录到数据 最后统一更新
               this.records.push(this.record); 
           } 

         }).catch(res=>{ 
           //console.info(res) 
         })

      },
      handleUpdateRecord(_callid){//更新话务记录 
        if(this.record.id==0) return;
      
       this.record.callId=_callid;
        //console.info(this.record)
        updateCallRecord(this.record).then(res=>{ 
            //console.info(res)
         })

      },
      handleCreateRest(){//保存小休
        var data={
          type:this.ctiRest.type,
          duration:this.ctiRest.duration,
          startTime:formatDate(this.ctiRest.start,'yyyy-MM-dd hh:mm:ss'),
          endTime:formatDate(new Date(),'yyyy-MM-dd hh:mm:ss')
        }
        //console.info(data)
        createRest(data).then(res=>{

        })

      },
      handleReset(_callId){//状态重置 

      //更新话务记录 会存在多条情况
        if(this.records.length>0&&this.call.builtId>0){
          for(let i=0;i<this.records.length;i++){
            this.records[i].callId=_callId;
          }

          updateCallRecords(this.records).catch(res=>{
            this.handle_Cti_Msg(res.data.errmsg,0) ;
          }) 
        }

        this.records=[];
        this.record={
          id:0,
          callId:undefined,
          ringingtime:0,
          talktime:0, 
          mobile:''
        };
        this.call={
          builtId:0,
          ticketId:0,
          customerId:0,
          mobile:'',
          name:'',
          type:'OB',
          source:''
        }
        this.status_active=''; 
        holly.phone.phone_setBusy(false,0) ;

      },
      handleTimer(){ 
        if(this.status_timer){
           this.title_timer++;
           //console.info(this.title_timer)
           if(this.status=='响铃中')
             this.record.ringingtime=this.title_timer
           else if(this.status=='通话中'&&this.record.talktime<this.title_timer )
             this.record.talktime=this.title_timer  
           else if(this.status=='小休'){
             this.ctiRest.duration=this.title_timer
           }
        }
      }
      
    }
  }
</script>

<style scoped>
  .ys-float-btn{
    background:#46a6ff;
    box-shadow:0 2px 10px 0 rgba(0,0,0,0.1);
    border-radius:25px;
    color: #666666;
    z-index: 9999;
    transition: all 0.3s; 
    flex-direction: column;
    justify-content: center;
    align-items: center; 
    position: fixed;
    bottom: 20vw;  

  }
  .status{
    height:50px;
    width:50px;
    border-radius:25px;
    background-color: rgb(102, 102, 245);
    color: white;
    margin:-1px
  }
  .svg-icon{
    height: 1.5em !important;
    width: 1.5em !important;
    color: white;    
    margin-top: 13px;
  }
  .svg-rest{
    color:#606266
  }
  .el-col{
    text-align: center;
    border:1px solid transparent
  }
  .el-col span{
    line-height:0px;
    color: white;
  }
  .el-col span br{
    line-height:0px;
  }

  .title{
    line-height: 30px;
    font-size: 14px;
  }

  .title .span{
     display:block;
     font-size: 10px;
  }

  .svg{
     margin-top: 5px;
  }

  .span{
    font-size: 9px;
    margin-top: 8px;
  }
  .div{
    display: flex;
    flex-direction: column;
    text-align: center;
    align-items: center; 
    cursor: pointer;
  } 
</style>