index.vue 18 KB

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