index.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. <script setup lang="ts">
  2. import { onMounted, reactive, ref, unref, watch } from 'vue'
  3. import dayjs from 'dayjs'
  4. import {
  5. ElTag,
  6. ElInput,
  7. ElCard,
  8. ElTree,
  9. ElTreeSelect,
  10. ElSelect,
  11. ElOption,
  12. ElTransfer,
  13. ElForm,
  14. ElFormItem,
  15. ElUpload,
  16. ElSwitch,
  17. ElCheckbox,
  18. UploadInstance,
  19. UploadRawFile
  20. } from 'element-plus'
  21. import { handleTree } from '@/utils/tree'
  22. import { useI18n } from '@/hooks/web/useI18n'
  23. import { useTable } from '@/hooks/web/useTable'
  24. import { FormExpose } from '@/components/Form'
  25. import type { UserVO } from '@/api/system/user/types'
  26. import type { PostVO } from '@/api/system/post'
  27. import type { PermissionAssignUserRoleReqVO } from '@/api/system/permission/types'
  28. import { listSimpleDeptApi } from '@/api/system/dept'
  29. import { listSimplePostsApi } from '@/api/system/post'
  30. import { listSimpleRolesApi } from '@/api/system/role'
  31. import { aassignUserRoleApi, listUserRolesApi } from '@/api/system/permission'
  32. import { rules, allSchemas } from './user.data'
  33. import * as UserApi from '@/api/system/user'
  34. import download from '@/utils/download'
  35. import { useRouter } from 'vue-router'
  36. import { CommonStatusEnum } from '@/utils/constants'
  37. import { getAccessToken, getTenantId } from '@/utils/auth'
  38. import { useMessage } from '@/hooks/web/useMessage'
  39. const message = useMessage()
  40. const defaultProps = {
  41. children: 'children',
  42. label: 'name',
  43. value: 'id'
  44. }
  45. const { t } = useI18n() // 国际化
  46. // ========== 列表相关 ==========
  47. const tableTitle = ref('用户列表')
  48. const { register, tableObject, methods } = useTable<UserVO>({
  49. getListApi: UserApi.getUserPageApi,
  50. delListApi: UserApi.deleteUserApi,
  51. exportListApi: UserApi.exportUserApi
  52. })
  53. const { getList, setSearchParams, delList, exportList } = methods
  54. // ========== 创建部门树结构 ==========
  55. const filterText = ref('')
  56. const deptOptions = ref<any[]>([]) // 树形结构
  57. const searchForm = ref<FormExpose>()
  58. const treeRef = ref<InstanceType<typeof ElTree>>()
  59. const getTree = async () => {
  60. const res = await listSimpleDeptApi()
  61. deptOptions.value.push(...handleTree(res))
  62. }
  63. const filterNode = (value: string, data: Tree) => {
  64. if (!value) return true
  65. return data.name.includes(value)
  66. }
  67. const handleDeptNodeClick = (data: { [key: string]: any }) => {
  68. tableObject.params = {
  69. deptId: data.id
  70. }
  71. tableTitle.value = data.name
  72. methods.getList()
  73. }
  74. const { push } = useRouter()
  75. const handleDeptEdit = () => {
  76. push('/system/dept')
  77. }
  78. watch(filterText, (val) => {
  79. treeRef.value!.filter(val)
  80. })
  81. // ========== CRUD 相关 ==========
  82. const loading = ref(false) // 遮罩层
  83. const actionType = ref('') // 操作按钮的类型
  84. const dialogVisible = ref(false) // 是否显示弹出层
  85. const dialogTitle = ref('edit') // 弹出层标题
  86. const formRef = ref<FormExpose>() // 表单 Ref
  87. const deptId = ref() // 部门ID
  88. const postIds = ref<string[]>([]) // 岗位ID
  89. const postOptions = ref<PostVO[]>([]) //岗位列表
  90. // 获取岗位列表
  91. const getPostOptions = async () => {
  92. const res = await listSimplePostsApi()
  93. postOptions.value.push(...res)
  94. }
  95. // 设置标题
  96. const setDialogTile = async (type: string) => {
  97. dialogTitle.value = t('action.' + type)
  98. actionType.value = type
  99. dialogVisible.value = true
  100. }
  101. // 新增操作
  102. const handleAdd = async () => {
  103. // 重置表单
  104. deptId.value = null
  105. postIds.value = []
  106. dialogVisible.value = true
  107. dialogTitle.value = t('action.create')
  108. actionType.value = 'create'
  109. await unref(formRef)?.getElFormRef().resetFields()
  110. }
  111. // 修改操作
  112. const handleUpdate = async (row: UserVO) => {
  113. await setDialogTile('update')
  114. unref(formRef)?.delSchema('username')
  115. unref(formRef)?.delSchema('password')
  116. // 设置数据
  117. const res = await UserApi.getUserApi(row.id)
  118. deptId.value = res.deptId
  119. postIds.value = res.postIds
  120. unref(formRef)?.setValues(res)
  121. }
  122. // 提交按钮
  123. const submitForm = async () => {
  124. loading.value = true
  125. // 提交请求
  126. try {
  127. const data = unref(formRef)?.formModel as UserVO
  128. data.deptId = deptId.value
  129. data.postIds = postIds.value
  130. if (actionType.value === 'create') {
  131. await UserApi.createUserApi(data)
  132. message.success(t('common.createSuccess'))
  133. } else {
  134. await UserApi.updateUserApi(data)
  135. message.success(t('common.updateSuccess'))
  136. }
  137. // 操作成功,重新加载列表
  138. dialogVisible.value = false
  139. await getList()
  140. } finally {
  141. loading.value = false
  142. }
  143. }
  144. // 改变用户状态操作
  145. const handleStatusChange = async (row: UserVO) => {
  146. const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
  147. message
  148. .confirm('确认要"' + text + '""' + row.username + '"用户吗?', t('common.reminder'))
  149. .then(async () => {
  150. row.status =
  151. row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.ENABLE : CommonStatusEnum.DISABLE
  152. await UserApi.updateUserStatusApi(row.id, row.status)
  153. message.success(text + '成功')
  154. await getList()
  155. })
  156. .catch(() => {
  157. row.status =
  158. row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  159. })
  160. }
  161. // 重置密码
  162. const handleResetPwd = (row: UserVO) => {
  163. message.prompt('请输入"' + row.username + '"的新密码', t('common.reminder')).then(({ value }) => {
  164. UserApi.resetUserPwdApi(row.id, value).then(() => {
  165. message.success('修改成功,新密码是:' + value)
  166. })
  167. })
  168. }
  169. // 分配角色
  170. const roleDialogVisible = ref(false)
  171. const roleOptions = ref()
  172. const userRole = reactive({
  173. id: 0,
  174. username: '',
  175. nickname: '',
  176. roleIds: []
  177. })
  178. const handleRole = async (row: UserVO) => {
  179. userRole.id = row.id
  180. userRole.username = row.username
  181. userRole.nickname = row.nickname
  182. // 获得角色拥有的权限集合
  183. const roles = await listUserRolesApi(row.id)
  184. userRole.roleIds = roles
  185. // 获取角色列表
  186. const roleOpt = await listSimpleRolesApi()
  187. roleOptions.value = roleOpt
  188. roleDialogVisible.value = true
  189. }
  190. // 提交
  191. const submitRole = async () => {
  192. const data = ref<PermissionAssignUserRoleReqVO>({
  193. userId: userRole.id,
  194. roleIds: userRole.roleIds
  195. })
  196. await aassignUserRoleApi(data.value)
  197. message.success(t('common.updateSuccess'))
  198. roleDialogVisible.value = false
  199. }
  200. // ========== 详情相关 ==========
  201. const detailRef = ref()
  202. // 详情操作
  203. const handleDetail = async (row: UserVO) => {
  204. // 设置数据
  205. detailRef.value = row
  206. await setDialogTile('detail')
  207. }
  208. // ========== 导入相关 ==========
  209. const importDialogVisible = ref(false)
  210. const uploadDisabled = ref(false)
  211. const importDialogTitle = ref('用户导入')
  212. const updateSupport = ref(0)
  213. let updateUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/system/user/import'
  214. const uploadHeaders = ref()
  215. // 下载导入模版
  216. const handleImportTemp = async () => {
  217. const res = await UserApi.importUserTemplateApi()
  218. download.excel(res, '用户导入模版.xls')
  219. }
  220. // 文件上传之前判断
  221. const beforeExcelUpload = (file: UploadRawFile) => {
  222. const isExcel =
  223. file.type === 'application/vnd.ms-excel' ||
  224. file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  225. const isLt5M = file.size / 1024 / 1024 < 5
  226. if (!isExcel) message.error('上传文件只能是 xls / xlsx 格式!')
  227. if (!isLt5M) message.error('上传文件大小不能超过 5MB!')
  228. return isExcel && isLt5M
  229. }
  230. // 文件上传
  231. const uploadRef = ref<UploadInstance>()
  232. const submitFileForm = () => {
  233. uploadHeaders.value = {
  234. Authorization: 'Bearer ' + getAccessToken(),
  235. 'tenant-id': getTenantId()
  236. }
  237. uploadDisabled.value = true
  238. uploadRef.value!.submit()
  239. }
  240. // 文件上传成功
  241. const handleFileSuccess = (response: any): void => {
  242. if (response.code !== 0) {
  243. message.error(response.msg)
  244. return
  245. }
  246. importDialogVisible.value = false
  247. uploadDisabled.value = false
  248. const data = response.data
  249. let text = '上传成功数量:' + data.createUsernames.length + ';'
  250. for (let username of data.createUsernames) {
  251. text += '< ' + username + ' >'
  252. }
  253. text += '更新成功数量:' + data.updateUsernames.length + ';'
  254. for (const username of data.updateUsernames) {
  255. text += '< ' + username + ' >'
  256. }
  257. text += '更新失败数量:' + Object.keys(data.failureUsernames).length + ';'
  258. for (const username in data.failureUsernames) {
  259. text += '< ' + username + ': ' + data.failureUsernames[username] + ' >'
  260. }
  261. message.alert(text)
  262. getList()
  263. }
  264. // 文件数超出提示
  265. const handleExceed = (): void => {
  266. message.error('最多只能上传一个文件!')
  267. }
  268. // 上传错误提示
  269. const excelUploadError = (): void => {
  270. message.error('导入数据失败,请您重新上传!')
  271. }
  272. // ========== 初始化 ==========
  273. onMounted(async () => {
  274. await getPostOptions()
  275. await getList()
  276. await getTree()
  277. })
  278. </script>
  279. <template>
  280. <div class="flex">
  281. <el-card class="w-1/5 user" :gutter="12" shadow="always">
  282. <template #header>
  283. <div class="card-header">
  284. <span>部门列表</span>
  285. <el-button link class="button" type="primary" @click="handleDeptEdit">
  286. 修改部门
  287. </el-button>
  288. </div>
  289. </template>
  290. <el-input v-model="filterText" placeholder="搜索部门" />
  291. <el-tree
  292. ref="treeRef"
  293. node-key="id"
  294. default-expand-all
  295. :data="deptOptions"
  296. :props="defaultProps"
  297. :highlight-current="true"
  298. :filter-node-method="filterNode"
  299. :expand-on-click-node="false"
  300. @node-click="handleDeptNodeClick"
  301. />
  302. </el-card>
  303. <!-- 搜索工作区 -->
  304. <el-card class="w-4/5 user" style="margin-left: 10px" :gutter="12" shadow="hover">
  305. <template #header>
  306. <div class="card-header">
  307. <span>{{ tableTitle }}</span>
  308. </div>
  309. </template>
  310. <Search
  311. :schema="allSchemas.searchSchema"
  312. @search="setSearchParams"
  313. @reset="setSearchParams"
  314. ref="searchForm"
  315. />
  316. <!-- 操作工具栏 -->
  317. <div class="mb-10px">
  318. <el-button type="primary" v-hasPermi="['system:user:create']" @click="handleAdd">
  319. <Icon icon="ep:zoom-in" class="mr-5px" /> {{ t('action.add') }}
  320. </el-button>
  321. <el-button
  322. type="info"
  323. v-hasPermi="['system:user:import']"
  324. @click="importDialogVisible = true"
  325. >
  326. <Icon icon="ep:upload" class="mr-5px" /> {{ t('action.import') }}
  327. </el-button>
  328. <el-button
  329. type="warning"
  330. v-hasPermi="['system:user:export']"
  331. @click="exportList('用户数据.xls')"
  332. >
  333. <Icon icon="ep:download" class="mr-5px" /> {{ t('action.export') }}
  334. </el-button>
  335. </div>
  336. <!-- 列表 -->
  337. <Table
  338. :columns="allSchemas.tableColumns"
  339. :selection="false"
  340. :data="tableObject.tableList"
  341. :loading="tableObject.loading"
  342. :pagination="{
  343. total: tableObject.total
  344. }"
  345. v-model:pageSize="tableObject.pageSize"
  346. v-model:currentPage="tableObject.currentPage"
  347. @register="register"
  348. >
  349. <template #status="{ row }">
  350. <el-switch
  351. v-model="row.status"
  352. :active-value="0"
  353. :inactive-value="1"
  354. @change="handleStatusChange(row)"
  355. />
  356. </template>
  357. <template #loginDate="{ row }">
  358. <span>{{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
  359. </template>
  360. <template #action="{ row }">
  361. <el-button
  362. link
  363. type="primary"
  364. v-hasPermi="['system:user:update']"
  365. @click="handleUpdate(row)"
  366. >
  367. <Icon icon="ep:edit" class="mr-1px" /> {{ t('action.edit') }}
  368. </el-button>
  369. <el-button
  370. link
  371. type="primary"
  372. v-hasPermi="['system:user:update']"
  373. @click="handleDetail(row)"
  374. >
  375. <Icon icon="ep:view" class="mr-1px" /> {{ t('action.detail') }}
  376. </el-button>
  377. <el-button
  378. link
  379. type="primary"
  380. v-hasPermi="['system:user:update-password']"
  381. @click="handleResetPwd(row)"
  382. >
  383. <Icon icon="ep:key" class="mr-1px" /> 重置密码
  384. </el-button>
  385. <el-button
  386. link
  387. type="primary"
  388. v-hasPermi="['system:permission:assign-user-role']"
  389. @click="handleRole(row)"
  390. >
  391. <Icon icon="ep:key" class="mr-1px" /> 分配角色
  392. </el-button>
  393. <el-button
  394. link
  395. type="primary"
  396. v-hasPermi="['system:user:delete']"
  397. @click="delList(row.id, false)"
  398. >
  399. <Icon icon="ep:delete" class="mr-1px" /> {{ t('action.del') }}
  400. </el-button>
  401. </template>
  402. </Table>
  403. </el-card>
  404. </div>
  405. <XModal v-model="dialogVisible" :title="dialogTitle">
  406. <!-- 对话框(添加 / 修改) -->
  407. <Form
  408. v-if="['create', 'update'].includes(actionType)"
  409. :rules="rules"
  410. :schema="allSchemas.formSchema"
  411. ref="formRef"
  412. >
  413. <template #deptId>
  414. <el-tree-select
  415. node-key="id"
  416. v-model="deptId"
  417. :props="defaultProps"
  418. :data="deptOptions"
  419. check-strictly
  420. />
  421. </template>
  422. <template #postIds>
  423. <el-select v-model="postIds" multiple :placeholder="t('common.selectText')">
  424. <el-option
  425. v-for="item in postOptions"
  426. :key="item.id"
  427. :label="item.name"
  428. :value="item.id"
  429. />
  430. </el-select>
  431. </template>
  432. </Form>
  433. <!-- 对话框(详情) -->
  434. <Descriptions
  435. v-if="actionType === 'detail'"
  436. :schema="allSchemas.detailSchema"
  437. :data="detailRef"
  438. >
  439. <template #deptId="{ row }">
  440. <span>{{ row.dept?.name }}</span>
  441. </template>
  442. <template #postIds="{ row }">
  443. <el-tag v-for="(post, index) in row.postIds" :key="index" index="">
  444. <template v-for="postObj in postOptions">
  445. {{ post === postObj.id ? postObj.name : '' }}
  446. </template>
  447. </el-tag>
  448. </template>
  449. </Descriptions>
  450. <!-- 操作按钮 -->
  451. <template #footer>
  452. <!-- 按钮:保存 -->
  453. <XButton
  454. v-if="['create', 'update'].includes(actionType)"
  455. type="primary"
  456. :title="t('action.save')"
  457. :loading="loading"
  458. @click="submitForm()"
  459. />
  460. <!-- 按钮:关闭 -->
  461. <XButton :loading="loading" :title="t('dialog.close')" @click="dialogVisible = false" />
  462. </template>
  463. </XModal>
  464. <!-- 分配用户角色 -->
  465. <XModal v-model="roleDialogVisible" title="分配角色">
  466. <el-form :model="userRole" label-width="80px">
  467. <el-form-item label="用户名称">
  468. <el-input v-model="userRole.username" :disabled="true" />
  469. </el-form-item>
  470. <el-form-item label="用户昵称">
  471. <el-input v-model="userRole.nickname" :disabled="true" />
  472. </el-form-item>
  473. <el-form-item label="角色">
  474. <el-transfer
  475. v-model="userRole.roleIds"
  476. :titles="['角色列表', '已选择']"
  477. :props="{
  478. key: 'id',
  479. label: 'name'
  480. }"
  481. :data="roleOptions"
  482. />
  483. </el-form-item>
  484. </el-form>
  485. <!-- 操作按钮 -->
  486. <template #footer>
  487. <el-button type="primary" :loading="loading" @click="submitRole">
  488. {{ t('action.save') }}
  489. </el-button>
  490. <el-button @click="roleDialogVisible = false">{{ t('dialog.close') }}</el-button>
  491. </template>
  492. </XModal>
  493. <!-- 导入 -->
  494. <XModal v-model="importDialogVisible" :title="importDialogTitle">
  495. <el-form class="drawer-multiColumn-form" label-width="150px">
  496. <el-form-item label="模板下载 :">
  497. <el-button type="primary" @click="handleImportTemp">
  498. <Icon icon="ep:download" />
  499. 点击下载
  500. </el-button>
  501. </el-form-item>
  502. <el-form-item label="文件上传 :">
  503. <el-upload
  504. ref="uploadRef"
  505. :action="updateUrl + '?updateSupport=' + updateSupport"
  506. :headers="uploadHeaders"
  507. :drag="true"
  508. :limit="1"
  509. :multiple="true"
  510. :show-file-list="true"
  511. :disabled="uploadDisabled"
  512. :before-upload="beforeExcelUpload"
  513. :on-exceed="handleExceed"
  514. :on-success="handleFileSuccess"
  515. :on-error="excelUploadError"
  516. :auto-upload="false"
  517. accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  518. >
  519. <Icon icon="ep:upload-filled" />
  520. <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
  521. <template #tip>
  522. <div class="el-upload__tip">请上传 .xls , .xlsx 标准格式文件</div>
  523. </template>
  524. </el-upload>
  525. </el-form-item>
  526. <el-form-item label="是否更新已经存在的用户数据:">
  527. <el-checkbox v-model="updateSupport" />
  528. </el-form-item>
  529. </el-form>
  530. <template #footer>
  531. <el-button type="primary" @click="submitFileForm">
  532. <Icon icon="ep:upload-filled" />
  533. {{ t('action.save') }}
  534. </el-button>
  535. <el-button @click="importDialogVisible = false">{{ t('dialog.close') }}</el-button>
  536. </template>
  537. </XModal>
  538. </template>
  539. <style scoped>
  540. .user {
  541. height: 900px;
  542. max-height: 960px;
  543. }
  544. .card-header {
  545. display: flex;
  546. justify-content: space-between;
  547. align-items: center;
  548. }
  549. </style>