<template>
  <div class="flex h-screen">
    <SideBar />
    <div class="flex-1 p-4 overflow-auto">
      <el-card>
        <template #header>
          <div class="flex justify-between items-center">
            <span>用户列表</span>
            <el-button type="primary" @click="handleCreateUser">新增用户</el-button>
          </div>
        </template>

        <el-form :inline="true" :model="searchForm" class="mb-4">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="active"></el-option>
              <el-option label="禁用" value="inactive"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID" width="100"></el-table-column>
          <el-table-column prop="username" label="用户名" width="120"></el-table-column>
          <el-table-column prop="name" label="姓名" width="120"></el-table-column>
          <el-table-column prop="gender" label="性别" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.gender === '男' ? 'primary' : 'success'">
                {{ scope.row.gender }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="age" label="年龄" width="80"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.status"
                  active-text="启用"
                  inactive-text="禁用"
                  @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            class="mt-4 flex justify-center"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        ></el-pagination>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs } from 'vue'
import SideBar from '../components/SideBar.vue'

// 搜索表单
const searchForm = reactive({
  username: '',
  status: ''
})

// 表格数据
const tableData = ref([
  { id: 1, username: 'user1', name: '张三', gender: '男', age: 20, email: 'zhangsan@example.com', status: true },
  { id: 2, username: 'user2', name: '李四', gender: '女', age: 24, email: 'lisi@example.com', status: true },
  { id: 3, username: 'user3', name: '王五', gender: '男', age: 30, email: 'wangwu@example.com', status: false },
  { id: 4, username: 'user4', name: '赵六', gender: '女', age: 22, email: 'zhaoliu@example.com', status: true },
  { id: 5, username: 'user5', name: '钱七', gender: '男', age: 28, email: 'qianqi@example.com', status: true },
  { id: 6, username: 'user6', name: '孙八', gender: '女', age: 25, email: 'sunba@example.com', status: false },
  { id: 7, username: 'user7', name: '周九', gender: '男', age: 32, email: 'zhoujiu@example.com', status: true },
  { id: 8, username: 'user8', name: '吴十', gender: '女', age: 27, email: 'wushi@example.com', status: true },
])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const editForm = reactive({
  id: null,
  username: '',
  name: '',
  gender: '男',
  age: 0,
  email: '',
  status: true
})

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ]
})

// 表单引用
const editFormRef = ref(null)

// 搜索方法
const handleSearch = () => {
  console.log('搜索条件:', searchForm)
  // 这里可以添加搜索逻辑
}

const resetSearch = () => {
  searchForm.username = ''
  searchForm.status = ''
}

// 表格操作
const handleEdit = (row) => {
  // 复制数据到编辑表单
  Object.assign(editForm, row)
  dialogTitle.value = '编辑用户'
  dialogVisible.value = true
}

const handleDelete = (row) => {
  elMessageBox.confirm(
      '确定要删除该用户吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 从表格数据中删除
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      tableData.value.splice(index, 1)
      elMessage({
        type: 'success',
        message: '删除成功!'
      })
    }
  }).catch(() => {
    elMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const handleStatusChange = (row) => {
  const statusText = row.status ? '启用' : '禁用'
  elMessage({
    type: 'success',
    message: `用户 ${row.username} 已${statusText}`
  })
}

// 分页事件处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  console.log('每页条数:', newSize)
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  console.log('当前页码:', newPage)
}

// 创建用户
const handleCreateUser = () => {
  // 清空表单
  Object.keys(editForm).forEach(key => {
    if (key === 'id') {
      editForm[key] = null
    } else if (key === 'status') {
      editForm[key] = true
    } else if (key === 'gender') {
      editForm[key] = '男'
    } else {
      editForm[key] = ''
    }
  })

  dialogTitle.value = '新增用户'
  dialogVisible.value = true
}

// 保存用户
const saveUser = () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      // 模拟保存操作
      setTimeout(() => {
        dialogVisible.value = false
        elMessage({
          type: 'success',
          message: dialogTitle.value === '新增用户' ? '创建成功!' : '更新成功!'
        })

        // 更新表格数据
        if (editForm.id) {
          // 更新现有用户
          const index = tableData.value.findIndex(item => item.id === editForm.id)
          if (index !== -1) {
            tableData.value.splice(index, 1, { ...editForm })
          }
        } else {
          // 创建新用户
          const newId = Math.max(...tableData.value.map(item => item.id)) + 1
          tableData.value.unshift({ ...editForm, id: newId })
        }
      }, 500)
    } else {
      console.log('验证失败')
      return false
    }
  })
}
</script>