index.vue 17 KB

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