<template>
  <div class="user-management-container">
    <div class="page-header">
      <h1 class="page-title">用户管理</h1>
      <div class="header-actions">
        <el-button 
          v-if="canManageSync" 
          type="warning" 
          @click="handleSyncWithDingTalk"
          :loading="syncLoading"
        >
          <el-icon class="el-icon--left"><Refresh /></el-icon>
          与钉钉同步
        </el-button>
        <el-button type="primary" @click="createUser">
          <el-icon class="el-icon--left"><Plus /></el-icon>
          新增用户
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="用户名">
          <el-input 
            v-model="filterForm.username" 
            placeholder="搜索用户名或姓名" 
            clearable 
            @input="handleRealTimeSearch"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="filterForm.status" 
            placeholder="全部状态" 
            clearable
            @change="handleRealTimeSearch"
            style="width: 120px"
          >
            <el-option label="已激活" value="active" />
            <el-option label="待激活" value="pending" />
            <el-option label="已禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select 
            v-model="filterForm.role" 
            placeholder="全部角色" 
            clearable
            @change="handleRealTimeSearch"
            style="width: 120px"
          >
            <el-option label="学员" value="trainee" />
            <el-option label="管理者" value="manager" />
            <el-option label="系统管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="岗位">
          <el-select 
            v-model="filterForm.position" 
            placeholder="全部岗位" 
            clearable
            @change="handleRealTimeSearch"
            style="width: 120px"
          >
            <el-option label="销售专员" value="sales" />
            <el-option label="销售主管" value="sales_manager" />
            <el-option label="客服专员" value="service" />
            <el-option label="技术支持" value="tech" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">
            <el-icon class="el-icon--left"><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 当前筛选条件显示 -->
      <div v-if="hasActiveFilters" class="filter-tags">
        <span class="filter-label">当前筛选：</span>
        <el-tag 
          v-if="filterForm.username" 
          closable 
          @close="clearUsername"
          type="primary"
        >
          用户名：{{ filterForm.username }}
        </el-tag>
        <el-tag 
          v-if="filterForm.status" 
          closable 
          @close="clearStatus"
          type="success"
        >
          状态：{{ getStatusText(filterForm.status) }}
        </el-tag>
        <el-tag 
          v-if="filterForm.role" 
          closable 
          @close="clearRole"
          type="warning"
        >
          角色：{{ getRoleText(filterForm.role) }}
        </el-tag>
        <el-tag 
          v-if="filterForm.position" 
          closable 
          @close="clearPosition"
          type="info"
        >
          岗位：{{ getPositionText(filterForm.position) }}
        </el-tag>
        <el-button 
          link 
          type="danger" 
          size="small" 
          @click="handleReset"
          class="clear-all-btn"
        >
          清空全部
        </el-button>
      </div>

      <!-- 搜索结果统计 -->
      <div class="search-result-info">
        <span class="result-count">
          共 <strong>{{ total }}</strong> 个用户
          <span v-if="hasActiveFilters" class="filter-hint">（已筛选）</span>
        </span>
      </div>
    </div>

    <!-- 待激活用户提醒 -->
    <el-alert
      v-if="pendingCount > 0"
      :title="'有 ' + pendingCount + ' 个用户等待激活'"
      type="warning"
      show-icon
      :closable="false"
      style="margin-bottom: 20px"
    >
      <template #default>
        <span>请及时处理待激活用户，为其分配岗位和角色。</span>
        <el-button type="text" size="small" @click="filterPendingUsers">
          查看待激活用户
        </el-button>
      </template>
    </el-alert>

    <!-- 批量操作栏 -->
    <div v-if="selectedUsers.length > 0" class="batch-actions card">
      <span class="selected-info">
        已选择 <strong>{{ selectedUsers.length }}</strong> 个用户
      </span>
      <div class="batch-buttons">
        <el-button type="success" size="small" @click="batchActivate">
          <el-icon><Check /></el-icon>
          批量启用
        </el-button>
        <el-button type="warning" size="small" @click="batchDeactivate">
          <el-icon><Close /></el-icon>
          批量禁用
        </el-button>
        <el-dropdown trigger="click" @command="handleBatchRoleChange">
          <el-button type="primary" size="small">
            批量修改角色<el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="trainee">设为学员</el-dropdown-item>
              <el-dropdown-item command="manager">设为管理者</el-dropdown-item>
              <el-dropdown-item command="admin">设为管理员</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown trigger="click" @command="handleBatchPositionChange">
          <el-button type="info" size="small">
            批量分配岗位<el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item 
                v-for="p in positionOptions" 
                :key="p.id" 
                :command="p.id"
              >
                {{ p.name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="danger" size="small" @click="batchDelete">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button size="small" @click="clearSelection">
          取消选择
        </el-button>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="user-list card">
      <el-table 
        ref="userTableRef"
        :data="filteredUsers" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="realName" label="姓名" min-width="100" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="position" label="岗位" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.position" size="small">
              {{ getPositionText(scope.row.position) }}
            </el-tag>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)" size="small">
              {{ getRoleText(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <template v-if="scope.row.status === 'pending'">
              <el-button link type="primary" size="small" @click="activateUser(scope.row)">
                激活账号
              </el-button>
            </template>
            <template v-else>
              <el-button link type="primary" size="small" @click="editUser(scope.row)">
                编辑
              </el-button>
              <el-button link type="primary" size="small" @click="resetPassword(scope.row)">
                重置密码
              </el-button>
              <el-button 
                link 
                :type="scope.row.status === 'active' ? 'danger' : 'success'" 
                size="small" 
                @click="toggleStatus(scope.row)"
              >
                {{ scope.row.status === 'active' ? '禁用' : '启用' }}
              </el-button>
              <el-dropdown trigger="click" style="margin-left: 12px">
                <el-button link size="small">
                  更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="viewUserDetail(scope.row)">
                      <el-icon><View /></el-icon>
                      查看详情
                    </el-dropdown-item>
                    <el-dropdown-item @click="viewUserLogs(scope.row)">
                      <el-icon><Files /></el-icon>
                      操作日志
                    </el-dropdown-item>
                    <el-dropdown-item @click="deleteUser(scope.row)" divided>
                      <el-icon><Delete /></el-icon>
                      删除用户
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 激活用户弹窗 -->
    <el-dialog
      v-model="activateDialogVisible"
      title="激活用户账号"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="activateFormRef" :model="activateForm" :rules="activateRules" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="activateForm.username" disabled />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="activateForm.realName" disabled />
        </el-form-item>
        <el-form-item label="分配岗位" prop="position">
          <el-select v-model="activateForm.position" placeholder="请选择岗位" style="width: 100%">
            <el-option
              v-for="p in positionOptions"
              :key="p.id"
              :label="p.name"
              :value="p.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分配角色" prop="role">
          <el-select v-model="activateForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="学员" value="trainee" />
            <el-option label="管理者" value="manager" />
            <el-option label="系统管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属团队" prop="team">
          <el-select v-model="activateForm.team" placeholder="请选择团队" style="width: 100%">
            <el-option 
              v-for="t in teamOptions" 
              :key="t.id" 
              :label="t.name" 
              :value="t.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="activateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleActivate" :loading="activateLoading">
            确认激活
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增用户弹窗 -->
    <el-dialog
      v-model="createDialogVisible"
      title="新增用户"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="createFormRef" :model="createForm" :rules="createRules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="createForm.username" placeholder="请输入用户名，3-50个字符" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="createForm.password" type="password" placeholder="请输入密码，至少6位" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="createForm.confirmPassword" type="password" placeholder="请再次输入密码" show-password />
        </el-form-item>
        <el-form-item label="真实姓名" prop="full_name">
          <el-input v-model="createForm.full_name" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="createForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="createForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="createForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="学员" value="trainee" />
            <el-option label="管理者" value="manager" />
            <el-option label="系统管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="岗位" prop="position">
          <el-select v-model="createForm.position" placeholder="请选择岗位" style="width: 100%">
            <el-option
              v-for="p in positionOptions"
              :key="p.id"
              :label="p.name"
              :value="p.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属团队" prop="team">
          <el-select v-model="createForm.team" placeholder="请选择团队" style="width: 100%">
            <el-option 
              v-for="t in teamOptions" 
              :key="t.id" 
              :label="t.name" 
              :value="t.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreate" :loading="createLoading">
            确认创建
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户信息"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="editForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="岗位" prop="position">
          <el-select v-model="editForm.position" placeholder="请选择岗位" style="width: 100%">
            <el-option
              v-for="p in positionOptions"
              :key="p.id"
              :label="p.name"
              :value="p.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="学员" value="trainee" />
            <el-option label="管理者" value="manager" />
            <el-option label="系统管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属团队" prop="team">
          <el-select v-model="editForm.team" placeholder="请选择团队" style="width: 100%">
            <el-option 
              v-for="t in teamOptions" 
              :key="t.id" 
              :label="t.name" 
              :value="t.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEdit" :loading="editLoading">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Refresh, Check, Close, ArrowDown, Delete, Plus, View, Files } from '@element-plus/icons-vue'
import { getUserList, getUserStatistics, resetUserPassword, updateUser, deleteUser as deleteUserApi, addUserToTeamAdmin, removeUserFromTeamAdmin, syncWithDingTalk, batchOperation } from '@/api/admin/user'
import type { ElTable } from 'element-plus'
import { getTeams, getUserDetail as getUserDetailRaw, getUserPositions } from '@/api/user'
import { getPositionList, addPositionMembers, removePositionMember } from '@/api/admin/position'
import { authManager } from '@/utils/auth'

// 加载状态
const loading = ref(false)

// 同步状态
const syncLoading = ref(false)

// 批量选择
const userTableRef = ref<InstanceType<typeof ElTable>>()
const selectedUsers = ref<any[]>([])

// 权限控制：admin 和 manager 可以执行同步
const canManageSync = computed(() => {
  const role = authManager.getUserRole()
  return role && ['admin', 'manager'].includes(role)
})

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 统计数据
const statistics = ref({
  total: 0,
  activeCount: 0,
  pendingCount: 0,
  inactiveCount: 0
})

// 待激活用户数量（动态计算）
const pendingCount = computed(() => statistics.value.pendingCount)

// 筛选表单
const filterForm = reactive({
  username: '',
  status: '',
  role: '',
  position: ''
})

// 激活用户
const activateDialogVisible = ref(false)
const activateFormRef = ref<FormInstance>()
const activateLoading = ref(false)
const activateForm = reactive({
  id: '',
  username: '',
  realName: '',
  position: '',
  role: '',
  team: null as null | number
})

// 新增用户
const createDialogVisible = ref(false)
const createFormRef = ref<FormInstance>()
const createLoading = ref(false)
const createForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  full_name: '',
  email: '',
  phone: '',
  role: 'trainee',
  position: null as null | number,
  team: null as null | number
})

// 编辑用户
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editLoading = ref(false)
const currentEditUserTeamIds = ref<number[]>([])
const currentEditUserPositionIds = ref<number[]>([])
const editForm = reactive({
  id: '',
  username: '',
  realName: '',
  email: '',
  phone: '',
  position: '',
  role: '',
  team: null as null | number
})

// 用户列表数据
const userList = ref<any[]>([])

// 显示的用户数据（直接使用后端返回的数据，不在前端过滤）
const filteredUsers = computed(() => {
  return userList.value
})

// 是否有活跃的筛选条件
const hasActiveFilters = computed(() => {
  return !!(filterForm.username || filterForm.status || filterForm.role || filterForm.position)
})

// 验证规则
const activateRules = reactive<FormRules>({
  position: [
    { required: true, message: '请选择岗位', trigger: 'change' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  team: [{ required: true, message: '请选择团队', trigger: 'change' }]
})
// 团队下拉
const teamOptions = ref<{ id: number; name: string }[]>([])
const positionOptions = ref<{ id: number; name: string }[]>([])
const loadTeams = async () => {
  try {
    const res = await getTeams()
    if (res.code === 200) {
      const arr = Array.isArray((res.data as any)?.items) ? (res.data as any).items : res.data
      teamOptions.value = (arr || []).map((t: any) => ({ id: t.id, name: t.name }))
    }
  } catch (e) {
    console.error('加载团队失败', e)
  }
}
const loadPositions = async () => {
  try {
    const res = await getPositionList({ page: 1, pageSize: 100 })
    if (res.code === 200) {
      const data = res.data || {}
      const items = Array.isArray((data as any).items) ? (data as any).items : (Array.isArray(data) ? data : [])
      positionOptions.value = (items || []).map((p: any) => ({ id: p.id, name: p.name }))
      if (!positionOptions.value.length) {
        // 兜底：再尝试无参请求（部分代理对query兼容性差）
        const res2: any = await getPositionList()
        const d2 = res2?.data || {}
        const it2 = Array.isArray((d2 as any).items) ? (d2 as any).items : (Array.isArray(d2) ? d2 : [])
        positionOptions.value = (it2 || []).map((p: any) => ({ id: p.id, name: p.name }))
      }
    }
  } catch (e) {
    console.error('加载岗位失败', e)
  }
}

// 新增用户验证规则
const createRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度为3-50个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: any, callback: any) => {
        if (value !== createForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  full_name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
})

const editRules = reactive<FormRules>({
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
})

/**
 * 实时搜索处理
 */
const handleRealTimeSearch = () => {
  // 重置到第一页并重新加载数据
  currentPage.value = 1
  loadUserList()
}

/**
 * 重置
 */
const handleReset = () => {
  filterForm.username = ''
  filterForm.status = ''
  filterForm.role = ''
  filterForm.position = ''
  currentPage.value = 1
  loadUserList()
  ElMessage.success('已重置所有筛选条件')
}

/**
 * 清除用户名筛选
 */
const clearUsername = () => {
  filterForm.username = ''
  currentPage.value = 1
  loadUserList()
}

/**
 * 清除状态筛选
 */
const clearStatus = () => {
  filterForm.status = ''
  currentPage.value = 1
  loadUserList()
}

/**
 * 清除角色筛选
 */
const clearRole = () => {
  filterForm.role = ''
  currentPage.value = 1
  loadUserList()
}

/**
 * 清除岗位筛选
 */
const clearPosition = () => {
  filterForm.position = ''
  currentPage.value = 1
  loadUserList()
}

/**
 * 获取状态文本
 */
const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    active: '已激活',
    pending: '待激活',
    disabled: '已禁用'
  }
  return map[status] || '未知'
}

/**
 * 获取角色文本
 */
const getRoleText = (role: string) => {
  const map: Record<string, string> = {
    trainee: '学员',
    manager: '管理者',
    admin: '系统管理员'
  }
  return map[role] || '未知'
}

/**
 * 获取岗位文本
 */
const getPositionText = (position: string | number) => {
  // 如果是数字（岗位ID），尝试从岗位选项中查找名称
  if (typeof position === 'number') {
    const found = positionOptions.value.find(p => p.id === position)
    return found ? found.name : `岗位${position}`
  }
  // 如果是字符串，直接返回（已经是岗位名称）
  return position || '未设置'
}

/**
 * 筛选待激活用户
 */
const filterPendingUsers = () => {
  filterForm.status = 'pending'
  currentPage.value = 1
  loadUserList()
}

/**
 * 新增用户 - 打开弹窗
 */
const createUser = () => {
  // 重置表单
  createForm.username = ''
  createForm.password = ''
  createForm.confirmPassword = ''
  createForm.full_name = ''
  createForm.email = ''
  createForm.phone = ''
  createForm.role = 'trainee'
  createForm.position = null
  createForm.team = null
  // 打开弹窗
  createDialogVisible.value = true
}

/**
 * 确认创建用户
 */
const handleCreate = async () => {
  if (!createFormRef.value) return
  
  await createFormRef.value.validate(async (valid) => {
    if (valid) {
      createLoading.value = true
      
      try {
        // 准备创建用户的数据
        const userData: any = {
          username: createForm.username,
          password: createForm.password,
          full_name: createForm.full_name,
          role: createForm.role
        }
        
        // 可选字段
        if (createForm.email) userData.email = createForm.email
        if (createForm.phone) userData.phone = createForm.phone
        
        // 调用创建用户 API
        const { createUser: createUserApi } = await import('@/api/admin/user')
        const response = await createUserApi(userData)
        
        if (response.code === 200 || response.code === 201) {
          const newUserId = response.data?.id
          
          // 如果选择了团队，添加到团队
          if (createForm.team && newUserId) {
            try {
              const { addUserToTeamAdmin } = await import('@/api/admin/user')
              await addUserToTeamAdmin(newUserId, createForm.team)
            } catch (e) {
              console.warn('添加团队失败', e)
            }
          }
          
          // 如果选择了岗位，添加到岗位
          if (createForm.position && newUserId) {
            try {
              const { addPositionMembers } = await import('@/api/admin/position')
              await addPositionMembers(Number(createForm.position), [newUserId])
            } catch (e) {
              console.warn('添加岗位失败', e)
            }
          }
          
          createDialogVisible.value = false
          ElMessage.success('用户创建成功')
          // 重新加载列表
          loadUserList()
          loadStatistics()
        }
      } catch (error: any) {
        console.error('创建用户失败:', error)
        // 处理后端返回的错误格式（可能是嵌套对象）
        let errorMsg = '创建用户失败'
        const detail = error.response?.data?.detail || error.detail
        if (typeof detail === 'string') {
          errorMsg = detail
        } else if (detail?.message) {
          errorMsg = detail.message
        } else if (error.message) {
          errorMsg = error.message
        }
        ElMessage.error(errorMsg)
      } finally {
        createLoading.value = false
      }
    }
  })
}

/**
 * 激活用户
 */
const activateUser = (user: any) => {
  activateForm.id = user.id
  activateForm.username = user.username
  activateForm.realName = user.realName
  activateForm.position = ''
  activateForm.role = ''
  activateForm.team = null
  activateDialogVisible.value = true
}

/**
 * 确认激活
 */
const handleActivate = async () => {
  if (!activateFormRef.value) return
  
  await activateFormRef.value.validate(async (valid) => {
    if (valid) {
      activateLoading.value = true
      
      try {
        // 调用更新用户 API
        const response = await updateUser(Number(activateForm.id), {
          username: activateForm.username,
          realName: activateForm.realName,
          email: '',
          phone: '',
          position: activateForm.position,
          department: activateForm.team ? String(activateForm.team) : '',
          role: activateForm.role,
          status: 'active'
        })
        
        if (response.code === 200) {
          activateDialogVisible.value = false
          ElMessage.success('用户激活成功')
          // 重新加载数据
          loadUserList()
          loadStatistics()
        }
      } catch (error) {
        console.error('激活用户失败:', error)
        ElMessage.error('激活用户失败')
      } finally {
        activateLoading.value = false
      }
    }
  })
}

/**
 * 编辑用户
 */
const editUser = (user: any) => {
  editForm.id = user.id
  editForm.username = user.username
  editForm.realName = user.realName
  editForm.email = user.email
  editForm.phone = user.phone
  editForm.role = user.role
  // 初始团队和岗位置空，随后加载详情填充
  editForm.team = null
  editForm.position = ''
  currentEditUserTeamIds.value = []
  currentEditUserPositionIds.value = []
  editDialogVisible.value = true

  // 载入真实用户详情，获取团队集合
  getUserDetailRaw(Number(user.id))
    .then(res => {
      if (res && res.code === 200) {
        const teams = res.data?.teams || []
        currentEditUserTeamIds.value = teams.map((t: any) => t.id)
        editForm.team = teams.length > 0 ? teams[0].id : null
      }
    })
    .catch(err => {
      console.error('加载用户详情失败', err)
    })
  
  // 载入用户岗位信息
  getUserPositions(Number(user.id))
    .then(res => {
      if (res && res.code === 200) {
        const positions = Array.isArray(res.data) ? res.data : (Array.isArray((res.data as any)?.items) ? (res.data as any).items : [])
        currentEditUserPositionIds.value = positions.map((p: any) => p.id)
        editForm.position = positions.length > 0 ? positions[0].id : null
      }
    })
    .catch(err => {
      console.error('加载用户岗位失败', err)
    })
}

/**
 * 确认编辑
 */
const handleEdit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      editLoading.value = true
      
      try {
        // 先保存基础信息（不含团队）
        // 仅提交后端可接受字段，且为空值不提交，避免422
        const payload: any = {}
        if (editForm.realName) payload.full_name = editForm.realName
        if (editForm.email) payload.email = editForm.email
        if (editForm.phone) payload.phone = editForm.phone
        if (editForm.role) payload.role = editForm.role
        // 可选：is_active 不在此处修改
        const response = await updateUser(Number(editForm.id), payload)
        
        if (response.code === 200) {
          // 同步团队：移除未选中的既有团队，添加新选择的团队
          const selectedId = editForm.team as number | null
          const toRemove = currentEditUserTeamIds.value.filter(id => id !== selectedId && selectedId !== null)
          // 若选项为空，则移除全部已有关联
          const removeTargets = selectedId === null ? currentEditUserTeamIds.value : toRemove
          for (const tid of removeTargets) {
            try { await removeUserFromTeamAdmin(Number(editForm.id), Number(tid)) } catch (e) { console.warn('移除团队失败', e) }
          }
          if (selectedId !== null && !currentEditUserTeamIds.value.includes(selectedId)) {
            try { await addUserToTeamAdmin(Number(editForm.id), Number(selectedId)) } catch (e) { console.warn('添加团队失败', e) }
          }
          
          // 同步岗位：移除未选中的既有岗位，添加新选择的岗位
          const selectedPositionId = editForm.position ? Number(editForm.position) : null
          const positionsToRemove = currentEditUserPositionIds.value.filter(id => id !== selectedPositionId && selectedPositionId !== null)
          // 若选项为空，则移除全部已有关联
          const removePositionTargets = selectedPositionId === null ? currentEditUserPositionIds.value : positionsToRemove
          for (const pid of removePositionTargets) {
            try { await removePositionMember(Number(pid), Number(editForm.id)) } catch (e) { console.warn('移除岗位失败', e) }
          }
          if (selectedPositionId !== null && !currentEditUserPositionIds.value.includes(selectedPositionId)) {
            try { await addPositionMembers(Number(selectedPositionId), [Number(editForm.id)]) } catch (e) { console.warn('添加岗位失败', e) }
          }
          
          editDialogVisible.value = false
          ElMessage.success('用户信息修改成功')
          loadUserList()
        }
      } catch (error) {
        console.error('编辑用户失败:', error)
        ElMessage.error('编辑用户失败')
      } finally {
        editLoading.value = false
      }
    }
  })
}

/**
 * 重置密码
 */
const resetPassword = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      '确定要重置用户 "' + user.realName + '" 的密码吗？',
      '重置密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用 API 重置密码
    const response = await resetUserPassword(user.id)
    if (response.code === 200) {
      ElMessageBox.alert(
        '密码已重置，临时密码为：<strong>' + response.data.tempPassword + '</strong><br>请复制并告知用户尽快修改密码。<br>密码有效期至：' + response.data.expiresAt,
        '重置成功',
        {
          confirmButtonText: '我已复制',
          dangerouslyUseHTMLString: true
        }
      )
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
      ElMessage.error('重置密码失败')
    }
  }
}

/**
 * 切换状态
 */
const toggleStatus = (user: any) => {
  const action = user.status === 'active' ? '禁用' : '启用'
  ElMessageBox.confirm(
    '确定要' + action + '用户 "' + user.realName + '" 吗？',
    action + '用户',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    user.status = user.status === 'active' ? 'disabled' : 'active'
    ElMessage.success('用户已' + action)
  }).catch(() => {})
}

/**
 * 查看详情
 */
const viewUserDetail = (user: any) => {
  ElMessage.info('查看用户详情：' + user.realName)
}

/**
 * 查看操作日志
 */
const viewUserLogs = (user: any) => {
  ElMessage.info('查看操作日志：' + user.realName)
}

/**
 * 处理表格选择变化
 */
const handleSelectionChange = (selection: any[]) => {
  selectedUsers.value = selection
}

/**
 * 清除选择
 */
const clearSelection = () => {
  userTableRef.value?.clearSelection()
  selectedUsers.value = []
}

/**
 * 批量启用
 */
const batchActivate = async () => {
  if (selectedUsers.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(
      `确定要启用选中的 ${selectedUsers.value.length} 个用户吗？`,
      '批量启用',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    
    const response = await batchOperation({
      ids: selectedUsers.value.map(u => u.id),
      action: 'activate'
    })
    
    if (response.code === 200) {
      ElMessage.success(response.message || '批量启用成功')
      clearSelection()
      loadUserList()
    } else {
      ElMessage.error(response.message || '批量启用失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量启用失败:', error)
      ElMessage.error('批量启用失败')
    }
  }
}

/**
 * 批量禁用
 */
const batchDeactivate = async () => {
  if (selectedUsers.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(
      `确定要禁用选中的 ${selectedUsers.value.length} 个用户吗？`,
      '批量禁用',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    
    const response = await batchOperation({
      ids: selectedUsers.value.map(u => u.id),
      action: 'deactivate'
    })
    
    if (response.code === 200) {
      ElMessage.success(response.message || '批量禁用成功')
      clearSelection()
      loadUserList()
    } else {
      ElMessage.error(response.message || '批量禁用失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量禁用失败:', error)
      ElMessage.error('批量禁用失败')
    }
  }
}

/**
 * 批量修改角色
 */
const handleBatchRoleChange = async (role: string) => {
  if (selectedUsers.value.length === 0) return
  
  const roleNames: Record<string, string> = {
    trainee: '学员',
    manager: '管理者',
    admin: '管理员'
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要将选中的 ${selectedUsers.value.length} 个用户角色修改为"${roleNames[role]}"吗？`,
      '批量修改角色',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    
    const response = await batchOperation({
      ids: selectedUsers.value.map(u => u.id),
      action: 'change_role',
      value: role
    })
    
    if (response.code === 200) {
      ElMessage.success(response.message || '批量修改角色成功')
      clearSelection()
      loadUserList()
    } else {
      ElMessage.error(response.message || '批量修改角色失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量修改角色失败:', error)
      ElMessage.error('批量修改角色失败')
    }
  }
}

/**
 * 批量分配岗位
 */
const handleBatchPositionChange = async (positionId: number) => {
  if (selectedUsers.value.length === 0) return
  
  const position = positionOptions.value.find(p => p.id === positionId)
  
  try {
    await ElMessageBox.confirm(
      `确定要将选中的 ${selectedUsers.value.length} 个用户分配到岗位"${position?.name || positionId}"吗？`,
      '批量分配岗位',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    
    const response = await batchOperation({
      ids: selectedUsers.value.map(u => u.id),
      action: 'assign_position',
      value: positionId
    })
    
    if (response.code === 200) {
      ElMessage.success(response.message || '批量分配岗位成功')
      clearSelection()
      loadUserList()
    } else {
      ElMessage.error(response.message || '批量分配岗位失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量分配岗位失败:', error)
      ElMessage.error('批量分配岗位失败')
    }
  }
}

/**
 * 批量删除
 */
const batchDelete = async () => {
  if (selectedUsers.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？删除后不可恢复。`,
      '批量删除',
      { confirmButtonText: '确定删除', cancelButtonText: '取消', type: 'error' }
    )
    
    const response = await batchOperation({
      ids: selectedUsers.value.map(u => u.id),
      action: 'delete'
    })
    
    if (response.code === 200) {
      ElMessage.success(response.message || '批量删除成功')
      clearSelection()
      loadUserList()
      loadStatistics()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

/**
 * 删除用户
 */
const deleteUser = async (user: any) => {
  // 调试：打印用户对象，确认 id 格式
  console.log('[deleteUser] 用户对象:', user)
  console.log('[deleteUser] user.id:', user.id, '类型:', typeof user.id)
  
  // 确保 id 是数字类型
  const userId = typeof user.id === 'number' ? user.id : parseInt(String(user.id), 10)
  if (isNaN(userId)) {
    console.error('[deleteUser] 无效的用户 ID:', user.id)
    ElMessage.error('无效的用户 ID')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      '确定要删除用户 "' + user.realName + '" 吗？删除后不可恢复。',
      '删除用户',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteUserApi(userId)
    if (response.code === 200) {
      ElMessage.success('用户已删除')
      loadUserList()
      loadStatistics()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}


/**
 * 获取角色标签类型
 */
const getRoleTagType = (role: string) => {
  const typeMap: Record<string, string> = {
    trainee: '',
    manager: 'warning',
    admin: 'danger'
  }
  return typeMap[role] || ''
}

/**
 * 获取状态标签类型
 */
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    active: 'success',
    pending: 'warning',
    disabled: 'info'
  }
  return typeMap[status] || ''
}

/**
 * 分页大小改变
 */
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  loadUserList()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadUserList()
}

/**
 * 加载用户列表
 */
// 与钉钉同步
const handleSyncWithDingTalk = async () => {
  try {
    await ElMessageBox.confirm(
      '将从钉钉同步新入职员工并移除离职员工，但不会修改现有员工的岗位、部门等信息。是否继续？',
      '同步确认',
      {
        confirmButtonText: '确定同步',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    syncLoading.value = true
    const res: any = await syncWithDingTalk()
    
    if (res.success || res.code === 200) {
      const data = res.data
      
      // 构建详细结果消息
      let message = `<div style="text-align: left;">
        <p><strong>同步完成！</strong></p>
        <p>• 新增员工：${data.added_count} 人</p>
        <p>• 删除员工：${data.deleted_count} 人</p>
        <p>• 跳过员工：${data.skipped_count} 人</p>
      `
      
      // 显示新增员工列表
      if (data.added_users && data.added_users.length > 0) {
        message += `<p style="margin-top: 10px;"><strong>新增员工：</strong></p><ul style="margin: 5px 0;">`
        data.added_users.forEach((user: any) => {
          message += `<li>${user.full_name} (${user.phone}) - ${user.role === 'manager' ? '管理者' : '学员'}</li>`
        })
        message += `</ul>`
      }
      
      // 显示删除员工列表
      if (data.deleted_users && data.deleted_users.length > 0) {
        message += `<p style="margin-top: 10px;"><strong>删除员工：</strong></p><ul style="margin: 5px 0;">`
        data.deleted_users.forEach((user: any) => {
          message += `<li>${user.full_name} (${user.phone})</li>`
        })
        message += `</ul>`
      }
      
      // 显示错误信息
      if (data.errors && data.errors.length > 0) {
        message += `<p style="margin-top: 10px; color: #f56c6c;"><strong>错误信息：</strong></p><ul style="margin: 5px 0;">`
        data.errors.forEach((error: string) => {
          message += `<li>${error}</li>`
        })
        message += `</ul>`
      }
      
      message += `<p style="margin-top: 10px; color: #909399;">耗时：${data.duration?.toFixed(2)}秒</p></div>`
      
      ElMessageBox({
        title: '同步结果',
        message: message,
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        type: 'success'
      })
      
      // 刷新用户列表
      await loadUserList()
      await loadStatistics()
    } else {
      ElMessage.error(res.message || '同步失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('同步失败:', error)
      ElMessage.error(error.message || '同步失败，请稍后重试')
    }
  } finally {
    syncLoading.value = false
  }
}

const loadUserList = async () => {
  try {
    loading.value = true
    const params: any = {
      page: currentPage.value,
      pageSize: pageSize.value,  // API层会转换为page_size
      keyword: filterForm.username || undefined,
      role: filterForm.role || undefined,
      status: filterForm.status || undefined  // API层会转换为is_active
    }
    
    const response = await getUserList(params)
    if (response && response.code === 200) {
      const data = response.data || {}
      const items = Array.isArray(data.items) ? data.items : (Array.isArray(data.list) ? data.list : [])
      total.value = typeof data.total === 'number' ? data.total : 0
      // 将后端字段映射为页面使用的字段
      const baseUsers = items.map((u: any) => ({
        id: u.id,
        username: u.username,
        realName: u.full_name || u.realName || '',
        email: u.email || '',
        phone: u.phone || '',
        position: '',
        role: u.role,
        status: u.is_active ? 'active' : 'disabled',
        createTime: u.created_at || u.createTime || ''
      }))
      // 并行加载每个用户的岗位（首屏数量有限，影响可接受）
      const withPositions = await Promise.all(baseUsers.map(async (u: any) => {
        try {
          const r = await getUserPositions(u.id)
          if (r && r.code === 200) {
            const arr = Array.isArray(r.data) ? r.data : (Array.isArray((r.data as any)?.items) ? (r.data as any).items : [])
            // 取第一个岗位名称用于表格展示（后续可改为数组Tag）
            const name = arr[0]?.name || ''
            return { ...u, position: name }
          }
        } catch {}
        return u
      }))
      userList.value = withPositions
    } else {
      userList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 加载统计数据
 */
const loadStatistics = async () => {
  try {
    const response = await getUserStatistics()
    if (response && response.code === 200) {
      statistics.value = response.data || { total: 0, activeCount: 0, pendingCount: 0, inactiveCount: 0 }
    } else {
      statistics.value = { total: 0, activeCount: 0, pendingCount: 0, inactiveCount: 0 }
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadUserList()
  loadStatistics()
  loadTeams()
  loadPositions()
})
</script>

<style lang="scss" scoped>
.user-management-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }

    .el-button {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
    }
  }

  .filter-section {
    margin-bottom: 20px;
    padding: 20px;

    .filter-form {
      .el-form-item {
        margin-bottom: 0;
      }
    }

    .filter-tags {
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 8px;

      .filter-label {
        color: #666;
        font-size: 14px;
        margin-right: 8px;
      }

      .clear-all-btn {
        margin-left: 8px;
      }
    }

    .search-result-info {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid #f0f0f0;

      .result-count {
        color: #666;
        font-size: 14px;

        strong {
          color: #409eff;
          font-weight: 600;
        }
      }

      .filter-hint {
        color: #e6a23c;
        font-size: 12px;
      }
    }
  }

  .batch-actions {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    margin-bottom: 16px;
    background: linear-gradient(135deg, #e8f4fd 0%, #f0f7ff 100%);
    border: 1px solid #b3d8ff;
    border-radius: 8px;

    .selected-info {
      color: #409eff;
      font-size: 14px;

      strong {
        font-size: 18px;
        margin: 0 4px;
      }
    }

    .batch-buttons {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }
  }

  .user-list {
    padding: 24px;

    .text-muted {
      color: #909399;
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 24px;
    }
  }
}

// 响应式
@media (max-width: 768px) {
  .user-management-container {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .el-button {
        width: 100%;
      }
    }

    .filter-form {
      .el-form-item {
        display: block;
        margin-bottom: 16px !important;
      }
    }
  }
}
</style>
