// IVR websocket
import { getProject } from '@/utils/baseConfig'
import { createCommand } from '@/utils/ivrtools'
import sapoOcx from 'sapoOcx'
import { Message } from 'element-ui'

const ivr = {
  namespace: true,
  state: {
    websocket: null, // websocket
    websocketObj: null, // websocket返回值对象
    queue: 'kefu', // 技能组
    skill: '1', // 技能组
    busyString: '忙碌', // 致忙原因
    autoAcw: '3', // 自动化后
    extensionList: [], // 分机列表
    wsStatus: false, // websocket连接状态：已连接为true，否则为false
    extension: null, // 分机号
    agentStaffid: null, // 坐席工号,用户id
    agentName: null, // 坐席名称，用户名称
    signStatus: false, // 签入状态：true为已签入，false为未签入
    busyStatus: null, // 忙碌状态 ：忙碌，空闲,
    callStatus: null, // 通话状态: 开始拨号，通话结束，外呼通话,呼入通话,自动外呼接入
    agentStatus: null, // 坐席状态: 已登录为true，其他为false
    isInCall: false, // 是否在通话中,通话中未true,其他为false
    isInComming: false, // 是否来电，外部来电为true，其他为false
    reg: '', // 话机状态： outbound ringing， outbound answered, incomming ringing, incomming answered, holding, unholding
    number: '', // 通话号码
    dialStatus: '' // 拨号状态
  },
  mutations: {
    SET_WEBSOCKET: (state, websocket) => {
      state.websocket = websocket
    },
    SET_WEBSOCKET_OBJ: (state, websocketObj) => {
      state.websocketObj = websocketObj
    },
    SET_SYSTEM: (state, system) => {
      state.system = system
    },
    SET_EXTENSION_LIST: (state, extensionList) => {
      state.extensionList = extensionList
    },
    SET_WS_STATUS: (state, wsStatus) => {
      state.wsStatus = wsStatus
    },
    SET_EXTENSION: (state, extension) => {
      state.extension = extension
    },
    SET_AGENT_NAME: (state, agentName) => {
      state.agentName = agentName
    },
    SET_AGENT_STATUS: (state, agentStatus) => {
      state.agentStatus = agentStatus
    },
    SET_SIGN_STATUS: (state, signStatus) => {
      state.signStatus = signStatus
    },
    SET_BUSY_STATUS: (state, busyStatus) => {
      state.busyStatus = busyStatus
    },
    SET_CALL_STATUS: (state, callStatus) => {
      state.callStatus = callStatus
    },
    SET_IS_IN_CALL: (state, isInCall) => {
      state.isInCall = isInCall
    },
    SET_IS_IN_COMMING: (state, isInComming) => {
      state.isInComming = isInComming
    },
    SET_REG: (state, reg) => {
      state.reg = reg
    },
    SET_NUMBER: (state, number) => {
      state.number = number
    },
    SET_DIAL_STATUS: (state, dialStatus) => {
      state.dialStatus = dialStatus
    },
    RESET_WS: (state) => {
      state.extension = null
      state.agentStaffid = null
      state.agentName = null
      state.skill = null
      state.signStatus = false
      state.callStatus = null
      state.agentStatus = null
      state.busyStatus = null
      state.holdStatus = null
    }
  },

  actions: {
    // 初始化websocket
    initWebSocket({ dispatch, commit }) {
      // 获取ws的ip和端口号
      const ip = getProject().ws_ip
      const port = getProject().ws_port
      if (!sapoOcx.api.config.initFinish) {
        sapoOcx.api.config.initFinish = true
        setTimeout(dispatch('initWebSocket'), 200)
      } else {
        // 初始化websocket
        const wsUrl = 'ws://' + ip + ':' + port + '/spcc/cti'
        commit('SET_WEBSOCKET', new WebSocket(wsUrl))
        // websocket 连接状态
        ivr.state.websocket.onopen = function() {
          commit('SET_WS_STATUS', true)// 已连接状态
          console.log('init websocket success!')
        }
        ivr.state.websocket.onclose = function() {
          commit('SET_WS_STATUS', false)// ws断开状态
        }
        ivr.state.websocket.onerror = function(event) {
          console.log(event)
        }
        ivr.state.websocket.onmessage = function(event) {
          // 将websocket 返回值转成对象 object
          const obj = event.data
          const data = obj.split('\n')
          const object = {}
          data.forEach(function(value) {
            if (value !== '') {
              const objData = value.split(':')
              object[objData[0]] = objData[1]
            }
          })
          console.log(object)
          commit('SET_WEBSOCKET_OBJ', object)
          // 根据返回值处理
          const messageType = object.messageType.trim() // 消息类型
          if (messageType === 'event') {
            const name = object.name
            if (name === 'agent status') { // 坐席状态
            }
            if (name === 'call status') { // 话机状态
              if (object.call === '空闲') {
                // 如果正在通话，表示通话结束
                if (ivr.state.isInCall) {
                  commit('SET_CALL_STATUS', '通话结束')
                }
                commit('SET_IS_IN_CALL', false)
                // commit('SET_CALL_STATUS', '空闲中')
              } else if (object.call === '外呼通话' || object.call === '呼入通话' || object.call === '自动外呼接入') {
                commit('SET_IS_IN_CALL', true)
                commit('SET_CALL_STATUS', object.call)
                // commit('SET_CALL_STATUS', '通话中')
              } else {
                commit('SET_IS_IN_CALL', true)
                commit('SET_CALL_STATUS', object.call)
              }
            }
            if (name === 'outbound ringing') { // 外呼振铃
              commit('SET_REG', 'outbound ringing')
            }
            if (name === 'outbound answered') { // 外呼接通,
              commit('SET_IS_IN_COMMING', false)
              commit('SET_REG', 'outbound answered')
            }
            if (name === 'incomming ringing') { // 内呼振铃
              commit('SET_REG', 'incomming ringing')
            }
            if (name === 'incomming answered') { // 来电接通
              commit('SET_IS_IN_COMMING', true)
              commit('SET_REG', 'incomming answered')
            }
            if (name === 'hangup') { // 挂断
              commit('SET_REG', 'hangup')
            }
            if (name === 'status changed') { // 状态改变
              commit('SET_BUSY_STATUS', object.busy)
              // commit('SET_AGENT_STATUS', object.agent)
              commit('SET_NUMBER', object.number)
              if (object.reg === '离线' || object.reg === '未知') {
                Message.warning('话机已离线，请检查！')
              }
            }
            if (name === 'queue status') {
              // OnQueueStatusChanged_cb(object.idle, object.agent, object.guest, object.queue)
            }
            if (name === 'busy status') {
            }
          } else if (messageType === 'heartbeat response') { // 心跳回复
            // TODO:心跳回复
          } else if (messageType === 'command response') { // 命令回复
            if (object.success && object.success.trim() === 'false') {
              Message.warning(object.resultText)
            }
            const command = object.command
            if (command === 'login') { // 签入结果
              if (object.success === 'true') { // 签入成功
                Message.success('签入成功')
                commit('SET_SIGN_STATUS', true)
              } else {
                // Message.error(object.resultText)
              }
            } else if (command === 'logout') { // 签出结果
              if (object.success === 'true') {
                commit('SET_SIGN_STATUS', false)
                commit('RESET_WS')
              }
            } else if (command === 'getExtensionList') { // 分机列表结果
              if (object.success) {
                const test = object.resultText
                const index = test.indexOf(',')
                const seatsList = []
                if (index > 0) {
                  const messageList = test.split(',')
                  for (let i = 0; i < messageList.length; i++) {
                    const tList = messageList[i].split('|')
                    const seat = {
                      exten: tList[0],
                      name: tList[1],
                      loginId: tList[2],
                      sector: tList[3],
                      group: tList[4],
                      state: tList[5],
                      busy: tList[6]
                    }
                    seatsList.push(seat)
                  }
                }
                commit('SET_EXTENSION_LIST', seatsList)
              }
            } else if (command === 'dial') { // 呼叫结果
              if (object.success === 'true') {
                console.log('DIAL_STATUS:' + object.resultText)
                commit('SET_DIAL_STATUS', object.resultText)
              }
            } else if (object.resultText === '准备挂断' && object.success === 'true') {
              // this.statusShow = false
            } else if (object.resultText === '准备保持' && object.success === 'true') {
              if (object.type === '') { // 保持成功后
                commit('SET_REG', 'holding')
              } else if (object.type === 'off') { // 解除保持成功后
                commit('SET_REG', 'unholding')
              }
            }
          }
        }
      }
    },
    // 签入 参数：userid用户id, deptid部门id, deptName部门名字，extension分机号，agentName坐席号
    signin({ dispatch, commit }, { userId, deptid, deptName, nowExten, agentName }) {
      commit('SET_EXTENSION', nowExten)
      commit('SET_AGENT_NAME', agentName)
      const sendObj = {
        agent: agentName,
        extension: nowExten,
        queue: ivr.state.queue,
        staffid: userId,
        busyString: ivr.state.busyString,
        skill: ivr.state.skill,
        secid: deptid,
        secname: deptName,
        autoacw: '',
        domain: '',
        security: ''
      }
      const strSend = createCommand('login', sendObj)
      ivr.state.websocket.send(strSend)
    },
    // 签出
    signout({ dispatch, commit }) {
      const strSend = 'command:logout\n\n'
      ivr.state.websocket.send(strSend)
    },
    // 示忙
    onbusy({ dispatch, commit }) {
      const strSend = createCommand('busy')
      ivr.state.websocket.send(strSend)
      commit('SET_BUSY_STATUS', '1')
    },
    // 示闲
    onidle({ dispatch, commit }) {
      const strSend = createCommand('idle')
      ivr.state.websocket.send(strSend)
      commit('SET_BUSY_STATUS', '0')
    },
    // 挂机
    hangup({ dispatch, commit }) {
      const strSend = createCommand('hangup')
      ivr.state.websocket.send(strSend)
    },
    // 保持
    hold({ dispatch, commit }) {
      const strSend = createCommand('hold')
      ivr.state.websocket.send(strSend)
    },
    // 解除保持
    unhold({ dispatch, commit }) {
      const strSend = createCommand('unhold')
      ivr.state.websocket.send(strSend)
    },
    // 获取坐席列表
    getExtensionList({ dispatch, commit }, params) {
      const strSend = createCommand('getExtensionList', params)
      ivr.state.websocket.send(strSend)
    },
    // 拨号
    dial({ dispatch, commit }, tel) {
      commit('SET_CALL_STATUS', '开始拨号')
      const sendObj = {
        dialString: tel,
        cusid: '',
        cusname: '',
        proid: '',
        proname: ''
      }
      const strSend = createCommand('dial', sendObj)
      ivr.state.websocket.send(strSend)
    },
    // 三方
    meeting({ dispatch, commit }, tel) {
      const params = {
        dialString: tel
      }
      const strSend = createCommand('threeWay', params)
      ivr.state.websocket.send(strSend)
    },
    // 转接
    transfer({ dispatch, commit }, tel) {
      const params = {
        dialString: tel
      }
      const strSend = createCommand('transfer', params)
      ivr.state.websocket.send(strSend)
    },
    // 分机监听
    spy({ dispatch, commit }, exten) {
      const params = {
        extension: exten
      }
      const strSend = createCommand('spy', params)
      ivr.state.websocket.send(strSend)
    },
    // 组监听
    groupSpy({ dispatch, commit }, group) {
      const params = {
        group: group
      }
      const strSend = createCommand('groupSpy', params)
      ivr.state.websocket.send(strSend)
    },
    // 取消ivr监听
    inject({ dispatch, commit }) {
      const strSend = createCommand('Inject')
      ivr.state.websocket.send(strSend)
    },
    // 转接ivr节点
    transferIvr({ dispatch, commit }, ivrCode) {
      const params = {
        ivr: ivrCode
      }
      const strSend = createCommand('transferIvr', params)
      ivr.state.websocket.send(strSend)
    },
    // 组抢接
    groupPickUp({ dispatch, commit }, group) {
      const params = {
        group: group
      }
      const strSend = createCommand('groupPickup', params)
      ivr.state.websocket.send(strSend)
    },
    // 分机监听
    extenPickUp({ dispatch, commit }, exten) {
      const params = {
        extension: exten
      }
      const strSend = createCommand('pickupExtension', params)
      ivr.state.websocket.send(strSend)
    },
    // 盲抢
    pickUp({ dispatch, commit }) {
      const strSend = createCommand('pickup')
      ivr.state.websocket.send(strSend)
    },
    // 分机强插
    extenInsert({ dispatch, commit }, exten) {
      const params = {
        extension: exten
      }
      const strSend = createCommand('insertExtension', params)
      ivr.state.websocket.send(strSend)
    },
    // 分机强拆
    extenCut({ dispatch, commit }, exten) {
      const params = {
        extension: exten
      }
      const strSend = createCommand('cutExtension', params)
      ivr.state.websocket.send(strSend)
    }

  }
}

export default ivr
