import { UserDTO, UserRoleDTO } from "@cdk/dtos/user.dto"; import { ApiService } from "@admin/app/services"; import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, TemplateRef, ViewChild, } from "@angular/core"; import { FormControl, FormGroup } from "@angular/forms"; import { ActivatedRoute } from "@angular/router"; import { AnyObject, FormValidators, TableListOption, Utils } from "@cdk/public-api"; import { MD5 } from "crypto-js"; import { NzMessageService } from "ng-zorro-antd/message"; import { NzModalService } from "ng-zorro-antd/modal"; import { lastValueFrom } from "rxjs"; @Component({ selector: "app-user-list", templateUrl: "./user-list.component.html", styleUrls: ["./user-list.component.less"], }) export class UserListComponent implements OnChanges { constructor( private api: ApiService, private route: ActivatedRoute, private modal: NzModalService, private msg: NzMessageService ) {} @ViewChild("userFormTpl") public userFormTpl!: TemplateRef; @Input() users: UserDTO[] = []; @Input() role!: UserRoleDTO; @Output() onReload = new EventEmitter(); searchValue = ""; visibledUsers: UserDTO[] = []; public userFrom = new FormGroup({ uid: new FormControl("", [FormValidators.required("请输入账号")]), name: new FormControl("", [FormValidators.required("请输入姓名")]), password: new FormControl("", [FormValidators.required("请输入密码")]), }); ngOnInit(): void {} ngOnChanges(changes: SimpleChanges): void { const u = changes["users"]?.currentValue; if (Array.isArray(u)) { this.onSearch(this.searchValue); } } onSearch(kw: string) { this.visibledUsers = this.users.filter((f) => f.name.includes(kw) || f.uid.includes(kw)); } deleteItem(uid: string) { this.modal.confirm({ nzTitle: "警告", nzContent: "是否要删除该用户?", nzOkDanger: true, nzOnOk: async () => { const res = await lastValueFrom(this.api.deleteUser(uid)); if (res.success) { this.msg.success(res.desc); this.onReload.emit(); return true; } return false; }, }); } resetUserForm() { this.userFrom.reset(); } openForm(item?: any) { if (item) { this.userFrom.patchValue(item); } this.modal.create({ nzTitle: item ? "编辑用户" : "新增用户", nzContent: this.userFormTpl, nzOnCancel: () => { this.resetUserForm(); }, nzOnOk: async () => { if (Utils.validateFormGroup(this.userFrom)) { const user = { ...this.userFrom.value, roleId: this.role.id }; user["password"] = MD5(user.password!).toString().substring(16).toUpperCase(); let notExist = true; if ((item && item.uid !== user.uid) || !item) { const check = await lastValueFrom(this.api.checkUid(user.uid!)); notExist = check.body; } if (notExist) { const res = await lastValueFrom(this.api.saveUser(user, Boolean(item))); this.msg.success(res.desc); this.onReload.emit(); this.resetUserForm(); return true; } else { this.msg.error("账号重复"); return false; } } return false; }, }); } }