<script setup lang="ts">
/**
 * 用户管理（C 端消费者）— 管理端代为管理
 *
 * 后端契约见 /api/admin/user/**
 * 表单 / 弹窗 / 详情：与 admin 管理页面结构对齐
 */
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete,
  Key,
  View,
  Phone
} from '@element-plus/icons-vue'
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from 'element-plus'
import {
  getUserPageApi,
  getUserDetailApi,
  createUserApi,
  updateUserApi,
  deleteUserApi,
  updateUserStatusApi,
  resetUserPasswordApi,
  getUserOrdersApi
} from '@/api/user'
import type { UserItem, UserSavePayload, UserOrderItem } from '@/api/user'
import { formatDate } from '@/utils/date'
import SearchBar from '@/components/common/SearchBar.vue'

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

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

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

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

// ============================================================
// 启停切换
// ============================================================
async function handleToggleStatus(row: any) {
  await ElMessageBox.confirm(
    `确定要${row.status === 1 ? '禁用' : '启用'}用户【${row.username}】吗？`,
    '提示',
    { type: 'warning' }
  )
  try {
    await updateUserStatusApi(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)

interface FormState {
  id?: number
  username: string
  password: string
  nickname: string
  phone: string
  gender: 0 | 1 | 2
  status: 0 | 1
}
const form = reactive<FormState>({
  username: '',
  password: '',
  nickname: '',
  phone: '',
  gender: 0,
  status: 1
})

const rules = computed<FormRules<FormState>>(() => ({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度 3-50', 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'
    }
  ],
  phone: [
    { pattern: /^$|^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ]
}))

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

async function openEdit(row: any) {
  dialogMode.value = 'edit'
  await nextTick()
  formRef.value?.resetFields()
  try {
    const detail = await getUserDetailApi(row.id)
    Object.assign(form, {
      id: detail.id,
      username: detail.username,
      password: '',
      nickname: detail.nickname ?? '',
      phone: detail.phone ?? '',
      gender: (detail.gender ?? 0) as 0 | 1 | 2,
      status: detail.status
    })
  } catch {
    Object.assign(form, {
      id: row.id,
      username: row.username,
      password: '',
      nickname: row.nickname ?? '',
      phone: row.phone ?? '',
      gender: (row.gender ?? 0) as 0 | 1 | 2,
      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: UserSavePayload = {
        id: form.id,
        username: form.username,
        password: dialogMode.value === 'create' ? form.password : form.password || undefined,
        nickname: form.nickname,
        phone: form.phone,
        gender: form.gender,
        status: form.status
      }
      if (dialogMode.value === 'create') {
        await createUserApi(payload)
        ElMessage.success('新增成功')
      } else {
        await updateUserApi(payload)
        ElMessage.success('更新成功')
      }
      dialogVisible.value = false
      await fetchData()
    } catch {
      /* 拦截器已提示 */
    } finally {
      submitting.value = false
    }
  })
}

// ============================================================
// 重置密码
// ============================================================
const resetDialogVisible = ref(false)
const resetTarget = ref<UserItem | 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) => (val !== resetForm.newPassword ? 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 resetUserPasswordApi(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 deleteUserApi(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch {
    /* 拦截器已提示 */
  }
}

// ============================================================
// 详情弹窗（用户基本信息 + 历史订单）
// ============================================================
const detailDialogVisible = ref(false)
const detailLoading = ref(false)
const detailUser = ref<UserItem | null>(null)
const detailOrders = ref<UserOrderItem[]>([])
const detailOrdersTotal = ref(0)
const detailOrdersQuery = reactive({ current: 1, size: 5 })
const detailOrdersLoading = ref(false)

const GENDER_LABELS = ['未知', '男', '女'] as const
const STATUS_LABELS = ['已禁用', '正常'] as const

async function openDetail(row: any) {
  detailDialogVisible.value = true
  detailLoading.value = true
  detailUser.value = null
  detailOrders.value = []
  detailOrdersQuery.current = 1
  try {
    detailUser.value = await getUserDetailApi(row.id)
  } catch {
    /* 拦截器已提示 */
  } finally {
    detailLoading.value = false
  }
  fetchDetailOrders()
}

async function fetchDetailOrders() {
  if (!detailUser.value) return
  detailOrdersLoading.value = true
  try {
    const res = await getUserOrdersApi(detailUser.value.id, detailOrdersQuery)
    detailOrders.value = res.records
    detailOrdersTotal.value = res.total
  } catch {
    /* 拦截器已提示 */
  } finally {
    detailOrdersLoading.value = false
  }
}

onMounted(fetchData)
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <div>
        <h2>用户管理</h2>
        <p class="page-desc">C 端消费者账号管理与历史订单查询</p>
      </div>
      <el-button 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.status" placeholder="账号状态" clearable style="width: 140px">
          <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="36" :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">
          <template #default="{ row }">
            <span v-if="row.phone">
              <el-icon><Phone /></el-icon> {{ row.phone }}
            </span>
            <span v-else class="muted">—</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" width="80" align="center">
          <template #default="{ row }">
            {{ GENDER_LABELS[row.gender ?? 0] }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <span :class="['status-dot', row.status === 1 ? 'success' : 'danger']">
              {{ STATUS_LABELS[row.status ?? 0] }}
            </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 prop="createTime" label="注册时间" width="180">
          <template #default="{ row }">{{ formatDate(row.createTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="320" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" :icon="View" @click="openDetail(row)">
              详情
            </el-button>
            <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
              link
              :type="row.status === 1 ? 'danger' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 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="480px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.username"
            placeholder="登录用户名（3-50 字符）"
            :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" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="可选" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :value="0">未知</el-radio>
            <el-radio :value="1">男</el-radio>
            <el-radio :value="2">女</el-radio>
          </el-radio-group>
        </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>

    <!-- 详情弹窗：基本信息 + 历史订单 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`用户详情 — ${detailUser?.username ?? ''}`"
      width="780px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div v-loading="detailLoading">
        <template v-if="detailUser">
          <el-descriptions :column="3" border size="default" class="detail-desc">
            <el-descriptions-item label="用户 ID">{{ detailUser.id }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{ detailUser.username }}</el-descriptions-item>
            <el-descriptions-item label="昵称">{{ detailUser.nickname || '—' }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ detailUser.phone || '—' }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ GENDER_LABELS[detailUser.gender ?? 0] }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <span :class="['status-dot', detailUser.status === 1 ? 'success' : 'danger']">
                {{ STATUS_LABELS[detailUser.status ?? 0] }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="最近登录">
              {{ detailUser.lastLoginTime ? formatDate(detailUser.lastLoginTime) : '从未登录' }}
            </el-descriptions-item>
            <el-descriptions-item label="最近登录 IP">{{ detailUser.lastLoginIp || '—' }}</el-descriptions-item>
            <el-descriptions-item label="注册时间">{{ formatDate(detailUser.createTime) }}</el-descriptions-item>
          </el-descriptions>

          <div class="orders-section">
            <div class="orders-header">
              <h4>历史订单</h4>
              <span class="muted">共 {{ detailOrdersTotal }} 单</span>
            </div>
            <el-table v-loading="detailOrdersLoading" :data="detailOrders" stripe size="small" border>
              <el-table-column prop="orderNo" label="订单号" min-width="160" />
              <el-table-column prop="payAmount" label="实付金额" width="100" align="right">
                <template #default="{ row }">¥{{ row.payAmount }}</template>
              </el-table-column>
              <el-table-column label="状态" width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.statusTagType as any" size="small">
                    {{ row.statusText }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="下单时间" width="160" />
              <el-table-column label="支付" width="100">
                <template #default="{ row }">
                  {{ row.payChannelText || '—' }}
                </template>
              </el-table-column>
            </el-table>
            <div class="orders-pagination" v-if="detailOrdersTotal > detailOrdersQuery.size">
              <el-pagination
                v-model:current-page="detailOrdersQuery.current"
                :page-size="detailOrdersQuery.size"
                :total="detailOrdersTotal"
                layout="prev, pager, next"
                small
                @current-change="fetchDetailOrders"
              />
            </div>
          </div>
        </template>
      </div>
    </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;
}
.detail-desc {
  margin-bottom: 24px;
}
.orders-section {
  .orders-header {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    margin-bottom: 12px;
    h4 {
      margin: 0;
      font-size: 15px;
      font-weight: 600;
    }
  }
  .orders-pagination {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
