<template>
  <div class="page-user">
    <!-- 标题栏 -->
    <div class="page-toolbar">
      <h2 class="page-title">用户管理</h2>
      <n-button type="primary" @click="showAddModal = true">
        <template #icon><n-icon :component="PersonAddOutline" /></template>
        新增用户
      </n-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <n-space align="center" :wrap="true" :size="12">
        <n-input
          v-model:value="searchForm.nick_name"
          placeholder="搜索昵称"
          clearable
          :style="{ width: '180px' }"
          @keyup.enter="handleSearch"
        />
        <n-input
          v-model:value="searchForm.user_name"
          placeholder="搜索用户名"
          clearable
          :style="{ width: '180px' }"
          @keyup.enter="handleSearch"
        />
        <n-button type="primary" size="small" @click="handleSearch">
          <template #icon><n-icon :component="SearchOutline" /></template>
          查询
        </n-button>
        <n-button size="small" @click="handleReset">重置</n-button>
      </n-space>
    </div>

    <!-- 数据表格 -->
    <div class="table-card">
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :row-key="rowKey"
        :bordered="false"
        :single-line="false"
        remote
        size="small"
        striped
      >
        <template #empty>
          <n-empty description="暂无用户数据">
            <template #extra>
              <n-button type="primary" size="small" @click="showAddModal = true">新增用户</n-button>
            </template>
          </n-empty>
        </template>
      </n-data-table>

      <div v-if="total > 0" class="table-footer">
        <span class="total-hint">共 {{ total }} 条数据</span>
        <n-pagination
          v-model:page="pagination.page"
          :page-size="pagination.page_size"
          :item-count="total"
          :page-sizes="[5, 10, 20, 50]"
          show-size-picker
          @update:page="handlePageChange"
          @update:page-size="handlePageSizeChange"
        />
      </div>
    </div>

    <!-- 新增用户弹窗 -->
    <n-modal v-model:show="showAddModal" preset="card" title="新增用户" :style="{ width: '520px' }" :mask-closable="false">
      <n-form ref="formRef" :model="formData" :rules="formRules" label-placement="left" label-width="80" require-mark-placement="right-hanging">
        <n-form-item label="用户名" path="user_name">
          <n-input v-model:value="formData.user_name" placeholder="请输入用户名" />
        </n-form-item>
        <n-form-item label="密码" path="password">
          <n-input v-model:value="formData.password" type="password" placeholder="请输入密码" show-password-on="click" />
        </n-form-item>
        <n-form-item label="昵称" path="nick_name">
          <n-input v-model:value="formData.nick_name" placeholder="请输入昵称" />
        </n-form-item>
        <n-form-item label="邮箱" path="email">
          <n-input v-model:value="formData.email" placeholder="请输入邮箱" />
        </n-form-item>
        <n-form-item label="手机号" path="phone">
          <n-input v-model:value="formData.phone" placeholder="请输入手机号" />
        </n-form-item>
        <n-form-item label="年龄" path="age">
          <n-input-number v-model:value="formData.age" :min="0" :max="150" :style="{ width: '100%' }" />
        </n-form-item>
        <n-form-item label="性别" path="sex">
          <n-select v-model:value="formData.sex" :options="sexOptions" placeholder="请选择性别" />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="showAddModal = false">取消</n-button>
          <n-button type="primary" :loading="submitting" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>
    <!-- 编辑用户弹窗 -->
    <n-modal v-model:show="showEditModal" preset="card" title="编辑用户" :style="{ width: '520px' }" :mask-closable="false">
      <n-form ref="editFormRef" :model="editFormData" :rules="editFormRules" label-placement="left" label-width="80" require-mark-placement="right-hanging">
        <n-form-item label="用户名" path="user_name">
          <n-input v-model:value="editFormData.user_name" placeholder="请输入用户名" />
        </n-form-item>
        <n-form-item label="昵称" path="nick_name">
          <n-input v-model:value="editFormData.nick_name" placeholder="请输入昵称" />
        </n-form-item>
        <n-form-item label="邮箱" path="email">
          <n-input v-model:value="editFormData.email" placeholder="请输入邮箱" />
        </n-form-item>
        <n-form-item label="手机号" path="phone">
          <n-input v-model:value="editFormData.phone" placeholder="请输入手机号" />
        </n-form-item>
        <n-form-item label="年龄" path="age">
          <n-input-number v-model:value="editFormData.age" :min="0" :max="150" :style="{ width: '100%' }" />
        </n-form-item>
        <n-form-item label="性别" path="sex">
          <n-select v-model:value="editFormData.sex" :options="sexOptions" placeholder="请选择性别" />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="showEditModal = false">取消</n-button>
          <n-button type="primary" :loading="editSubmitting" @click="handleEditSubmit">保存</n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 分配角色弹窗 -->
    <n-modal v-model:show="showRoleModal" preset="card" :title="'分配角色 - ' + selectedRoleUser.user_name" :style="{ width: '460px' }" :mask-closable="false">
      <div v-if="allRoles.length > 0" style="max-height: 360px; overflow-y: auto; padding: 4px 0;">
        <n-checkbox-group v-model:value="checkedRoleIds">
          <n-space vertical :size="4">
            <n-checkbox v-for="role in allRoles" :key="role.id" :value="role.id">
              <span style="font-weight: 500;">{{ role.role_name }}</span>
              <span style="color: #86909C; font-size: 12px; margin-left: 8px;">{{ role.role_key }}</span>
            </n-checkbox>
          </n-space>
        </n-checkbox-group>
      </div>
      <n-empty v-else description="暂无可用角色" style="padding: 24px 0;" />
      <template #footer>
        <n-space justify="end">
          <n-button @click="showRoleModal = false">取消</n-button>
          <n-button type="primary" :loading="roleSubmitting" @click="handleRoleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h } from 'vue'
import { NButton, NIcon, useMessage, useDialog } from 'naive-ui'
import type { DataTableColumns, FormInst, FormRules } from 'naive-ui'
import { SearchOutline, PersonAddOutline, CreateOutline, TrashOutline, ShieldCheckmarkOutline } from '@vicons/ionicons5'
import UserApi, { type UserInfo, type UserSaveReq } from '@/api/system/user'
import RoleApi, { type RoleInfo } from '@/api/system/role'

const message = useMessage()
const dialog = useDialog()

// ─── 搜索 ───
const searchForm = reactive({ nick_name: '', user_name: '' })

// ─── 分页 ───
const pagination = reactive({ page: 1, page_size: 10 })

// ─── 表格 ───
const loading = ref(false)
const tableData = ref<UserInfo[]>([])
const total = ref(0)
const rowKey = (row: UserInfo) => row.id

const sexMap: Record<number, string> = { 0: '未知', 1: '男', 2: '女' }

const columns: DataTableColumns<UserInfo> = [
  { title: 'ID', key: 'id', width: 70, align: 'center' },
  { title: '用户名', key: 'user_name', width: 120, ellipsis: { tooltip: true } },
  { title: '昵称', key: 'nick_name', width: 120, ellipsis: { tooltip: true } },
  { title: '邮箱', key: 'email', width: 180, ellipsis: { tooltip: true } },
  { title: '手机号', key: 'phone', width: 130 },
  { title: '年龄', key: 'age', width: 60, align: 'center' },
  {
    title: '性别', key: 'sex', width: 70, align: 'center',
    render(row) { return h('span', {}, sexMap[row.sex] ?? '未知') },
  },
  {
    title: '创建时间', key: 'create_time', width: 170,
    render(row) { return row.create_time ?? '-' },
  },
    {
    title: '操作', key: 'actions', width: 220, align: 'center',
    render(row) {
      return h('div', { style: { display: 'flex', gap: '8px', justifyContent: 'center' } }, [
        h(NButton, {
          text: true, size: 'tiny', type: 'info',
          onClick: (e: Event) => { e.stopPropagation(); openRoleModal(row) },
        }, { icon: () => h(NIcon, null, { default: () => h(ShieldCheckmarkOutline) }), default: () => '角色' }),
        h(NButton, {
          text: true, size: 'tiny', type: 'primary',
          onClick: (e: Event) => { e.stopPropagation(); openEditModal(row) },
        }, { icon: () => h(NIcon, null, { default: () => h(CreateOutline) }), default: () => '编辑' }),
        h(NButton, {
          text: true, size: 'tiny', type: 'error',
          onClick: (e: Event) => { e.stopPropagation(); handleDelete(row) },
        }, { icon: () => h(NIcon, null, { default: () => h(TrashOutline) }), default: () => '删除' }),
      ])
    },
  },
]
// ─── 数据加载 ───
async function fetchData() {
  loading.value = true
  try {
    const res = await UserApi.getUserPage({
      page: pagination.page,
      page_size: pagination.page_size,
      nick_name: searchForm.nick_name || undefined,
      user_name: searchForm.user_name || undefined,
    })
    if (res.success && res.data) {
      tableData.value = res.data.list ?? []
      total.value = res.data.total
    }
  } catch (e: any) {
    message.error(e?.toString() ?? '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

fetchData()

function handleSearch() { pagination.page = 1; fetchData() }
function handleReset() { searchForm.nick_name = ''; searchForm.user_name = ''; pagination.page = 1; fetchData() }
function handlePageChange(page: number) { pagination.page = page; fetchData() }
function handlePageSizeChange(size: number) { pagination.page_size = size; pagination.page = 1; fetchData() }

// ─── 新增用户 ───
const showAddModal = ref(false)
const submitting = ref(false)
const formRef = ref<FormInst | null>(null)

const formData = reactive<UserSaveReq>({
  id: 0, nick_name: '', avatar: '', user_name: '', password: '',
  email: '', phone: '', age: 0, sex: 0, creater: 0,
})

const formRules: FormRules = {
  user_name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, message: '密码至少6位', trigger: 'blur' }],
  nick_name: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
}

const sexOptions = [
  { label: '未知', value: 0 },
  { label: '男', value: 1 },
  { label: '女', value: 2 },
]
async function handleSubmit() {
  try { await formRef.value?.validate() } catch { return }
  submitting.value = true
  try {
    const res = await UserApi.register({ ...formData })
    if (res.success) {
      message.success('新增用户成功')
      showAddModal.value = false
      Object.assign(formData, { id: 0, nick_name: '', avatar: '', user_name: '', password: '', email: '', phone: '', age: 0, sex: 0, creater: 0 })
      fetchData()
    } else {
      message.error(res.message)
    }
  } catch (e: any) {
    message.error(e?.toString() ?? '操作失败')
  } finally {
    submitting.value = false
  }
}

// ─── 编辑用户 ───
const showEditModal = ref(false)
const editSubmitting = ref(false)
const editFormRef = ref<FormInst | null>(null)
const editingUserId = ref<number>(0)

const editFormData = reactive<UserSaveReq>({
  id: 0, nick_name: '', avatar: '', user_name: '', password: '',
  email: '', phone: '', age: 0, sex: 0, creater: 0,
})

const editFormRules: FormRules = {
  user_name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  nick_name: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
}

function openEditModal(row: UserInfo) {
  editingUserId.value = row.id
  Object.assign(editFormData, {
    id: row.id, nick_name: row.nick_name, avatar: row.avatar,
    user_name: row.user_name, password: '', email: row.email,
    phone: row.phone, age: row.age, sex: row.sex, creater: 0,
  })
  showEditModal.value = true
}

async function handleEditSubmit() {
  try { await editFormRef.value?.validate() } catch { return }
  editSubmitting.value = true
  try {
    const res = await UserApi.update_user({ ...editFormData, id: editingUserId.value })
    if (res.success) {
      message.success('更新成功')
      showEditModal.value = false
      fetchData()
    } else {
      message.error(res.message)
    }
  } catch (e: any) {
    message.error(e?.toString() ?? '更新失败')
  } finally {
    editSubmitting.value = false
  }
}
// ─── 删除用户 ───
function handleDelete(row: UserInfo) {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除用户「${row.user_name}」吗？此操作不可撤销。`,
    positiveText: '确认删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        const res = await UserApi.delUser(row.id)
        if (res.success) {
          message.success('删除成功')
          fetchData()
        } else {
          message.error(res.message)
        }
      } catch (e: any) {
        message.error(e?.toString() ?? '删除失败')
      }
    },
  })
}

// ─── 分配角色 ───
const showRoleModal = ref(false)
const roleSubmitting = ref(false)
const allRoles = ref<RoleInfo[]>([])
const checkedRoleIds = ref<number[]>([])
const selectedRoleUser = ref<UserInfo>({ id: 0, nick_name: '', user_name: '', email: '', phone: '', avatar: '', age: 0, sex: 0 })

async function openRoleModal(row: UserInfo) {
  selectedRoleUser.value = row
  try {
    const [rolesRes, roleIdsRes] = await Promise.all([
      RoleApi.roleList(),
      UserApi.getUserRole(row.id),
    ])
    if (rolesRes.success && rolesRes.data) {
      allRoles.value = rolesRes.data
    }
    if (roleIdsRes.success && roleIdsRes.data) {
      checkedRoleIds.value = roleIdsRes.data
    }
  } catch (e: any) {
    message.error(e?.toString() ?? '加载角色信息失败')
    return
  }
  showRoleModal.value = true
}

async function handleRoleSubmit() {
  roleSubmitting.value = true
  try {
    const res = await UserApi.assignRole(selectedRoleUser.value.id, checkedRoleIds.value)
    if (res.success) {
      message.success('分配角色成功')
      showRoleModal.value = false
    } else {
      message.error(res.message)
    }
  } catch (e: any) {
    message.error(e?.toString() ?? '分配角色失败')
  } finally {
    roleSubmitting.value = false
  }
}
</script>

<style scoped>
.page-user {
  padding: 24px;
  width: 100%;
  box-sizing: border-box;
}

.page-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-family: 'Space Grotesk', system-ui, sans-serif;
  font-size: 22px;
  font-weight: 700;
  color: var(--color-text, #1D2129);
  letter-spacing: -0.3px;
}

.search-bar {
  background: var(--color-surface, #fff);
  border: 1px solid var(--color-border, #E5E6EB);
  border-radius: 10px;
  padding: 14px 18px;
  margin-bottom: 16px;
}

.table-card {
  background: var(--color-surface, #fff);
  border: 1px solid var(--color-border, #E5E6EB);
  border-radius: 10px;
  overflow-x: auto;
}

.table-card :deep(.n-data-table) {
  --n-th-padding: 12px 16px;
  --n-td-padding: 10px 16px;
  --n-th-font-weight: 600;
}

.table-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 20px;
  border-top: 1px solid var(--color-border, #E5E6EB);
}

.total-hint {
  font-size: 13px;
  color: var(--color-text-secondary, #86909C);
}

@media (max-width: 768px) {
  .page-user { padding: 16px; }
  .page-toolbar { flex-direction: column; align-items: flex-start; gap: 12px; }
  .search-bar :deep(.n-space) { flex-direction: column; align-items: stretch; }
}
</style>
