<script setup lang="ts">
import { ArrowDown } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'

import AdminPageHeader from '@/components/admin/AdminPageHeader.vue'
import AdminStatusTag from '@/components/admin/AdminStatusTag.vue'
import { isFeedbackDismissed, showConfirm, showError, showPrompt, showSuccess } from '@/lib/feedback'
import {
  createAdminUser,
  fetchAdminUsers,
  resetAdminUserPassword,
  updateAdminUserInventoryGroups,
  updateAdminUserRole,
  updateAdminUserStatus,
} from '@/services/admin'
import type { AdminPagination, AdminRole, AdminUserListItem } from '@/types/admin'
import { getAdminUserId, hasAdminRole } from '@/utils/admin-auth'
import { adminUserRoleOptions, adminUserStatusOptions } from '@/utils/admin-options'
import { formatAdminDateTime } from '@/utils/admin-time'

const loading = ref(true)
const creating = ref(false)
const actionLoadingId = ref<number | null>(null)
const errorMessage = ref('')
const username = ref('')
const role = ref('')
const status = ref('')
const createUsername = ref('')
const createPassword = ref('')
const createRole = ref<AdminRole>('operator')
const items = ref<AdminUserListItem[]>([])
const pagination = ref<AdminPagination>({ page: 1, pageSize: 20, total: 0 })

function isCurrentUser(userId: number) { return getAdminUserId() === userId }

function formatRoleLabel(role: AdminRole) {
  if (role === 'admin') return '管理员'
  if (role === 'support') return '客服'
  return '普通运营'
}

function formatInventoryGroups(item: AdminUserListItem) {
  if (item.role !== 'support') return ['不限库存组']
  if (item.inventoryGroupCodes.length === 0) return ['未绑定']
  return item.inventoryGroupCodes
}

async function loadUsers(page = pagination.value.page) {
  if (!hasAdminRole('admin')) { loading.value = false; return }
  loading.value = true; errorMessage.value = ''
  try {
    const response = await fetchAdminUsers({ page, pageSize: pagination.value.pageSize, username: username.value.trim(), role: role.value.trim(), status: status.value.trim() })
    items.value = response.data.items; pagination.value = response.data.pagination
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : '读取后台用户失败'
  } finally { loading.value = false }
}

async function submitCreate() {
  if (!createUsername.value.trim() || !createPassword.value.trim()) { showError('请填写账号和密码'); return }
  creating.value = true
  try {
    await createAdminUser({ username: createUsername.value.trim(), password: createPassword.value.trim(), role: createRole.value, status: 'active' })
    showSuccess('后台用户已创建'); createUsername.value = ''; createPassword.value = ''; createRole.value = 'operator'
    await loadUsers(1)
  } catch (error) { showError(error instanceof Error ? error.message : '创建后台用户失败') }
  finally { creating.value = false }
}

async function updateRole(item: AdminUserListItem, nextRole: AdminRole) {
  if (item.role === nextRole) return
  try { await showConfirm(`确认将 ${item.username} 调整为${formatRoleLabel(nextRole)}吗？`, '确认操作', { type: 'warning', confirmButtonText: '继续执行', cancelButtonText: '取消' }) } catch { return }
  actionLoadingId.value = item.userId
  try { await updateAdminUserRole(item.userId, { role: nextRole }); showSuccess('用户角色已更新'); await loadUsers() }
  catch (error) { showError(error instanceof Error ? error.message : '更新用户角色失败') }
  finally { actionLoadingId.value = null }
}

async function toggleStatus(item: AdminUserListItem) {
  const nextStatus = item.status === 'active' ? 'disabled' : 'active'
  try { await showConfirm(`确认将 ${item.username}${nextStatus === 'active' ? '启用' : '停用'}吗？`, '确认操作', { type: nextStatus === 'active' ? 'info' : 'warning', confirmButtonText: '继续执行', cancelButtonText: '取消' }) } catch { return }
  actionLoadingId.value = item.userId
  try { await updateAdminUserStatus(item.userId, { status: nextStatus }); showSuccess('用户状态已更新'); await loadUsers() }
  catch (error) { showError(error instanceof Error ? error.message : '更新用户状态失败') }
  finally { actionLoadingId.value = null }
}

async function promptResetPassword(item: AdminUserListItem) {
  try {
    const result = await showPrompt(`请输入 ${item.username} 的新密码`, '重置密码', { inputType: 'password', inputPlaceholder: '至少 8 位', confirmButtonText: '提交', cancelButtonText: '取消', inputValidator: (value) => value.trim().length >= 8 || '密码至少 8 位' })
    actionLoadingId.value = item.userId
    await resetAdminUserPassword(item.userId, { password: result.value.trim() }); showSuccess('用户密码已重置'); await loadUsers()
  } catch (error) { if (isFeedbackDismissed(error)) return; showError(error instanceof Error ? error.message : '重置密码失败') }
  finally { actionLoadingId.value = null }
}

async function promptUpdateInventoryGroups(item: AdminUserListItem) {
  if (item.role !== 'support') { showError('仅客服账号需要绑定库存组'); return }
  try {
    const result = await showPrompt(`请输入 ${item.username} 可用的库存组，多个组用英文逗号分隔`, '配置库存组', { inputType: 'text', inputValue: item.inventoryGroupCodes.join(','), inputPlaceholder: '例如 A组,B组,售后组', confirmButtonText: '保存', cancelButtonText: '取消' })
    const inventoryGroupCodes = String(result.value || '').split(',').map((v) => v.trim()).filter(Boolean)
    actionLoadingId.value = item.userId
    await updateAdminUserInventoryGroups(item.userId, { inventoryGroupCodes }); showSuccess('用户库存组已更新'); await loadUsers()
  } catch (error) { if (isFeedbackDismissed(error)) return; showError(error instanceof Error ? error.message : '更新库存组失败') }
  finally { actionLoadingId.value = null }
}

onMounted(loadUsers)
</script>

<template>
  <div class="users-page">
    <AdminPageHeader title="后台用户" description="管理员可维护后台账号、角色和启停状态，避免继续使用单一口令。" />

    <el-result v-if="!hasAdminRole('admin')" icon="warning" title="仅管理员可以访问用户管理。" />

    <template v-else>
      <!-- 筛选 + 创建 -->
      <el-card shadow="never" class="filter-card" style="margin-top: 16px">
        <div class="filter-row">
          <el-input v-model="username" placeholder="账号筛选" clearable style="width: 140px" @keyup.enter="loadUsers(1)" />
          <el-select v-model="role" placeholder="角色" clearable style="width: 120px">
            <el-option v-for="opt in adminUserRoleOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
          <el-select v-model="status" placeholder="状态" clearable style="width: 120px">
            <el-option v-for="opt in adminUserStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
          <el-button @click="loadUsers(1)">查询列表</el-button>
        </div>
        <el-divider />
        <div class="filter-row">
          <el-input v-model="createUsername" placeholder="新账号" style="width: 140px" />
          <el-input v-model="createPassword" type="password" show-password placeholder="新密码，至少 8 位" style="width: 180px" />
          <el-select v-model="createRole" style="width: 120px">
            <el-option value="operator" label="普通运营" />
            <el-option value="support" label="客服" />
            <el-option value="admin" label="管理员" />
          </el-select>
          <el-button :loading="creating" type="primary" @click="submitCreate">新增用户</el-button>
        </div>
      </el-card>

      <el-alert v-if="errorMessage" :title="errorMessage" type="error" show-icon :closable="false" style="margin-top: 16px" />

      <el-card shadow="never" class="users-table-card" style="margin-top: 16px">
        <el-table :data="items" stripe size="small" v-loading="loading" element-loading-text="用户列表加载中" class="users-table" style="width: 100%">
          <el-table-column prop="userId" label="ID" width="52" align="center" />
          <el-table-column prop="username" label="账号" width="112" show-overflow-tooltip />
          <el-table-column label="角色" width="82">
            <template #default="{ row }">{{ formatRoleLabel(row.role) }}</template>
          </el-table-column>
          <el-table-column label="库存组" width="112">
            <template #default="{ row }">
              <div class="inventory-tags">
                <el-tag v-for="(code, i) in formatInventoryGroups(row)" :key="i" size="small" :type="(code === '未绑定' || code === '不限库存组') ? 'info' : undefined">{{ code }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="128">
            <template #default="{ row }"><AdminStatusTag :status="row.status" /></template>
          </el-table-column>
          <el-table-column label="创建时间" width="154">
            <template #default="{ row }"><span class="date-cell">{{ formatAdminDateTime(row.createdAt) }}</span></template>
          </el-table-column>
          <el-table-column label="更新时间" width="154">
            <template #default="{ row }"><span class="date-cell">{{ formatAdminDateTime(row.updatedAt) }}</span></template>
          </el-table-column>
          <el-table-column label="操作" min-width="356">
            <template #default="{ row }">
              <div class="action-stack">
                <el-dropdown trigger="click" :disabled="isCurrentUser(row.userId)" @command="(cmd: string) => updateRole(row, cmd as AdminRole)">
                  <el-button :loading="actionLoadingId === row.userId" size="small" :disabled="isCurrentUser(row.userId)">
                    改角色<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="admin" :disabled="row.role === 'admin'">设为管理员</el-dropdown-item>
                      <el-dropdown-item command="operator" :disabled="row.role === 'operator'">设为运营</el-dropdown-item>
                      <el-dropdown-item command="support" :disabled="row.role === 'support'">设为客服</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-button :loading="actionLoadingId === row.userId" size="small" :disabled="isCurrentUser(row.userId)" @click="toggleStatus(row)">{{ row.status === 'active' ? '停用' : '启用' }}</el-button>
                <el-button :loading="actionLoadingId === row.userId" size="small" :disabled="row.role !== 'support'" @click="promptUpdateInventoryGroups(row)">配库存组</el-button>
                <el-button :loading="actionLoadingId === row.userId" size="small" type="primary" @click="promptResetPassword(row)">重置密码</el-button>
                <el-tag v-if="isCurrentUser(row.userId)" size="small" type="info">当前账号</el-tag>
              </div>
            </template>
          </el-table-column>
          <template #empty><el-empty :image-size="60" description="暂无用户" /></template>
        </el-table>
        <el-pagination
          v-if="pagination.total > 0"
          v-model:current-page="pagination.page"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          layout="total, prev, pager, next"
          style="margin-top: 16px; justify-content: center"
          @current-change="loadUsers"
        />
      </el-card>
    </template>
  </div>
</template>

<style scoped>
.users-page { display: grid; gap: 0; }
.filter-row { display: flex; gap: var(--space-3); align-items: center; flex-wrap: wrap; }
.users-table-card { overflow: visible; }
.users-table { width: 100%; }
.inventory-tags { display: flex; gap: 4px; align-items: center; white-space: nowrap; }
.inventory-tags :deep(.el-tag) { flex: 0 0 auto; }
.date-cell { display: inline-block; white-space: nowrap; font-size: var(--text-xs); }
.action-stack { display: flex; flex-wrap: nowrap; gap: 6px; align-items: center; white-space: nowrap; }
.action-stack :deep(.el-button) { flex: 0 0 auto; margin-left: 0; padding: 5px 8px; }
.action-stack :deep(.el-tag) { flex: 0 0 auto; padding: 0 7px; }
.action-stack :deep(.el-icon--right) { margin-left: 4px; }
</style>
