index.vue 17 KB

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