<template>
  <div class="user-management">
    <a-card>
      <template #title>
        <div class="card-title">
          <span>用户管理</span>
          <a-button type="primary" @click="handleAdd">新增用户</a-button>
        </div>
      </template>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === '0' ? 'green' : 'red'">
              {{ record.status === '0' ? '正常' : '禁用' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleEdit(record)">编辑</a-button>
              <a-button type="link" danger @click="handleDelete(record)">删除</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        :model="formState"
        :label-col="{ span: 6 }"
        layout="horizontal"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" />
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="formState.phone" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="formState.status">
            <a-select-option value="0">正常</a-select-option>
            <a-select-option value="1">禁用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import request from '@/utils/request'

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '用户名', dataIndex: 'username', key: 'username' },
  { title: '邮箱', dataIndex: 'email', key: 'email' },
  { title: '手机号', dataIndex: 'phone', key: 'phone' },
  { title: '状态', key: 'status', width: 100 },
  { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt' },
  { title: '操作', key: 'action', width: 200 }
]

const loading = ref(false)
const dataSource = ref([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const modalVisible = ref(false)
const modalTitle = ref('')
const formState = reactive({
  id: null as number | null,
  username: '',
  email: '',
  phone: '',
  status: '0'
})

const fetchData = async () => {
  loading.value = true
  try {
    const res: any = await request.get('/users', {
      params: {
        page: pagination.current,
        pageSize: pagination.pageSize
      }
    })
    dataSource.value = res.data
    pagination.total = res.total
  } finally {
    loading.value = false
  }
}

const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  fetchData()
}

const handleAdd = () => {
  modalTitle.value = '新增用户'
  Object.assign(formState, { id: null, username: '', email: '', phone: '', status: '0' })
  modalVisible.value = true
}

const handleEdit = (record: any) => {
  modalTitle.value = '编辑用户'
  Object.assign(formState, record)
  modalVisible.value = true
}

const handleDelete = async (record: any) => {
  try {
    await request.delete(`/users/${record.id}`)
    message.success('删除成功')
    fetchData()
  } catch {
    message.error('删除失败')
  }
}

const handleModalOk = async () => {
  try {
    if (formState.id) {
      await request.put(`/users/${formState.id}`, formState)
      message.success('更新成功')
    } else {
      await request.post('/users', formState)
      message.success('创建成功')
    }
    modalVisible.value = false
    fetchData()
  } catch {
    message.error('操作失败')
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.user-management {
  .card-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
