UserView.vue 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <script setup>
  2. import { UserRole } from '@/enums'
  3. import { createUserApi, listUsersApi, updateUserApi } from '@/services/api'
  4. import { Form } from '@primevue/forms'
  5. import { zodResolver } from '@primevue/forms/resolvers/zod'
  6. import { useDateFormat } from '@vueuse/core'
  7. import Button from 'primevue/button'
  8. import Column from 'primevue/column'
  9. import DataTable from 'primevue/datatable'
  10. import Dialog from 'primevue/dialog'
  11. import Dropdown from 'primevue/dropdown'
  12. import FloatLabel from 'primevue/floatlabel'
  13. import IconField from 'primevue/iconfield'
  14. import InputIcon from 'primevue/inputicon'
  15. import InputText from 'primevue/inputtext'
  16. import Message from 'primevue/message'
  17. import Password from 'primevue/password'
  18. import { useToast } from 'primevue/usetoast'
  19. import { computed, onMounted, ref } from 'vue'
  20. import { z } from 'zod'
  21. const toast = useToast()
  22. const tableData = ref({
  23. content: [],
  24. metadata: {
  25. page: 0,
  26. size: 20,
  27. total: 0
  28. }
  29. })
  30. const search = ref('')
  31. const fetchData = async () => {
  32. const response = await listUsersApi(tableData.value.metadata.page, tableData.value.metadata.size)
  33. tableData.value = response
  34. }
  35. const handlePageChange = (event) => {
  36. console.log('handlePageChange', event)
  37. tableData.value.metadata.page = event.page
  38. tableData.value.metadata.size = event.rows
  39. fetchData()
  40. }
  41. const formatDate = (date) => {
  42. return useDateFormat(new Date(date), 'YYYY-MM-DD HH:mm:ss').value
  43. }
  44. // 获取角色名称
  45. const getRoleName = (role) => {
  46. return UserRole[role] || role
  47. }
  48. // 用户角色选项
  49. const roleOptions = computed(() => {
  50. const allowedRoles = ['user', 'admin', 'channel', 'operator']
  51. return allowedRoles.map((role) => ({
  52. value: role,
  53. label: UserRole[role]
  54. }))
  55. })
  56. // 用户表单相关
  57. const userDialog = ref(false)
  58. const isEditMode = ref(false)
  59. const userForm = ref({
  60. id: null,
  61. name: '',
  62. password: '',
  63. confirmPassword: '',
  64. role: 'user'
  65. })
  66. const userFormLoading = ref(false)
  67. const userFormResolver = computed(() => {
  68. // 创建和更新时的验证规则不同
  69. const passwordRules = isEditMode.value
  70. ? z.string().optional() // 更新时密码可选
  71. : z.string().min(8, { message: '密码至少8位' })
  72. return zodResolver(
  73. z.object({
  74. name: z.string().min(1, { message: '用户名不能为空' }),
  75. password: passwordRules,
  76. confirmPassword: z
  77. .string()
  78. .refine((val) => !userForm.value.password || val === userForm.value.password, { message: '密码不一致' }),
  79. role: z.string().min(1, { message: '请选择角色' })
  80. })
  81. )
  82. })
  83. const openNewUserDialog = () => {
  84. userForm.value = {
  85. id: null,
  86. name: '',
  87. password: '',
  88. confirmPassword: '',
  89. role: 'user'
  90. }
  91. isEditMode.value = false
  92. userDialog.value = true
  93. }
  94. const openEditUserDialog = (user) => {
  95. userForm.value = {
  96. id: user.id,
  97. name: user.name,
  98. password: '',
  99. confirmPassword: '',
  100. role: user.role
  101. }
  102. isEditMode.value = true
  103. userDialog.value = true
  104. }
  105. const saveUser = async ({ valid, values }) => {
  106. if (!valid) return
  107. userFormLoading.value = true
  108. try {
  109. // 构建提交数据,过滤掉不需要的confirmPassword
  110. const submitData = {
  111. name: values.name,
  112. role: values.role
  113. }
  114. if (values.password) {
  115. submitData.password = values.password
  116. }
  117. if (isEditMode.value) {
  118. submitData.id = userForm.value.id
  119. await updateUserApi(submitData)
  120. toast.add({
  121. severity: 'success',
  122. summary: '成功',
  123. detail: '用户更新成功',
  124. life: 3000
  125. })
  126. } else {
  127. // 新建用户必须有密码
  128. await createUserApi(submitData)
  129. toast.add({
  130. severity: 'success',
  131. summary: '成功',
  132. detail: '用户创建成功',
  133. life: 3000
  134. })
  135. }
  136. userDialog.value = false
  137. fetchData() // 刷新列表
  138. } catch (error) {
  139. const errorMsg = error.message || (isEditMode.value ? '更新用户失败' : '创建用户失败')
  140. toast.add({
  141. severity: 'error',
  142. summary: '错误',
  143. detail: errorMsg,
  144. life: 3000
  145. })
  146. } finally {
  147. userFormLoading.value = false
  148. }
  149. }
  150. onMounted(() => {
  151. fetchData()
  152. })
  153. </script>
  154. <template>
  155. <div class="rounded-lg p-4 bg-[var(--p-content-background)]">
  156. <DataTable
  157. :value="tableData.content"
  158. :paginator="true"
  159. paginatorTemplate="CurrentPageReport FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown JumpToPageInput"
  160. currentPageReportTemplate="{totalRecords} 条记录 "
  161. :rows="tableData.metadata.size"
  162. :rowsPerPageOptions="[10, 20, 50, 100]"
  163. :totalRecords="tableData.metadata.total"
  164. @page="handlePageChange"
  165. lazy
  166. scrollable
  167. >
  168. <template #header>
  169. <div class="flex flex-wrap items-center">
  170. <Button icon="pi pi-refresh" @click="fetchData" label="刷新" size="small" />
  171. <Button
  172. icon="pi pi-plus"
  173. @click="openNewUserDialog"
  174. label="新增用户"
  175. severity="success"
  176. size="small"
  177. class="ml-2"
  178. />
  179. <div class="flex-1"></div>
  180. <IconField>
  181. <InputIcon>
  182. <i class="pi pi-search" />
  183. </InputIcon>
  184. <InputText v-model="search" placeholder="搜素" />
  185. </IconField>
  186. </div>
  187. </template>
  188. <Column field="id" header="ID"></Column>
  189. <Column field="name" header="用户名"></Column>
  190. <Column field="role" header="角色">
  191. <template #body="slotProps">
  192. <span class="px-2 py-1 rounded-md text-sm">
  193. {{ getRoleName(slotProps.data.role) }}
  194. </span>
  195. </template>
  196. </Column>
  197. <Column field="createdAt" header="创建时间" style="min-width: 200px">
  198. <template #body="slotProps">
  199. {{ formatDate(slotProps.data.createdAt) }}
  200. </template>
  201. </Column>
  202. <Column header="操作" style="min-width: 150px">
  203. <template #body="slotProps">
  204. <Button
  205. icon="pi pi-pencil"
  206. severity="info"
  207. size="small"
  208. text
  209. rounded
  210. aria-label="编辑"
  211. @click="openEditUserDialog(slotProps.data)"
  212. />
  213. </template>
  214. </Column>
  215. </DataTable>
  216. <!-- 用户表单对话框 -->
  217. <Dialog
  218. v-model:visible="userDialog"
  219. :modal="true"
  220. :header="isEditMode ? '编辑用户' : '创建用户'"
  221. :style="{ width: '450px' }"
  222. position="center"
  223. >
  224. <Form v-slot="$form" :resolver="userFormResolver" :initialValues="userForm" @submit="saveUser" class="p-fluid">
  225. <div class="field mt-4">
  226. <FloatLabel variant="on">
  227. <IconField>
  228. <InputIcon class="pi pi-user" />
  229. <InputText id="name" name="name" v-model="userForm.name" autocomplete="off" fluid />
  230. </IconField>
  231. <label for="name">用户名</label>
  232. </FloatLabel>
  233. <Message v-if="$form.name?.invalid" severity="error" size="small" variant="simple">
  234. {{ $form.name.error?.message }}
  235. </Message>
  236. </div>
  237. <div class="field mt-4">
  238. <FloatLabel variant="on">
  239. <IconField>
  240. <InputIcon class="pi pi-lock" />
  241. <Password
  242. id="password"
  243. name="password"
  244. v-model="userForm.password"
  245. toggleMask
  246. :feedback="false"
  247. autocomplete="off"
  248. fluid
  249. />
  250. </IconField>
  251. <label for="password">{{ isEditMode ? '密码 (可选)' : '密码' }}</label>
  252. </FloatLabel>
  253. <Message v-if="$form.password?.invalid" severity="error" size="small" variant="simple">
  254. {{ $form.password.error?.message }}
  255. </Message>
  256. <div v-if="isEditMode" class="text-sm text-gray-500 mt-1 ml-1">* 留空则不修改</div>
  257. </div>
  258. <div class="field mt-4">
  259. <FloatLabel variant="on">
  260. <IconField>
  261. <InputIcon class="pi pi-lock" />
  262. <Password
  263. id="confirmPassword"
  264. name="confirmPassword"
  265. v-model="userForm.confirmPassword"
  266. toggleMask
  267. :feedback="false"
  268. fluid
  269. autocomplete="off"
  270. />
  271. </IconField>
  272. <label for="confirmPassword">确认密码</label>
  273. </FloatLabel>
  274. <Message v-if="$form.confirmPassword?.invalid" severity="error" size="small" variant="simple">
  275. {{ $form.confirmPassword.error?.message }}
  276. </Message>
  277. <div v-if="isEditMode" class="text-sm text-gray-500 mt-1 ml-1">* 留空则不修改</div>
  278. </div>
  279. <div class="field mt-4">
  280. <FloatLabel variant="on">
  281. <Dropdown
  282. id="role"
  283. name="role"
  284. v-model="userForm.role"
  285. :options="roleOptions"
  286. optionLabel="label"
  287. optionValue="value"
  288. fluid
  289. />
  290. <label for="role">角色</label>
  291. </FloatLabel>
  292. <Message v-if="$form.role?.invalid" severity="error" size="small" variant="simple">
  293. {{ $form.role.error?.message }}
  294. </Message>
  295. </div>
  296. <div class="flex justify-end gap-2 mt-4">
  297. <Button
  298. label="取消"
  299. severity="secondary"
  300. type="button"
  301. @click="userDialog = false"
  302. :disabled="userFormLoading"
  303. />
  304. <Button label="保存" type="submit" :loading="userFormLoading" />
  305. </div>
  306. </Form>
  307. </Dialog>
  308. </div>
  309. </template>