<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchSupportAdmins, transferChat, type SupportAdmin } from '@/features/chats'
import { User } from '@element-plus/icons-vue'

const props = defineProps<{
  modelValue: boolean
  conversationId: number
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

const visible = ref(false)
const loading = ref(false)
const submitting = ref(false)
const admins = ref<SupportAdmin[]>([])
const selectedAdminId = ref<number | null>(null)

// 按在线状态和会话数排序：在线客服优先，会话数少的优先
const sortedAdmins = computed(() => {
  return [...admins.value].sort((a, b) => {
    // 在线状态优先级：online > busy > offline
    const statusPriority: Record<string, number> = { online: 0, busy: 1, offline: 2 }
    const aPriority = statusPriority[a.support_status] ?? 2
    const bPriority = statusPriority[b.support_status] ?? 2
    if (aPriority !== bPriority) return aPriority - bPriority
    // 同状态下按会话数排序
    return a.chat_count - b.chat_count
  })
})

function getSupportStatusLabel(status: string) {
  const labels: Record<string, string> = {
    online: '在线',
    offline: '离线',
    busy: '忙碌',
  }
  return labels[status] || '未知'
}

function getSupportStatusColor(status: string) {
  const colors: Record<string, string> = {
    online: '#10b981',
    offline: '#9ca3af',
    busy: '#f59e0b',
  }
  return colors[status] || '#9ca3af'
}

watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    loadAdmins()
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

async function loadAdmins() {
  loading.value = true
  try {
    admins.value = await fetchSupportAdmins()
  } catch {
    ElMessage.error('加载客服列表失败')
  } finally {
    loading.value = false
  }
}

async function handleSubmit() {
  if (!selectedAdminId.value) {
    ElMessage.warning('请选择目标客服')
    return
  }
  submitting.value = true
  try {
    await transferChat(props.conversationId, selectedAdminId.value)
    ElMessage.success('转接成功')
    visible.value = false
    emit('success')
  } catch {
    ElMessage.error('转接失败')
  } finally {
    submitting.value = false
  }
}

function getStatusTag(count: number) {
  if (count === 0) return { text: '空闲', type: 'success' }
  if (count <= 3) return { text: '正常', type: '' }
  return { text: '繁忙', type: 'warning' }
}
</script>

<template>
  <el-dialog v-model="visible" title="转接会话" width="480px">
    <div v-loading="loading" class="transfer-content">
      <p class="tip">选择要转接给的客服：</p>
      <el-radio-group v-model="selectedAdminId" class="admin-list">
        <el-radio
          v-for="admin in sortedAdmins"
          :key="admin.id"
          :value="admin.id"
          class="admin-item"
        >
          <div class="admin-info">
            <div class="admin-avatar-wrap">
              <el-avatar :size="36" :icon="User" />
              <span class="status-indicator" :style="{ backgroundColor: getSupportStatusColor(admin.support_status) }"></span>
            </div>
            <div class="admin-detail">
              <span class="admin-name">{{ admin.nickname }}</span>
              <span class="admin-id">ID: {{ admin.id }}</span>
            </div>
          </div>
          <div class="admin-status">
            <span class="support-status" :style="{ color: getSupportStatusColor(admin.support_status) }">
              {{ getSupportStatusLabel(admin.support_status) }}
            </span>
            <span class="admin-count">{{ admin.chat_count }} 个会话</span>
          </div>
        </el-radio>
      </el-radio-group>
      <el-empty v-if="!loading && admins.length === 0" description="暂无可用客服" />
    </div>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="submitting" :disabled="!selectedAdminId" @click="handleSubmit">
        确认转接
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.transfer-content {
  min-height: 100px;
}

.tip {
  margin: 0 0 16px;
  color: #6b7280;
  font-size: 14px;
}

.admin-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.admin-item {
  display: flex;
  align-items: center;
  gap: 12px;
  height: auto;
  padding: 12px 16px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  margin-right: 0;
  width: 100%;
}

.admin-item :deep(.el-radio__label) {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-width: 0;
}

.admin-item.is-checked {
  border-color: #409eff;
  background: #ecf5ff;
}

.admin-info {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}

.admin-avatar-wrap {
  position: relative;
  flex-shrink: 0;
}

.status-indicator {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  border: 2px solid #fff;
}

.admin-detail {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
}

.admin-name {
  font-weight: 500;
  font-size: 14px;
  color: #111827;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.admin-id {
  color: #9ca3af;
  font-size: 12px;
}

.admin-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
  flex-shrink: 0;
}

.support-status {
  font-size: 13px;
  font-weight: 600;
}

.admin-count {
  color: #9ca3af;
  font-size: 12px;
}
</style>
