index.vue 17 KB

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