<template>
  <el-dialog
    :model-value="visible"
    title="选择用户"
    width="700px"
    class="user-selector-dialog"
    append-to-body
    @update:model-value="handleVisibleChange"
  >
    <div class="user-selector-content">
      <!-- 搜索栏 -->
      <div class="selector-search">
        <el-input
          v-model="searchParams.key"
          placeholder="搜索用户名、邮箱或ID"
          clearable
          @keyup.enter="handleSearch"
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
        <el-button @click="handleReset" class="reset-btn">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </div>

      <!-- 用户表格 -->
      <el-table
        v-loading="loading"
        :data="userList"
        highlight-current-row
        @current-change="handleCurrentChange"
        style="width: 100%"
        max-height="350"
        :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
      >
        <el-table-column prop="user_id" label="用户ID" width="100" />
        <el-table-column prop="user_name" label="用户名" min-width="130">
          <template #default="{ row }">
            <div class="user-name-cell">
              <el-avatar v-if="row.cover" :src="row.cover" :size="28" />
              <el-avatar v-else :size="28">
                {{ row.user_name?.charAt(0)?.toUpperCase() || 'U' }}
              </el-avatar>
              <span class="user-name">{{ row.user_name || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="180">
          <template #default="{ row }">
            <span class="text-ellipsis">{{ row.email || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.disable" type="danger" size="small">禁用</el-tag>
            <el-tag v-else type="success" size="small">正常</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="searchParams.page"
        v-model:page-size="searchParams.count"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        background
        small
        class="selector-pagination"
      />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <span v-if="selectedUser" class="selected-info">
          已选择: <el-tag type="primary" size="small">{{ selectedUser.user_name }} (ID: {{ selectedUser.user_id }})</el-tag>
        </span>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="confirmSelection" :disabled="!selectedUser">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

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

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'select'])

const loading = ref(false)
const userList = ref([])
const total = ref(0)
const selectedUser = ref(null)

const searchParams = reactive({
  key: '',
  page: 1,
  count: 10
})

// 监听 visible 变化，打开时加载数据
watch(() => props.visible, (newVal) => {
  if (newVal) {
    selectedUser.value = null
    fetchUserList()
  }
})

const handleVisibleChange = (val) => {
  emit('update:visible', val)
}

const closeDialog = () => {
  emit('update:visible', false)
}

const fetchUserList = async () => {
  loading.value = true
  try {
    const res = await getUserList(searchParams)
    if (res.data.code === 200) {
      userList.value = res.data.data?.data || []
      total.value = res.data.data?.all_count || 0
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  searchParams.page = 1
  fetchUserList()
}

const handleReset = () => {
  searchParams.key = ''
  searchParams.page = 1
  fetchUserList()
}

const handleCurrentChange = (row) => {
  selectedUser.value = row
}

const handleSizeChange = (size) => {
  searchParams.count = size
  fetchUserList()
}

const handlePageChange = (page) => {
  searchParams.page = page
  fetchUserList()
}

const confirmSelection = () => {
  if (!selectedUser.value) {
    ElMessage.warning('请选择一个用户')
    return
  }
  emit('select', selectedUser.value)
  closeDialog()
}
</script>

<style scoped>
.user-selector-content {
  max-height: 500px;
  overflow: hidden;
}

.selector-search {
  display: flex;
  align-items: center;
  gap: 12px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 16px;
}

.search-input {
  flex: 1;
  max-width: 350px;
}

.reset-btn {
  flex-shrink: 0;
}

.user-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-weight: 500;
  color: #303133;
}

.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.selector-pagination {
  margin-top: 16px;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
}

.selected-info {
  margin-right: auto;
  color: #606266;
  font-size: 13px;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row):hover {
  background-color: #f5f7fa;
}

:deep(.current-row) {
  background-color: var(--el-color-primary-light-9) !important;
}

:deep(.current-row td) {
  color: var(--el-color-primary);
}

:deep(.el-avatar) {
  background-color: var(--el-color-primary-light-5);
  color: #fff;
  font-size: 12px;
}
</style>
