index.vue 17 KB

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