<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->

<template>
  <div class="app-container ">
    <div class="max-h-screen">

      <!-- 状态统计区域 -->
      <div class="">
        <div class="max-w-7xl mx-auto px-4">
          <div class="grid grid-cols-6 gap-4">
            <div v-for="(stat, index) in statistics" :key="index" class="p-4 rounded-lg" :class="stat.bgColor">
              <div class="text-lg font-medium mb-2">{{ stat.label }}</div>
              <div class="text-2xl font-semibold">{{ stat.count }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 坐席列表 -->
      <div class="pb-8">
        <div class="bg-white rounded-lg shadow-sm p-6">
          <div class="mb-6 flex justify-between items-center">
            <h1 class="text-lg font-medium">坐席监控</h1>
            <div>
              <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 100px;">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-button v-if="!isStartMonitor" class="mx-10" @click="startMonitor">开启监控</el-button>
              <el-button type="success" v-if="isStartMonitor" class="mx-10" @click="cancelMonitor">关闭监控</el-button>
            </div>
          </div>

          <!-- <div class="grid grid-cols-5 gap-2"> -->
            <transition-group class="grid grid-cols-5 gap-2" tag="div" name="fade">  
            <div v-for="agent in filteredAgents" :key="agent.id"
              class="relative bg-white border rounded-lg p-4 hover:shadow-md transition-shadow" :class="{
                'border-green-500': agent.status === 'online',
                'border-red-500': agent.status === 'offline',
                'border-blue-500': ['ringing', 'calling'].includes(agent.status),
                'border-yellow-500': agent.status === 'idle',
                'border-purple-500': agent.status === 'afterCall'
              }">
              <div class="flex items-start">
                <el-avatar :size="48" :src="agent.avatar" />
                <div class="ml-3 flex-1">
                  <div class="font-medium">{{ agent.name }}</div>
                  <div class="text-sm text-gray-500">工号: {{ agent.workId }}</div>
                  <div class="text-sm text-gray-500">姓名: {{ agent.nickName }}</div>
                  <div class="text-sm text-gray-500">分机: {{ agent.extension }}</div>
                </div>
                <div :class="`status-dot ${agent.status}`" />
              </div>

              <div class="mt-3">
                <div class="text-sm mb-2" :class="getStatusClass(agent.status)">
                  {{ getStatusText(agent.status) }}
                  <span v-if="agent.status === 'calling' || agent.status === 'afterCall'">
                    {{ agent.duration }}
                  </span>
                </div>

                <div class="flex justify-between" v-if="isStartMonitor">
                  <el-button v-if="['idle', 'online'].includes(agent.status)" type="primary" :icon="agent.status === 'idle' ? 'Mute' : 'VideoPlay'" size="small"
                    class="!rounded-button whitespace-nowrap" @click="toggleStatus(agent)">
                    {{ agent.status === 'idle' ? '置闲' : '置忙' }}
                  </el-button>
                  <el-dropdown trigger="click" v-if="!['offline', 'unknown'].includes(agent.status) && ['空闲', '小休'].includes(scoketState)">
                    <el-button type="info" size="small" class="!rounded-button whitespace-nowrap">
                      更多操作
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-if="['calling'].includes(agent.status)" @click="oparateSeats(agent,'Break')">强拆</el-dropdown-item>
                        <el-dropdown-item v-if="['calling'].includes(agent.status)" @click="oparateSeats(agent,'Insert')">强插</el-dropdown-item>
                        <el-dropdown-item v-if="['calling'].includes(agent.status)" @click="oparateSeats(agent,'Listen')">监听</el-dropdown-item>
                        <el-dropdown-item v-if="['ringing'].includes(agent.status)" @click="oparateSeats(agent,'Instead')">代接</el-dropdown-item>
                        <el-dropdown-item v-if="['calling'].includes(agent.status)" @click="oparateSeats(agent,'Intercept')">拦截</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </div>
          </transition-group>
          <!-- </div> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="SeatMonitor">
import { ref, computed, onMounted, watch, onBeforeUnmount } from 'vue';
import { Monitor, Search, Mute, VideoPlay } from '@element-plus/icons-vue';
import { getPageListData } from '@/api/main/system/system';
import { Send, ws } from '@/utils/telWebsocket'
import useSocketStore from '@/store/modules/socket'
import { shuffle} from 'lodash'
const { proxy } = getCurrentInstance();

const searchQuery = ref('');
const statusFilter = ref('');
const scoketDatas = ref({})
const scoketState = ref('签出')
// 创建定时，没一秒监听一下坐席状态，并把通话中的坐席的通话时长更新
const timer: any = ref(null)

const lineState = computed(() => {
  return useSocketStore().lineState
})

watch(lineState, (newValue, oldValue) => {
  // console.log(newValue);
  scoketState.value = newValue
})

const statistics = ref([
  { key: 'online', label: '空闲', count: 0, bgColor: 'bg-green-50' },
  { key: 'idle', label: '小休', count: 0, bgColor: 'bg-yellow-50' },
  { key: 'ringing', label: '振铃', count: 0, bgColor: 'bg-blue-50' },
  { key: 'calling', label: '通话中', count: 0, bgColor: 'bg-blue-100' },
  { key: 'afterCall', label: '话后处理', count: 0, bgColor: 'bg-purple-50' },
  { key: 'offline', label: '离线', count: 0, bgColor: 'bg-red-50' },
]);

const statusOptions = [
  { label: '全部', value: '' },
  { label: '空闲', value: 'online' },
  { label: '振铃', value: 'ringing' },
  { label: '通话中', value: 'calling' },
  { label: '小休', value: 'idle' },
  { label: '话后处理', value: 'afterCall' },
  { label: '离线', value: 'offline' },
  // { label: '未知', value: 'unknown' }
];

const agents: any = ref([]);

// 获取坐席列表
const getAgents = () => {
  getPageListData('/UserExtension/userextension').then((res) => {
    if (res.data.length > 0) {
      const info = statistics.value.find((item) => item.key === 'offline');
      if (info) info.count = res.data.length;
      res.data.forEach((ele) => {
        agents.value.push({
          id: ele.id,
          name: ele.username,
          workId: ele.usercode,
          extension: ele.extension, // 分机号
          nickName:ele.nickName,
          status: 'unknown', // 线路状态
          duration: '',
          time: '',
          avatar: 'https://ai-public.mastergo.com/ai/img_res/ab51d696ad01cfa012b8a51117797b21.jpg'
        })
      })
    }
  })
}
let num = 100;
// setInterval(() => {
//   agents.value.push({
//     id: num++,
//     name: '张三',
//     workId: '1001',
//     extension: '1001', // 分机号
//     status: 'online', // 线路状态
//     duration: '',
//      avatar: 'https://ai-public.mastergo.com/ai/img_res/ab51d696ad01cfa012b8a51117797b21.jpg',
//     time: '',
//   });
// }, 5000)

// setInterval(() => {
//   // 随机剔除一条数据
//   // const index = Math.floor(Math.random() * agents.value.length);
//   // agents.value.splice(index, 1);
//   agents.value = shuffle(agents.value)
// }, 8000)

// 发送操作指令
const oparateSeats = (agent, operType) => {
  if (agent.extension == useSocketStore().extensionNumber) {
    proxy.$modal.msgError('不能对自己进行操作');
    return false
  }
  const socketObj = {
    AgentId: useSocketStore().accountNumber,
    AgentExten: useSocketStore().extensionNumber,
    TargetAgentID: agent.workId,
    Type: operType,
  }
  Send(socketObj)
  
}

// 通过状态过滤坐席
const filteredAgents = computed(() => {
  return agents.value.filter(agent => {
    const matchStatus = !statusFilter.value || agent.status === statusFilter.value;
    const matchSearch = !searchQuery.value ||
      agent.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      agent.workId.toLowerCase().includes(searchQuery.value.toLowerCase());
    return matchStatus && matchSearch;
  });
});

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    online: '空闲',
    idle: '小休',
    offline: '离线',
    calling: '通话中 ',
    afterCall: '话后处理 ',
    unknown: '未上线',
    ringing: '振铃',
  };
  return statusMap[status] || status;
};

const getStatusClass = (status: string) => {
  const statusMap: Record<string, string> = {
    online: 'text-green-600',
    offline: 'text-red-600',
    ringing: 'text-blue-500',
    calling: 'text-blue-600',
    idle: 'text-yellow-600',
    afterCall: 'text-purple-600',
    unknown: 'text-gray-600'
  };
  return statusMap[status] || '';
};

const toggleStatus = (agent: any) => {
  if (agent.extension == useSocketStore().extensionNumber) {
    proxy.$modal.msgError('不能对自己进行操作');
    return false
  }
  const oldStatus = agent.status;
  agent.status = agent.status === 'idle' ? 'online' : 'idle';
  calculatCount(oldStatus, agent.status);
  const operType = agent.status === 'idle' ? 'ForceWorkOff' : 'ForceWorkOn';  
  oparateSeats(agent, operType);
};


// 0离线，1登录中，2空闲，3通话中，4话后处理中，5忙碌，6振铃，7注销
const stateMap = {
  0: 'offline',
  1: 'offline',
  2: 'online',
  3: 'calling',
  4: 'afterCall',
  5: 'idle',
  6: 'ringing',
  7: 'offline',
}


const monitorBack = (data) => {
  // console.log(data, 'monitorBack')
  
  const status = stateMap[data.State]
  if (data.AgentId && status) {
    const info = agents.value.find(item => item.workId === data.AgentId);
    if (!info) return;
    if (status === 'calling') info.time = new Date().getTime()
    else if (info.time) info.time = ''
    const oldStatus = info.status
    // console.log(info.time, status, 'info.time')
    info.status = status

    calculatCount(oldStatus, status)

    // 如果离线把该坐席移到最后，如果是通话中，则把该坐席移到最前面
    if (status === 'offline') {
      agents.value = agents.value.filter(item => item.workId !== data.AgentId)
      agents.value.push(info)
      //   const index = Math.floor(Math.random() * agents.value.length);
      //   agents.value.splice(index, 1);
      // if (status === 'calling')
    } else {
      agents.value = agents.value.filter(item => item.workId !== data.AgentId)
      agents.value.unshift(info)
    }
    // agents.value = shuffle(agents.value)
  }
  
}

const isStartMonitor = ref(false) // 是否开始监控

const startMonitor = () => {
  // console.log(scoketState.value, 'scoketState.value')
  if (scoketState.value !== '签出') {
    isStartMonitor.value = true
    if (!timer.value) {
      timer.value = setInterval(() => {
        agents.value.forEach((agent) => {
          if (agent.status === 'calling' && agent.time) {
            const currentTime = new Date().getTime();
            agent.duration = proxy.getTimeDifference(agent.time, currentTime)
          }
        });
      }, 1000);
    }
    // 所有坐席设置为离线状态
    agents.value.forEach(ele => {
      ele.status = 'offline'
    })

    scoketDatas.value = {
      AgentId: useSocketStore().accountNumber,
      AgentExten: useSocketStore().extensionNumber,
      Type: 'SubScribeOn',
    }
    Send(scoketDatas.value)

  } else {
    proxy.$modal.msgSuccess('当前状态不能监控');
  }

}
// 取消监控
const cancelMonitor = () => {
  isStartMonitor.value = false // 是否开始监控

  clearInterval(timer.value)
  timer.value = null

  scoketDatas.value = {
    AgentId: useSocketStore().accountNumber,
    AgentExten: useSocketStore().extensionNumber,
    Type: 'SubScribeOff',
  }
  Send(scoketDatas.value)
  // 所有坐席设置为未知状态
  agents.value.forEach(ele => {
    ele.status = 'unknown'
  })
  statistics.value.forEach(ele => {
    calculatCount('', ele.key, true)
  })
}

const calculatCount = (oldStata, stateCode, isInit = false) => {
  // console.log(oldStata, stateCode, 'stateCode')
  if (oldStata === stateCode) return;
  const info = statistics.value.find(item => item.key === stateCode);
 
  if (!info) return;
  if (isInit) {
    if (stateCode !== 'offline') info.count = 0
    else info.count = agents.value.length
    return;
  }
  info.count++;
  const oldInfo = statistics.value.find(item => item.key === oldStata);
  if (oldInfo) oldInfo.count--;
  
}

// 页面退出或注销取消定时
onBeforeUnmount(() => {
  if (timer.value) clearInterval(timer.value)
  timer.value = null
})



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
      }
    }
  })
  getAgents()
})

</script>

<style scoped>
/* 1. 声明过渡效果 */
.fade-move,
.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
}

/* 2. 声明进入和离开的状态 */
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: scaleY(0.01) translate(30px, 0);
}

/* 3. 确保离开的项目被移除出了布局流
      以便正确地计算移动时的动画效果。 */
.fade-leave-active {
  position: absolute;
}
.status-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-left: 8px;
}

.status-dot.online {
  background-color: #10B981;
}

.status-dot.offline {
  background-color: #EF4444;
}

.status-dot.calling {
  background-color: #3B82F6;
}

.status-dot.idle {
  background-color: #F59E0B;
}

.status-dot.afterCall {
  background-color: #8B5CF6;
}

:deep(.el-input__wrapper) {
  background-color: #f3f4f6;
  box-shadow: none !important;
}

:deep(.el-input__inner) {
  height: 40px;
}

:deep(.el-dropdown-menu__item) {
  padding: 8px 20px;
}

</style>
