<!--
=============================================================================
企微IT智能服务台 — 坐席人员管理页
=============================================================================
说明：管理坐席人员，功能包括：
  - 表格列表显示所有坐席信息
  - 按状态筛选（全部/在线/忙碌/离线）
  - 编辑坐席对话框（角色、技能标签、最大负载）
  - 添加坐席对话框（user_id、name、技能标签等）
  - 移除坐席确认
-->
<template>
  <div class="agents-page">
    <!-- 页面标题 -->
    <div class="page-title">坐席人员管理</div>
    <div class="page-desc">坐席状态、技能标签、权限分级管理。技能标签与快速回复7大类对齐。</div>

    <!-- 顶部操作栏 -->
    <div class="agents-toolbar">
      <!-- 状态筛选标签 -->
      <div class="category-tabs">
        <el-button
          v-for="tab in statusTabs"
          :key="tab.value"
          :type="agentStore.filterStatus === tab.value ? 'primary' : 'default'"
          size="small"
          @click="agentStore.setFilter(tab.value)"
        >
          {{ tab.label }} ({{ agentStore.statusCounts[tab.value] }})
        </el-button>
      </div>

      <!-- 添加坐席按钮 -->
      <el-button type="primary" @click="openAddDialog">
        <el-icon><Plus /></el-icon>
        添加坐席
      </el-button>
    </div>

    <!-- 坐席表格 -->
    <AgentTable
      :agents="agentStore.filteredAgents"
      :loading="agentStore.loading"
      @edit="openEditDialog"
      @delete="handleDelete"
    />

    <!-- ================================================================ -->
    <!-- 编辑坐席对话框 -->
    <!-- ================================================================ -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑坐席"
      width="480px"
      destroy-on-close
    >
      <el-form v-if="editingAgent" label-position="top">
        <el-form-item label="姓名">
          <el-input :model-value="editingAgent.name" disabled />
        </el-form-item>

        <el-form-item label="角色">
          <el-radio-group v-model="editForm.role">
            <el-radio value="agent">坐席</el-radio>
            <el-radio value="admin">组长</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="技能标签">
          <el-checkbox-group v-model="editForm.skillTags">
            <el-checkbox
              v-for="tag in skillTagOptions"
              :key="tag"
              :value="tag"
              :label="tag"
            />
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="最大负载">
          <el-input-number
            v-model="editForm.maxLoad"
            :min="1"
            :max="20"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="OTP二次验证">
          <div v-if="editingAgent?.otp_enabled === 1">
            <el-tag type="success">已启用</el-tag>
            <el-button size="small" type="danger" style="margin-left: 12px;" @click="handleUnbindOtp">
              强制解绑
            </el-button>
          </div>
          <div v-else-if="editingAgent?.otp_secret">
            <el-tag type="warning">已绑定(未验证)</el-tag>
            <el-button size="small" type="danger" style="margin-left: 12px;" @click="handleUnbindOtp">
              强制解绑
            </el-button>
          </div>
          <el-tag v-else type="info">未绑定</el-tag>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- ================================================================ -->
    <!-- 添加坐席对话框 -->
    <!-- ================================================================ -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加坐席"
      width="480px"
      destroy-on-close
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-position="top"
      >
        <el-form-item label="企微用户ID" prop="userId">
          <el-input v-model="addForm.userId" placeholder="如 WangLi" />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name" placeholder="如 王丽" />
        </el-form-item>

        <el-form-item label="角色">
          <el-radio-group v-model="addForm.role">
            <el-radio value="agent">坐席</el-radio>
            <el-radio value="admin">组长</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="技能标签">
          <el-checkbox-group v-model="addForm.skillTags">
            <el-checkbox
              v-for="tag in skillTagOptions"
              :key="tag"
              :value="tag"
              :label="tag"
            />
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="最大负载">
          <el-input-number
            v-model="addForm.maxLoad"
            :min="1"
            :max="20"
            controls-position="right"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSave">确认添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// ==========================================================================
// 依赖导入
// ==========================================================================
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import AgentTable from '@/components/AgentTable.vue'
import { useAgentStore } from '@/stores/agent'
import { unbindOtp as unbindOtpApi } from '@/api/admin'
import type { Agent, AgentFilterStatus } from '@/types'
import { SKILL_TAGS } from '@/types'

// ==========================================================================
// Store
// ==========================================================================
const agentStore = useAgentStore()

// ==========================================================================
// 状态筛选标签
// ==========================================================================
const statusTabs: Array<{ label: string; value: AgentFilterStatus }> = [
  { label: '全部', value: 'all' },
  { label: '在线', value: 'online' },
  { label: '忙碌', value: 'busy' },
  { label: '离线', value: 'offline' },
]

// ==========================================================================
// 技能标签选项
// ==========================================================================
const skillTagOptions = [...SKILL_TAGS]

// ==========================================================================
// 编辑对话框
// ==========================================================================
const editDialogVisible = ref<boolean>(false)
const editingAgent = ref<Agent | null>(null)
const editForm = reactive({
  role: 'agent' as string,
  skillTags: [] as string[],
  maxLoad: 5,
})

/** 打开编辑对话框 */
function openEditDialog(agent: Agent): void {
  editingAgent.value = agent
  editForm.role = agent.role
  editForm.skillTags = [...agent.skill_tags]
  editForm.maxLoad = agent.max_load
  editDialogVisible.value = true
}

/** 保存编辑 */
async function handleEditSave(): Promise<void> {
  if (!editingAgent.value) return
  const success = await agentStore.editAgent(editingAgent.value.id, {
    role: editForm.role as Agent['role'],
    skill_tags: editForm.skillTags,
    max_load: editForm.maxLoad,
  })
  if (success) {
    ElMessage.success('坐席信息已更新')
    editDialogVisible.value = false
  } else {
    ElMessage.error('更新失败')
  }
}

/**
 * 强制解绑OTP
 */
async function handleUnbindOtp(): Promise<void> {
  if (!editingAgent.value) return
  try {
    await ElMessageBox.confirm(
      `确定要强制解绑 ${editingAgent.value.name} 的OTP吗？`,
      '提示',
      { confirmButtonText: '确定解绑', cancelButtonText: '取消', type: 'warning' }
    )
    await unbindOtpApi(editingAgent.value.id)
    ElMessage.success('OTP已解绑')
    // 刷新列表
    await agentStore.loadAgents()
    editDialogVisible.value = false
  } catch (error) {
    if ((error as Error)?.message?.includes('cancel')) {
      // 用户取消
    } else {
      console.error('解绑OTP失败:', error)
      ElMessage.error('解绑OTP失败')
    }
  }
}

// ==========================================================================
// 添加对话框
// ==========================================================================
const addDialogVisible = ref<boolean>(false)
const addFormRef = ref<FormInstance>()
const addForm = reactive({
  userId: '',
  name: '',
  role: 'agent' as string,
  skillTags: [] as string[],
  maxLoad: 5,
})

const addFormRules: FormRules = {
  userId: [{ required: true, message: '请输入企微用户ID', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
}

/** 打开添加对话框 */
function openAddDialog(): void {
  addForm.userId = ''
  addForm.name = ''
  addForm.role = 'agent'
  addForm.skillTags = []
  addForm.maxLoad = 5
  addDialogVisible.value = true
}

/** 保存添加 */
async function handleAddSave(): Promise<void> {
  const valid = await addFormRef.value?.validate().catch(() => false)
  if (!valid) return

  const success = await agentStore.addAgent({
    user_id: addForm.userId.trim(),
    name: addForm.name.trim(),
    role: addForm.role as Agent['role'],
    skill_tags: addForm.skillTags,
    max_load: addForm.maxLoad,
  })
  if (success) {
    ElMessage.success('坐席已添加')
    addDialogVisible.value = false
  } else {
    ElMessage.error('添加失败')
  }
}

// ==========================================================================
// 删除坐席
// ==========================================================================
function handleDelete(agent: Agent): void {
  ElMessageBox.confirm(
    `确定要移除坐席「${agent.name}」吗？`,
    '移除坐席',
    {
      confirmButtonText: '确定移除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const success = await agentStore.removeAgent(agent.id)
    if (success) {
      ElMessage.success('坐席已移除')
    }
  }).catch(() => {
    // 取消删除
  })
}

// ==========================================================================
// 初始化
// ==========================================================================
onMounted(() => {
  agentStore.loadAgents()
})
</script>

<style scoped>
/* 顶部操作栏 */
.agents-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 分类标签 */
.category-tabs {
  display: flex;
  gap: 8px;
}
</style>
