<template>
  <el-dialog v-model="visible" title="选择用户" width="860px" append-to-body @close="handleClose" class="user-selector-dialog">
    <div class="uls-root">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="uls-tabs">
        <!-- ====== 选择用户 ====== -->
        <el-tab-pane name="selectUser">
          <template #label>
            <span class="tab-lbl">
              <svg viewBox="0 0 24 24" width="16" height="16"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" fill="currentColor"/></svg>
              选择用户
            </span>
          </template>

          <!-- 搜索栏 -->
          <div class="uls-search">
            <el-input v-model="searchParams.key" placeholder="搜索用户名 / 邮箱 / ID" clearable @keyup.enter="handleSearch" class="uls-search-input" :prefix-icon="Search" />
            <el-select v-model="searchParams.is_admin" placeholder="全部身份" clearable style="width: 120px" @change="handleSearch">
              <el-option label="管理员" :value="true" />
              <el-option label="普通用户" :value="false" />
            </el-select>
            <el-button type="primary" @click="handleSearch" :icon="Search" circle />
            <el-button @click="handleReset" :icon="Refresh" circle />
          </div>

          <!-- 已选提示 -->
          <transition name="fade">
            <div class="uls-selected-bar" v-if="selectedUser">
              <div class="uls-sel-left">
                <svg viewBox="0 0 24 24" width="16" height="16"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" fill="#67c23a"/></svg>
                <span>已选择：</span>
                <el-avatar :size="24" :src="selectedUser.cover" class="sel-avatar">{{ selectedUser.user_name?.charAt(0)?.toUpperCase() || 'U' }}</el-avatar>
                <b>{{ selectedUser.user_name }}</b>
                <span class="sel-id">#{{ selectedUser.user_id }}</span>
              </div>
              <el-button size="small" link type="danger" @click="selectedUser = null">取消选择</el-button>
            </div>
          </transition>

          <!-- 用户卡片列表 -->
          <div class="uls-grid" v-loading="loading">
            <div
              v-for="user in userList" :key="user.user_id"
              class="uls-card" :class="{ active: selectedUser?.user_id === user.user_id }"
              @click="handleCurrentChange(user)"
            >
              <div class="uls-card-check" v-if="selectedUser?.user_id === user.user_id">
                <svg viewBox="0 0 24 24" width="16" height="16"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" fill="#fff"/></svg>
              </div>
              <el-avatar :size="42" :src="user.cover" class="uls-avatar">{{ user.user_name?.charAt(0)?.toUpperCase() || 'U' }}</el-avatar>
              <div class="uls-card-body">
                <div class="uls-card-name">
                  {{ user.user_name }}
                  <el-tag v-if="user.is_admin" type="warning" size="small" effect="dark" round class="admin-tag">管理员</el-tag>
                </div>
                <div class="uls-card-meta">
                  <span class="meta-id">#{{ user.user_id }}</span>
                  <span v-if="user.email" class="meta-email">{{ user.email }}</span>
                  <span v-if="user.phone" class="meta-phone">{{ user.phone }}</span>
                </div>
              </div>
            </div>
          </div>

          <el-empty v-if="userList.length === 0 && !loading" description="暂无用户数据" :image-size="80" />

          <!-- 分页 -->
          <div class="uls-pagination" v-if="total > 0">
            <el-pagination
              v-model:current-page="searchParams.page"
              v-model:page-size="searchParams.count"
              :page-sizes="[12, 24, 48]"
              :total="total"
              layout="total, sizes, prev, pager, next"
              background small
              @size-change="s => { searchParams.count = s; searchParams.page = 1; fetchUserList() }"
              @current-change="p => { searchParams.page = p; fetchUserList() }"
            />
          </div>
        </el-tab-pane>

        <!-- ====== 添加用户 ====== -->
        <el-tab-pane name="addUser">
          <template #label>
            <span class="tab-lbl">
              <svg viewBox="0 0 24 24" width="16" height="16"><path d="M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm-9-2V7H4v3H1v2h3v3h2v-3h3v-2H6zm9 4c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" fill="currentColor"/></svg>
              添加用户
            </span>
          </template>
          <div class="uls-add-section">
            <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="90px" class="uls-add-form">
              <el-form-item label="用户名" prop="user_name">
                <el-input v-model="addForm.user_name" placeholder="请输入用户名" maxlength="50" show-word-limit />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email" placeholder="请输入邮箱地址" type="email" />
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="addForm.phone" placeholder="请输入手机号（选填）" maxlength="11" />
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password" placeholder="请输入密码" type="password" show-password />
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="addForm.confirmPassword" placeholder="请再次输入密码" type="password" show-password />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleAddUser" :loading="addLoading" :icon="Plus">立即创建</el-button>
                <el-button @click="resetAddForm" :icon="Refresh">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <div class="uls-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="!selectedUser" v-if="activeTab === 'selectUser'">确定选择</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Plus, User } from '@element-plus/icons-vue'
import { getUserList, createTask } from '@/api/admin/user'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  currentUserId: { type: [String, Number], default: '' }
})
const emit = defineEmits(['update:modelValue', 'confirm'])

const visible = ref(false)
const activeTab = ref('selectUser')
const loading = ref(false)
const addLoading = ref(false)
const userList = ref([])
const total = ref(0)
const selectedUser = ref(null)
const addFormRef = ref(null)

const searchParams = reactive({ key: '', is_admin: undefined, page: 1, count: 12 })

const addForm = reactive({ user_name: '', email: '', phone: '', password: '', confirmPassword: '' })
const validateConfirmPassword = (rule, value, callback) => {
  if (!value) callback(new Error('请再次输入密码'))
  else if (value !== addForm.password) callback(new Error('两次输入密码不一致'))
  else callback()
}
const addFormRules = {
  user_name: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { min: 2, max: 50, message: '2-50 个字符', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }, { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, max: 20, message: '6-20 个字符', trigger: 'blur' }],
  confirmPassword: [{ required: true, message: '请确认密码', trigger: 'blur' }, { validator: validateConfirmPassword, trigger: 'blur' }]
}

watch(() => props.modelValue, (v) => {
  visible.value = v
  if (v) { activeTab.value = 'selectUser'; selectedUser.value = null; searchParams.page = 1; fetchUserList() }
})
watch(visible, (v) => emit('update:modelValue', v))

const fetchUserList = async () => {
  loading.value = true; userList.value = []
  try {
    const params = { page: searchParams.page, count: searchParams.count, key: searchParams.key || '' }
    if (searchParams.is_admin !== undefined && searchParams.is_admin !== null && searchParams.is_admin !== '') params.is_admin = searchParams.is_admin
    const res = await getUserList(params)
    if (res.data.code === 200) {
      userList.value = res.data.data?.data || []
      total.value = res.data.data?.all_count || 0
      if (props.currentUserId) { const u = userList.value.find(u => u.user_id === props.currentUserId); if (u) selectedUser.value = u }
    }
  } catch { ElMessage.error('获取用户列表失败') }
  finally { loading.value = false }
}

const handleTabClick = (tab) => { if (tab.paneName === 'selectUser') fetchUserList() }
const handleSearch = () => { searchParams.page = 1; fetchUserList() }
const handleReset = () => { searchParams.key = ''; searchParams.is_admin = undefined; searchParams.page = 1; fetchUserList() }
const handleCurrentChange = (row) => { selectedUser.value = (selectedUser.value?.user_id === row.user_id) ? null : row }
const switchToAdd = () => { activeTab.value = 'addUser' }

const handleAddUser = async () => {
  if (!addFormRef.value) return
  await addFormRef.value.validate(async (valid) => {
    if (!valid) return
    addLoading.value = true
    try {
      const fd = new FormData()
      fd.append('user_name', addForm.user_name); fd.append('email', addForm.email)
      if (addForm.phone) fd.append('phone', addForm.phone)
      fd.append('password', addForm.password)
      const res = await createTask(fd)
      if (res.data.code === 200) {
        ElMessage.success('用户创建成功')
        const newUser = res.data.data
        if (newUser) { selectedUser.value = { user_id: newUser.user_id || newUser.id, user_name: newUser.user_name || addForm.user_name, email: newUser.email || addForm.email, phone: newUser.phone || addForm.phone, ...newUser }; emit('confirm', selectedUser.value); handleClose() }
        else { activeTab.value = 'selectUser'; searchParams.page = 1; await fetchUserList() }
        resetAddForm()
      } else { ElMessage.error(res.data.msg || '创建失败') }
    } catch { ElMessage.error('创建失败') }
    finally { addLoading.value = false }
  })
}

const resetAddForm = () => { Object.assign(addForm, { user_name: '', email: '', phone: '', password: '', confirmPassword: '' }); addFormRef.value?.resetFields() }
const handleClose = () => { visible.value = false; selectedUser.value = null; userList.value = []; searchParams.key = ''; searchParams.is_admin = undefined; searchParams.page = 1; total.value = 0; resetAddForm() }
const handleConfirm = () => { if (selectedUser.value) { emit('confirm', selectedUser.value); handleClose() } else ElMessage.warning('请选择一个用户') }
</script>

<style scoped>
.uls-root { min-height: 460px; }

/* 标签页 */
.tab-lbl { display: inline-flex; align-items: center; gap: 5px; }
:deep(.el-tabs__item) { font-size: 15px; padding: 0 20px; }
:deep(.el-tabs__item.is-active) { font-weight: 600; }

/* 搜索栏 */
.uls-search { display: flex; align-items: center; gap: 8px; margin-bottom: 14px; }
.uls-search-input { flex: 1; max-width: 320px; }

/* 已选提示条 */
.uls-selected-bar { display: flex; align-items: center; justify-content: space-between; padding: 8px 14px; margin-bottom: 12px; background: linear-gradient(135deg, #f0f9eb 0%, #e1f3d8 100%); border: 1px solid #c2e7b0; border-radius: 8px; }
.uls-sel-left { display: flex; align-items: center; gap: 6px; font-size: 13px; color: #1d2129; }
.uls-sel-left b { font-weight: 600; }
.sel-id { color: #86909c; font-size: 12px; }
.sel-avatar { flex-shrink: 0; font-size: 11px; background: linear-gradient(135deg, #67c23a, #85ce61); color: #fff; }

.fade-enter-active, .fade-leave-active { transition: all .25s ease; }
.fade-enter-from, .fade-leave-to { opacity: 0; transform: translateY(-6px); }

/* 卡片网格 */
.uls-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 10px; max-height: 340px; overflow-y: auto; padding: 2px; }

.uls-card { position: relative; display: flex; align-items: center; gap: 12px; padding: 12px 14px; border: 2px solid #ebeef5; border-radius: 10px; cursor: pointer; transition: all .2s ease; background: #fff; }
.uls-card:hover { border-color: #b3d8ff; background: #f5faff; transform: translateY(-1px); box-shadow: 0 4px 12px rgba(64,158,255,.1); }
.uls-card.active { border-color: #409eff; background: #ecf5ff; }

.uls-card-check { position: absolute; top: -1px; right: -1px; width: 24px; height: 24px; background: #409eff; border-radius: 0 8px 0 8px; display: flex; align-items: center; justify-content: center; }

.uls-avatar { flex-shrink: 0; font-size: 16px; font-weight: 700; background: linear-gradient(135deg, #c6e2ff, #409eff); color: #fff; }
.uls-card.active .uls-avatar { background: linear-gradient(135deg, #409eff, #337ecc); }

.uls-card-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.uls-card-name { font-size: 14px; font-weight: 600; color: #1d2129; display: flex; align-items: center; gap: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.admin-tag { transform: scale(.85); transform-origin: left center; }

.uls-card-meta { display: flex; flex-wrap: wrap; gap: 4px 8px; font-size: 11px; color: #a8abb2; line-height: 1.3; }
.meta-id { color: #86909c; font-weight: 500; }
.meta-email, .meta-phone { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 150px; }

/* 分页 */
.uls-pagination { margin-top: 14px; display: flex; justify-content: flex-end; }

/* 添加用户 */
.uls-add-section { padding: 24px 40px; }
.uls-add-form { max-width: 460px; margin: 0 auto; }

/* 底部 */
.uls-footer { display: flex; justify-content: flex-end; gap: 10px; }

/* 滚动条美化 */
.uls-grid::-webkit-scrollbar { width: 5px; }
.uls-grid::-webkit-scrollbar-thumb { background: #dcdfe6; border-radius: 4px; }
.uls-grid::-webkit-scrollbar-thumb:hover { background: #c0c4cc; }
</style>
