<template>
  <el-dialog
    v-model="visible"
    title="选择用户"
    width="900px"
    append-to-body
    @close="handleClose"
  >
    <div class="user-selector">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <!-- 选择用户 -->
        <el-tab-pane label="选择用户" name="selectUser">
          <div class="user-list-container">
            <!-- 搜索筛选区域 -->
            <div class="filter-section">
              <el-form :inline="true" :model="searchParams" class="search-form">
                <el-form-item label="关键词">
                  <el-input
                    v-model="searchParams.key"
                    placeholder="搜索用户名或ID"
                    clearable
                    @keyup.enter="handleSearch"
                    style="width: 200px"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="用户状态">
                  <el-select
                    v-model="searchParams.status"
                    placeholder="全部状态"
                    clearable
                    style="width: 120px"
                  >
                    <el-option label="正常" value="1" />
                    <el-option label="禁用" value="0" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSearch" :icon="Search">
                    搜索
                  </el-button>
                  <el-button @click="handleReset" :icon="Refresh">
                    重置
                  </el-button>
                  <el-button type="success" @click="switchToAdd" :icon="Plus">
                    添加新用户
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 用户列表表格 -->
            <el-table
              v-loading="loading"
              :data="userList"
              highlight-current-row
              @current-change="handleCurrentChange"
              style="width: 100%"
              :height="350"
              :row-class-name="tableRowClassName"
            >
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column prop="user_id" label="用户ID" width="100" align="center" />
              <el-table-column prop="user_name" label="用户名" min-width="120">
                <template #default="{ row }">
                  <div class="user-info-cell">
                    <el-avatar :size="32" :src="row.cover">
                      <el-icon><User /></el-icon>
                    </el-avatar>
                    <span class="user-name">{{ row.user_name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
              <el-table-column prop="phone" label="手机号" width="130" show-overflow-tooltip />
              <!-- <el-table-column prop="status" label="状态" width="80" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                    {{ row.status === 1 ? '正常' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column> -->
              <el-table-column prop="created_at" label="注册时间" width="160" show-overflow-tooltip />
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container" v-if="total > 0">
              <el-pagination
                v-model:current-page="searchParams.page"
                v-model:page-size="searchParams.count"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                background
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
              />
            </div>
            
            <el-empty v-if="userList.length === 0 && !loading" description="暂无用户数据" />
          </div>
        </el-tab-pane>

        <!-- 添加用户 -->
        <el-tab-pane label="添加用户" name="addUser">
          <div class="add-user-section">
            <el-form
              ref="addFormRef"
              :model="addForm"
              :rules="addFormRules"
              label-width="100px"
              class="add-user-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">
                  <el-icon><Plus /></el-icon>
                  立即创建
                </el-button>
                <el-button @click="resetAddForm">
                  <el-icon><Refresh /></el-icon>
                  重置表单
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <div class="dialog-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'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  // 当前已选中的用户ID（用于回显）
  currentUserId: {
    type: [String, Number],
    default: ''
  }
})

// Emits
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: '',
  status: '',
  page: 1,
  count: 10
})

// 添加用户表单
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' }
  ]
}

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    // 重置状态
    activeTab.value = 'selectUser'
    selectedUser.value = null
    searchParams.page = 1
    fetchUserList()
  }
})

// 监听 visible 变化
watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  userList.value = []
  
  try {
    const params = {
      page: searchParams.page,
      count: searchParams.count,
      key: searchParams.key || ''
    }
    
    const res = await getUserList(params)
    
    if (res.data.code === 200) {
      userList.value = res.data.data?.data || []
      total.value = res.data.data?.all_count || 0
      
      // 如果有当前选中的用户ID，自动选中
      if (props.currentUserId) {
        const currentUser = userList.value.find(
          user => user.user_id === props.currentUserId
        )
        if (currentUser) {
          selectedUser.value = currentUser
        }
      }
    } else {
      ElMessage.error(res.data.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    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.status = ''
  searchParams.page = 1
  fetchUserList()
}

// 分页处理
const handleSizeChange = (size) => {
  searchParams.count = size
  searchParams.page = 1
  fetchUserList()
}

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

// 切换到添加用户标签页
const switchToAdd = () => {
  activeTab.value = 'addUser'
}

// 选择用户
const handleCurrentChange = (row) => {
  selectedUser.value = row
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (selectedUser.value && row.user_id === selectedUser.value.user_id) {
    return 'selected-row'
  }
  return ''
}

// 添加用户
const handleAddUser = async () => {
  if (!addFormRef.value) return
  
  await addFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    addLoading.value = true
    
    try {
      const formData = new FormData()
      formData.append('user_name', addForm.user_name)
      formData.append('email', addForm.email)
      if (addForm.phone) {
        formData.append('phone', addForm.phone)
      }
      formData.append('password', addForm.password)
      
      const res = await createTask(formData)
      
      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 (error) {
      console.error('用户创建失败:', error)
      ElMessage.error('用户创建失败')
    } finally {
      addLoading.value = false
    }
  })
}

// 重置添加表单
const resetAddForm = () => {
  addForm.user_name = ''
  addForm.email = ''
  addForm.phone = ''
  addForm.password = ''
  addForm.confirmPassword = ''
  addFormRef.value?.resetFields()
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  selectedUser.value = null
  userList.value = []
  searchParams.key = ''
  searchParams.status = ''
  searchParams.page = 1
  total.value = 0
  resetAddForm()
}

// 确认选择
const handleConfirm = () => {
  if (selectedUser.value) {
    emit('confirm', selectedUser.value)
    handleClose()
  } else {
    ElMessage.warning('请选择一个用户')
  }
}
</script>

<style scoped>
.user-selector {
  min-height: 450px;
}

.user-list-container {
  padding: 10px 0;
}

.filter-section {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 12px;
}

.user-info-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}

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

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.add-user-section {
  padding: 30px 60px;
}

.add-user-form {
  max-width: 500px;
  margin: 0 auto;
}

.add-user-form :deep(.el-input) {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表格样式 */
:deep(.el-table__row) {
  cursor: pointer;
}

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

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

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

:deep(.el-table__body tr.current-row > td) {
  background-color: var(--el-color-primary-light-8) !important;
}

/* 标签页样式 */
:deep(.el-tabs__header) {
  margin-bottom: 16px;
}

:deep(.el-tabs__item) {
  font-size: 15px;
  padding: 0 24px;
}

:deep(.el-tabs__item.is-active) {
  font-weight: 600;
}
</style>
