<script setup lang="ts">
/**
 * 管理员（后台账号）管理
 *
 * 权限提示：除列表/详情/启停/重置密码外，新建/编辑/删除都要求 super_admin 角色
 * （由后端 @SaCheckRole("super_admin") 拦截）。
 */
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { Search, Refresh, Plus, Edit, Delete, Key } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  getAdminPageApi,
  getAdminDetailApi,
  createAdminApi,
  updateAdminApi,
  deleteAdminApi,
  updateAdminStatusApi,
  resetAdminPasswordApi
} from '@/api/admin'
import type { AdminItem, AdminSavePayload } from '@/api/admin'
import { useUserStore } from '@/stores/modules/user'
import { formatDate } from '@/utils/date'
import SearchBar from '@/components/common/SearchBar.vue'

const userStore = useUserStore()

// ============================================================
// 当前用户角色（决定能否看到「新建/编辑/删除」按钮）
// ============================================================
const isSuperAdmin = computed(() => userStore.role === 'super_admin')

// ============================================================
// 列表
// ============================================================
const loading = ref(false)
const list = ref<AdminItem[]>([])
const total = ref(0)

const query = reactive({
  current: 1,
  size: 10,
  keyword: '',
  role: undefined as string | undefined,
  status: undefined as 0 | 1 | undefined
})

async function fetchData() {
  loading.value = true
  try {
    const res = await getAdminPageApi(query)
    list.value = res.records
    total.value = res.total
  } finally {
    loading.value = false
  }
}

function handleReset() {
  query.keyword = ''
  query.role = undefined
  query.status = undefined
  query.current = 1
  fetchData()
}

// ============================================================
// 启用 / 禁用
// ============================================================
async function handleToggleStatus(row: any) {
  // super_admin 不能被自己禁用/启用（前端防御性拦截）
  if (row.username === 'admin' || row.id === 1) {
    ElMessage.warning('不能变更超级管理员状态')
    return
  }
  await ElMessageBox.confirm(
    `确定要${row.status === 1 ? '禁用' : '启用'}账号【${row.username}】吗？`,
    '提示',
    { type: 'warning' }
  )
  try {
    await updateAdminStatusApi(row.id, row.status === 1 ? 0 : 1)
    ElMessage.success('操作成功')
    fetchData()
  } catch {
    /* 拦截器已提示 */
  }
}

// ============================================================
// 新增 / 编辑（共用弹窗）
// ============================================================
const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const dialogTitle = computed(() => (dialogMode.value === 'edit' ? '编辑管理员' : '新增管理员'))
const formRef = ref<FormInstance>()
const submitting = ref(false)

const ROLE_OPTIONS: { value: AdminItem['role']; label: string }[] = [
  { value: 'super_admin', label: '超级管理员' },
  { value: 'admin', label: '管理员' },
  { value: 'operator', label: '运营/客服' }
]

interface FormState {
  id?: number
  username: string
  password: string
  nickname: string
  email: string
  phone: string
  role: AdminItem['role']
  status: 0 | 1
}
const form = reactive<FormState>({
  username: '',
  password: '',
  nickname: '',
  email: '',
  phone: '',
  role: 'operator',
  status: 1
})

const rules = computed<FormRules<FormState>>(() => ({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 30, message: '用户名长度 3-30', trigger: 'blur' }
  ],
  password: [
    {
      validator: (_r, val, cb) => {
        if (dialogMode.value === 'create' && !val) {
          return cb(new Error('请输入密码'))
        }
        if (val && (val.length < 6 || val.length > 50)) {
          return cb(new Error('密码长度 6-50'))
        }
        cb()
      },
      trigger: 'blur'
    }
  ],
  email: [{ type: 'email', message: '邮箱格式不正确', trigger: 'blur' }],
  phone: [
    {
      pattern: /^$|^1[3-9]\d{9}$/,
      message: '手机号格式不正确',
      trigger: 'blur'
    }
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
}))

async function openCreate() {
  dialogMode.value = 'create'
  await nextTick()
  formRef.value?.resetFields()
  Object.assign(form, {
    id: undefined,
    username: '',
    password: '',
    nickname: '',
    email: '',
    phone: '',
    role: 'operator',
    status: 1
  })
  dialogVisible.value = true
}

async function openEdit(row: any) {
  dialogMode.value = 'edit'
  await nextTick()
  formRef.value?.resetFields()
  // 拉取一次最新数据（防止列表中字段不全）
  try {
    const detail = await getAdminDetailApi(row.id)
    Object.assign(form, {
      id: detail.id,
      username: detail.username,
      password: '', // 编辑时密码留空 = 不修改
      nickname: detail.nickname ?? '',
      email: detail.email ?? '',
      phone: detail.phone ?? '',
      role: detail.role,
      status: detail.status
    })
  } catch {
    // 拉取失败时退回到表格行数据
    Object.assign(form, {
      id: row.id,
      username: row.username,
      password: '',
      nickname: row.nickname ?? '',
      email: row.email ?? '',
      phone: row.phone ?? '',
      role: row.role,
      status: row.status
    })
  }
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitting.value = true
    try {
      const payload: AdminSavePayload = {
        id: form.id,
        username: form.username,
        password: dialogMode.value === 'create' ? form.password : form.password || undefined,
        nickname: form.nickname,
        email: form.email,
        phone: form.phone,
        role: form.role,
        status: form.status
      }
      if (dialogMode.value === 'create') {
        await createAdminApi(payload)
        ElMessage.success('新增成功')
      } else {
        await updateAdminApi(payload)
        ElMessage.success('更新成功')
      }
      dialogVisible.value = false
      await fetchData()
    } catch {
      /* 拦截器已提示 */
    } finally {
      submitting.value = false
    }
  })
}

// ============================================================
// 重置密码
// ============================================================
const resetDialogVisible = ref(false)
const resetTarget = ref<AdminItem | null>(null)
const resetFormRef = ref<FormInstance>()
const resetSubmitting = ref(false)
const resetForm = reactive({ newPassword: '', confirm: '' })

const resetRules: FormRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 50, message: '密码长度 6-50', trigger: 'blur' }
  ],
  confirm: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (_r, val, cb) => {
        if (val !== resetForm.newPassword) return cb(new Error('两次密码不一致'))
        cb()
      },
      trigger: 'blur'
    }
  ]
}

function openReset(row: any) {
  resetTarget.value = row
  resetForm.newPassword = ''
  resetForm.confirm = ''
  resetDialogVisible.value = true
}

async function handleResetSubmit() {
  if (!resetFormRef.value || !resetTarget.value) return
  await resetFormRef.value.validate(async (valid) => {
    if (!valid) return
    resetSubmitting.value = true
    try {
      await resetAdminPasswordApi(resetTarget.value!.id, resetForm.newPassword)
      ElMessage.success(`已重置【${resetTarget.value!.username}】的密码`)
      resetDialogVisible.value = false
    } catch {
      /* 拦截器已提示 */
    } finally {
      resetSubmitting.value = false
    }
  })
}

// ============================================================
// 删除
// ============================================================
async function handleDelete(row: any) {
  await ElMessageBox.confirm(
    `确定要删除管理员【${row.username}】吗？该操作不可恢复。`,
    '提示',
    { type: 'warning' }
  )
  try {
    await deleteAdminApi(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch {
    /* 拦截器已提示 */
  }
}

const ROLE_LABELS: Record<AdminItem['role'], { text: string; type: 'danger' | 'warning' | 'info' }> = {
  super_admin: { text: '超级管理员', type: 'danger' },
  admin: { text: '管理员', type: 'warning' },
  operator: { text: '运营/客服', type: 'info' }
}

onMounted(fetchData)
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <div>
        <h2>管理员管理</h2>
        <p class="page-desc">管理后台账号、角色与权限</p>
      </div>
      <el-button
        v-if="isSuperAdmin"
        type="primary"
        :icon="Plus"
        @click="openCreate"
      >
        新增管理员
      </el-button>
    </div>

    <el-card shadow="never" class="table-card">
      <SearchBar show-divider>
        <el-input
          v-model="query.keyword"
          placeholder="用户名 / 昵称 / 手机号"
          :prefix-icon="Search"
          clearable
          style="width: 240px"
          @keyup.enter="fetchData"
        />
        <el-select v-model="query.role" placeholder="角色" clearable style="width: 140px">
          <el-option v-for="r in ROLE_OPTIONS" :key="r.value" :label="r.label" :value="r.value" />
        </el-select>
        <el-select v-model="query.status" placeholder="状态" clearable style="width: 120px">
          <el-option label="正常" :value="1" />
          <el-option label="已禁用" :value="0" />
        </el-select>
        <el-button type="primary" :icon="Search" @click="fetchData">搜索</el-button>
        <el-button :icon="Refresh" @click="handleReset">重置</el-button>
      </SearchBar>

      <el-table v-loading="loading" :data="list" stripe border>
        <el-table-column type="index" label="#" width="60" align="center" />
        <el-table-column label="账号" min-width="200">
          <template #default="{ row }">
            <div class="user-cell">
              <el-avatar :size="32" :src="row.avatar">{{ row.username.charAt(0) }}</el-avatar>
              <div>
                <div class="username">{{ row.username }}</div>
                <div class="nickname">{{ row.nickname || '—' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="角色" width="140" align="center">
          <template #default="{ row }">
            <el-tag :type="(ROLE_LABELS as any)[row.role]?.type" size="small">
              {{ (ROLE_LABELS as any)[row.role]?.text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" width="140" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <span :class="['status-dot', row.status === 1 ? 'success' : 'danger']">
              {{ row.status === 1 ? '正常' : '已禁用' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="最近登录" width="180">
          <template #default="{ row }">
            <div v-if="row.lastLoginTime">{{ formatDate(row.lastLoginTime) }}</div>
            <div v-else class="muted">从未登录</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" :icon="Edit" @click="openEdit(row)">
              编辑
            </el-button>
            <el-button link type="primary" size="small" :icon="Key" @click="openReset(row)">
              重置密码
            </el-button>
            <el-button
              v-if="isSuperAdmin && row.username !== 'admin' && row.id !== 1"
              link
              :type="row.status === 1 ? 'danger' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              v-if="isSuperAdmin && row.username !== 'admin' && row.id !== 1"
              link
              type="danger"
              size="small"
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="query.current"
          v-model:page-size="query.size"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="fetchData"
          @size-change="fetchData"
        />
      </div>
    </el-card>

    <!-- 新增 / 编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="520px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="90px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.username"
            placeholder="登录用户名（3-30 字符）"
            :disabled="dialogMode === 'edit'"
          />
          <div v-if="dialogMode === 'edit'" class="form-tip">用户名创建后不可修改</div>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            show-password
            :placeholder="dialogMode === 'create' ? '6-50 字符' : '留空表示不修改'"
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="显示用昵称" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="form.role">
            <el-radio v-for="r in ROLE_OPTIONS" :key="r.value" :value="r.value">
              {{ r.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="可选" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="可选" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 重置密码弹窗 -->
    <el-dialog
      v-model="resetDialogVisible"
      title="重置密码"
      width="420px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form ref="resetFormRef" :model="resetForm" :rules="resetRules" label-width="90px">
        <el-form-item label="目标账号">
          <span class="target-text">{{ resetTarget?.username }}（{{ resetTarget?.nickname || '—' }}）</span>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="resetForm.newPassword"
            type="password"
            show-password
            placeholder="6-50 字符"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm">
          <el-input
            v-model="resetForm.confirm"
            type="password"
            show-password
            placeholder="再次输入新密码"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="resetSubmitting" @click="handleResetSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.user-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}
.username {
  font-weight: 500;
  line-height: 1.4;
}
.nickname {
  font-size: 12px;
  color: $color-text-secondary;
  line-height: 1.4;
}
.status-dot {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 10px;
  font-size: 12px;
  &.success {
    background: rgba(16, 185, 129, 0.1);
    color: $color-success;
  }
  &.danger {
    background: rgba(239, 68, 68, 0.1);
    color: $color-danger;
  }
}
.muted {
  color: $color-text-secondary;
  font-size: 12px;
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 16px 20px;
}
.target-text {
  color: $color-text-primary;
  font-weight: 500;
}
.form-tip {
  font-size: 12px;
  color: $color-text-secondary;
  margin-top: 4px;
}
</style>
