Files
WXProgram/miniprogram/pages/staff/employee-management.ts

635 lines
14 KiB
TypeScript
Raw Normal View History

2025-10-19 23:38:54 +08:00
// 员工管理页面 - 集成到管理员界面
import { EmployeeInfo } from '../../types';
import employeeService from '../../services/employeeService';
import { Role, getRoleOptions } from '../../utils/roleUtils';
2025-10-26 13:15:04 +08:00
import { avatarCache } from '../../utils/avatarCache';
import { API_BASE_URL } from '../../services/apiService';
2025-10-19 23:38:54 +08:00
Page({
data: {
// 员工列表
employees: [] as EmployeeInfo[],
filteredEmployees: [] as EmployeeInfo[],
// 页面状态
2025-10-26 13:15:04 +08:00
currentTab: 'list', // list: 列表页, add: 添加页, edit: 编辑页
2025-10-19 23:38:54 +08:00
loading: false,
// 添加员工表单数据
addForm: {
name: '',
phone: '',
role: Role.DELIVERY_PERSON
},
2025-10-26 13:15:04 +08:00
// 编辑员工表单数据
editForm: {
id: 0,
name: '',
phone: '',
role: Role.DELIVERY_PERSON,
avatarUrl: ''
},
2025-10-19 23:38:54 +08:00
// 错误信息
errorMessage: '',
successMessage: '',
// 搜索关键词
searchKeyword: '',
// 角色选项
roleOptions: getRoleOptions(),
// 用户信息
2025-10-26 13:15:04 +08:00
userInfo: null as any,
// 临时头像路径(用于头像上传)
tempAvatarPath: ''
2025-10-19 23:38:54 +08:00
},
onLoad() {
this.getUserInfo();
this.loadEmployees();
},
onShow() {
2025-10-26 13:15:04 +08:00
// 只在页面显示时检查是否需要刷新数据,避免频繁请求
if (this.data.employees.length === 0) {
this.loadEmployees();
}
2025-10-19 23:38:54 +08:00
},
/**
*
*/
getUserInfo() {
const app = getApp<any>();
if (app.globalData.userInfo) {
const userInfo = app.globalData.userInfo;
this.setData({ userInfo });
// 验证是否为管理员
if (userInfo.role !== 'ADMIN') {
wx.showToast({
title: '无权限访问',
icon: 'none'
});
wx.navigateBack();
}
}
},
2025-10-26 13:15:04 +08:00
/**
* URL
* @param avatarPath
* @returns URL
*/
getFullAvatarUrl(avatarPath: string | undefined): string {
if (!avatarPath) {
return '/images/user-avatar.png';
}
// 如果已经是完整URL直接返回
if (avatarPath.startsWith('http')) {
return avatarPath;
}
// 将相对路径转换为完整URL
return `${API_BASE_URL}${avatarPath}`;
},
/**
*
*/
async getLocalAvatarPath(avatarPath: string | undefined): Promise<string> {
if (!avatarPath) {
return '/images/user-avatar.png';
}
try {
// 使用头像缓存获取本地文件路径
const fullAvatarUrl = this.getFullAvatarUrl(avatarPath);
const localAvatarPath = await avatarCache.getAvatarPath(fullAvatarUrl);
return localAvatarPath;
} catch (error) {
console.error('获取头像缓存失败:', error);
// 如果缓存失败回退到远程URL
return this.getFullAvatarUrl(avatarPath);
}
},
2025-10-19 23:38:54 +08:00
/**
*
*/
async loadEmployees() {
this.setData({
loading: true,
errorMessage: '',
successMessage: ''
});
try {
const employees = await employeeService.getEmployees();
2025-10-26 13:15:04 +08:00
// 为每个员工获取本地缓存的头像路径
const employeesWithAvatars = await Promise.all(
employees.map(async (employee) => {
const localAvatarPath = await this.getLocalAvatarPath(employee.avatarPath);
return {
...employee,
fullAvatarUrl: localAvatarPath
};
})
);
2025-10-19 23:38:54 +08:00
// 获取过滤后的员工列表
2025-10-26 13:15:04 +08:00
const filteredEmployees = this.getFilteredEmployees(employeesWithAvatars);
2025-10-19 23:38:54 +08:00
this.setData({
2025-10-26 13:15:04 +08:00
employees: employeesWithAvatars,
2025-10-19 23:38:54 +08:00
filteredEmployees,
loading: false
});
} catch (error) {
console.error('加载员工列表失败:', error);
this.setData({
loading: false,
errorMessage: '加载员工列表失败,请稍后重试'
});
}
},
/**
*
*/
switchTab(e: any) {
const tab = e.currentTarget.dataset.tab;
this.setData({
currentTab: tab,
errorMessage: '',
successMessage: ''
});
2025-10-26 13:15:04 +08:00
// 只在切换到列表页且没有数据时才加载,避免频繁请求
if (tab === 'list' && this.data.employees.length === 0) {
2025-10-19 23:38:54 +08:00
this.loadEmployees();
}
},
/**
*
*/
onFormInput(e: any) {
const { field } = e.currentTarget.dataset;
const value = e.detail.value;
this.setData({
[`addForm.${field}`]: value,
errorMessage: '',
successMessage: ''
});
},
/**
*
*/
onRoleChange(e: any) {
const index = e.detail.value;
const selectedRole = this.data.roleOptions[index].value;
this.setData({
'addForm.role': selectedRole
});
},
/**
*
*/
validateForm(): boolean {
const { name, phone, role } = this.data.addForm;
if (!name.trim()) {
this.setData({
errorMessage: '请输入员工姓名'
});
return false;
}
if (!phone.trim()) {
this.setData({
2025-10-21 21:51:51 +08:00
errorMessage: '请输入员工工号'
2025-10-19 23:38:54 +08:00
});
return false;
}
2025-10-21 21:51:51 +08:00
// 简单的工号格式验证
const phoneRegex = /^\d+$/;
2025-10-19 23:38:54 +08:00
if (!phoneRegex.test(phone)) {
this.setData({
2025-10-21 21:51:51 +08:00
errorMessage: '工号只能包含数字'
2025-10-19 23:38:54 +08:00
});
return false;
}
if (!role) {
this.setData({
errorMessage: '请选择员工角色'
});
return false;
}
return true;
},
/**
*
*/
async submitAddForm() {
if (!this.validateForm()) {
return;
}
this.setData({
loading: true,
errorMessage: '',
successMessage: ''
});
try {
await employeeService.addEmployee(this.data.addForm);
this.setData({
loading: false,
successMessage: '员工添加成功',
addForm: {
name: '',
phone: '',
role: Role.DELIVERY_PERSON
}
});
// 添加成功后自动切换到列表页
setTimeout(() => {
this.setData({
currentTab: 'list'
});
this.loadEmployees();
}, 1500);
} catch (error) {
console.error('添加员工失败:', error);
this.setData({
loading: false,
errorMessage: (error as Error).message || '添加员工失败,请稍后重试'
});
}
},
2025-10-26 13:15:04 +08:00
/**
*
*/
editEmployee(e: any) {
const employeeId = e.currentTarget.dataset.id;
const employee = this.data.employees.find(emp => emp.id === employeeId);
if (employee) {
this.setData({
editForm: {
id: employee.id || 0,
name: employee.name || '',
phone: employee.phone || '',
role: employee.role || Role.DELIVERY_PERSON,
avatarUrl: ''
},
currentTab: 'edit'
});
}
},
/**
*
*/
async submitEditForm() {
if (!this.validateEditForm()) {
return;
}
this.setData({
loading: true,
errorMessage: '',
successMessage: ''
});
try {
// 调用更新员工的API方法
await employeeService.updateEmployee(this.data.editForm.id, {
name: this.data.editForm.name,
phone: this.data.editForm.phone,
role: this.data.editForm.role
});
// 如果有新头像,上传头像
if (this.data.tempAvatarPath) {
try {
const result = await employeeService.uploadAvatar(this.data.editForm.id, this.data.tempAvatarPath);
if (result.success && result.avatarUrl) {
// 更新头像URL
this.setData({
'editForm.avatarUrl': result.avatarUrl
});
}
} catch (avatarError) {
console.error('上传头像失败:', avatarError);
wx.showToast({
title: '头像上传失败',
icon: 'error'
});
}
}
this.setData({
loading: false,
successMessage: '员工更新成功',
currentTab: 'list',
tempAvatarPath: ''
});
// 重新加载员工列表
this.loadEmployees();
} catch (error) {
console.error('更新员工失败:', error);
this.setData({
loading: false,
errorMessage: '更新员工失败,请重试'
});
}
},
/**
*
*/
chooseAvatar() {
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['album'],
maxDuration: 30,
camera: 'back',
success: (res) => {
if (res.tempFiles && res.tempFiles.length > 0) {
const tempFilePath = res.tempFiles[0].tempFilePath;
this.setData({
'editForm.avatarUrl': tempFilePath,
tempAvatarPath: tempFilePath
});
}
},
fail: (err) => {
console.error('选择头像失败:', err);
wx.showToast({
title: '选择头像失败',
icon: 'error'
});
}
});
},
/**
*
*/
takePhoto() {
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['camera'],
maxDuration: 30,
camera: 'back',
success: (res) => {
if (res.tempFiles && res.tempFiles.length > 0) {
const tempFilePath = res.tempFiles[0].tempFilePath;
this.setData({
'editForm.avatarUrl': tempFilePath,
tempAvatarPath: tempFilePath
});
}
},
fail: (err) => {
console.error('拍照失败:', err);
wx.showToast({
title: '拍照失败',
icon: 'error'
});
}
});
},
/**
*
*/
validateEditForm(): boolean {
const { name, phone, role } = this.data.editForm;
if (!name.trim()) {
this.setData({
errorMessage: '请输入员工姓名'
});
return false;
}
if (!phone.trim()) {
this.setData({
errorMessage: '请输入员工工号'
});
return false;
}
// 简单的工号格式验证
const phoneRegex = /^\d+$/;
if (!phoneRegex.test(phone)) {
this.setData({
errorMessage: '工号只能包含数字'
});
return false;
}
if (!role) {
this.setData({
errorMessage: '请选择员工角色'
});
return false;
}
return true;
},
/**
*
*/
cancelEdit() {
this.setData({
currentTab: 'list',
errorMessage: '',
successMessage: ''
});
},
/**
*
*/
onEditFormInput(e: any) {
const { field } = e.currentTarget.dataset;
const value = e.detail.value;
this.setData({
[`editForm.${field}`]: value,
errorMessage: '',
successMessage: ''
});
},
/**
*
*/
onEditRoleChange(e: any) {
const index = e.detail.value;
const selectedRole = this.data.roleOptions[index].value;
this.setData({
'editForm.role': selectedRole
});
},
2025-10-19 23:38:54 +08:00
/**
*
*/
async deleteEmployee(e: any) {
const employeeId = e.currentTarget.dataset.id;
const employee = this.data.employees.find(emp => emp.id === employeeId);
if (!employee) {
return;
}
wx.showModal({
title: '确认删除',
content: `确定要删除员工 ${employee.name} (${employee.phone}) 吗?此操作不可恢复。`,
confirmText: '删除',
confirmColor: '#ff4d4f',
cancelText: '取消',
success: async (res) => {
if (res.confirm) {
this.setData({
loading: true,
errorMessage: '',
successMessage: ''
});
try {
const result = await employeeService.deleteEmployee(employeeId);
if (result.success) {
this.setData({
loading: false,
successMessage: result.message || '员工删除成功'
});
// 重新加载员工列表
this.loadEmployees();
} else {
this.setData({
loading: false,
errorMessage: result.message || '删除员工失败'
});
}
} catch (error) {
console.error('删除员工失败:', error);
this.setData({
loading: false,
errorMessage: '删除员工失败,请稍后重试'
});
}
}
}
});
},
/**
*
*/
onSearchInput(e: any) {
const keyword = e.detail.value;
this.setData({
searchKeyword: keyword
});
// 更新过滤后的员工列表
this.updateFilteredEmployees();
},
/**
*
*/
updateFilteredEmployees() {
const { employees } = this.data;
const filteredEmployees = this.getFilteredEmployees(employees);
this.setData({
filteredEmployees
});
},
/**
*
*/
getFilteredEmployees(employees?: EmployeeInfo[]): EmployeeInfo[] {
const { searchKeyword } = this.data;
// 如果employees为空返回空数组
if (!employees || !Array.isArray(employees)) {
return [];
}
2025-10-26 13:15:04 +08:00
// 显示所有员工,包括当前用户
let filteredEmployees = employees;
2025-10-19 23:38:54 +08:00
// 更严格的搜索关键词检查
if (!searchKeyword || typeof searchKeyword !== 'string' || !searchKeyword.trim()) {
return filteredEmployees;
}
const keyword = searchKeyword.toLowerCase();
return filteredEmployees.filter(emp =>
emp.name.toLowerCase().includes(keyword) ||
emp.phone.includes(keyword) ||
(emp.role || '').toLowerCase().includes(keyword)
);
},
/**
*
*/
getRoleText(role: string): string {
const roleMap: Record<string, string> = {
'ADMIN': '管理员',
'DELIVERY_PERSON': '配送员',
'EMPLOYEE': '员工'
};
return roleMap[role] || role;
},
/**
*
*/
clearMessages() {
this.setData({
errorMessage: '',
successMessage: ''
});
},
/**
*
*/
goBack() {
wx.navigateBack();
}
});