index.vue 17 KB

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