Files
WXProgram/dist/pages/staff/employee-management.js

536 lines
16 KiB
JavaScript
Raw Permalink Normal View History

2025-10-26 13:15:04 +08:00
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const employeeService_1 = __importDefault(require("../../services/employeeService"));
const roleUtils_1 = require("../../utils/roleUtils");
Page({
data: {
// 员工列表
employees: [],
filteredEmployees: [],
// 页面状态
currentTab: 'list', // list: 列表页, add: 添加页, edit: 编辑页
loading: false,
// 添加员工表单数据
addForm: {
name: '',
phone: '',
role: roleUtils_1.Role.DELIVERY_PERSON
},
// 编辑员工表单数据
editForm: {
id: 0,
name: '',
phone: '',
role: roleUtils_1.Role.DELIVERY_PERSON,
avatarUrl: ''
},
// 错误信息
errorMessage: '',
successMessage: '',
// 搜索关键词
searchKeyword: '',
// 角色选项
roleOptions: (0, roleUtils_1.getRoleOptions)(),
// 用户信息
userInfo: null,
// 临时头像路径(用于头像上传)
tempAvatarPath: ''
},
onLoad() {
this.getUserInfo();
this.loadEmployees();
},
onShow() {
// 只在页面显示时检查是否需要刷新数据,避免频繁请求
if (this.data.employees.length === 0) {
this.loadEmployees();
}
},
/**
* 获取用户信息
*/
getUserInfo() {
const app = getApp();
if (app.globalData.userInfo) {
const userInfo = app.globalData.userInfo;
this.setData({ userInfo });
// 验证是否为管理员
if (userInfo.role !== 'ADMIN') {
wx.showToast({
title: '无权限访问',
icon: 'none'
});
wx.navigateBack();
}
}
},
/**
* 加载员工列表
*/
async loadEmployees() {
this.setData({
loading: true,
errorMessage: '',
successMessage: ''
});
try {
const employees = await employeeService_1.default.getEmployees();
// 为每个员工获取头像URL
const employeesWithAvatars = await Promise.all(employees.map(async (employee) => {
try {
const avatarUrl = await employeeService_1.default.getAvatarUrl(employee.id);
return {
...employee,
avatarUrl: avatarUrl
};
}
catch (error) {
console.error(`获取员工 ${employee.id} 头像失败:`, error);
return {
...employee,
avatarUrl: ''
};
}
}));
// 获取过滤后的员工列表
const filteredEmployees = this.getFilteredEmployees(employeesWithAvatars);
this.setData({
employees: employeesWithAvatars,
filteredEmployees,
loading: false
});
}
catch (error) {
console.error('加载员工列表失败:', error);
this.setData({
loading: false,
errorMessage: '加载员工列表失败,请稍后重试'
});
}
},
/**
* 切换页面标签
*/
switchTab(e) {
const tab = e.currentTarget.dataset.tab;
this.setData({
currentTab: tab,
errorMessage: '',
successMessage: ''
});
// 只在切换到列表页且没有数据时才加载,避免频繁请求
if (tab === 'list' && this.data.employees.length === 0) {
this.loadEmployees();
}
},
/**
* 处理添加员工表单输入
*/
onFormInput(e) {
const { field } = e.currentTarget.dataset;
const value = e.detail.value;
this.setData({
[`addForm.${field}`]: value,
errorMessage: '',
successMessage: ''
});
},
/**
* 处理角色选择
*/
onRoleChange(e) {
const index = e.detail.value;
const selectedRole = this.data.roleOptions[index].value;
this.setData({
'addForm.role': selectedRole
});
},
/**
* 验证表单数据
*/
validateForm() {
const { name, phone, role } = this.data.addForm;
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;
},
/**
* 提交添加员工表单
*/
async submitAddForm() {
if (!this.validateForm()) {
return;
}
this.setData({
loading: true,
errorMessage: '',
successMessage: ''
});
try {
await employeeService_1.default.addEmployee(this.data.addForm);
this.setData({
loading: false,
successMessage: '员工添加成功',
addForm: {
name: '',
phone: '',
role: roleUtils_1.Role.DELIVERY_PERSON
}
});
// 添加成功后自动切换到列表页
setTimeout(() => {
this.setData({
currentTab: 'list'
});
this.loadEmployees();
}, 1500);
}
catch (error) {
console.error('添加员工失败:', error);
this.setData({
loading: false,
errorMessage: error.message || '添加员工失败,请稍后重试'
});
}
},
/**
* 编辑员工
*/
editEmployee(e) {
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 || roleUtils_1.Role.DELIVERY_PERSON,
avatarUrl: employee.avatarUrl || ''
},
currentTab: 'edit'
});
}
},
/**
* 提交编辑员工表单
*/
async submitEditForm() {
if (!this.validateEditForm()) {
return;
}
this.setData({
loading: true,
errorMessage: '',
successMessage: ''
});
try {
// 调用更新员工的API方法
await employeeService_1.default.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_1.default.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() {
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) {
const { field } = e.currentTarget.dataset;
const value = e.detail.value;
this.setData({
[`editForm.${field}`]: value,
errorMessage: '',
successMessage: ''
});
},
/**
* 处理编辑角色选择
*/
onEditRoleChange(e) {
const index = e.detail.value;
const selectedRole = this.data.roleOptions[index].value;
this.setData({
'editForm.role': selectedRole
});
},
/**
* 删除员工
*/
async deleteEmployee(e) {
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_1.default.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) {
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) {
const { searchKeyword } = this.data;
// 如果employees为空返回空数组
if (!employees || !Array.isArray(employees)) {
return [];
}
// 显示所有员工,包括当前用户
let filteredEmployees = employees;
// 更严格的搜索关键词检查
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) {
const roleMap = {
'ADMIN': '管理员',
'DELIVERY_PERSON': '配送员',
'EMPLOYEE': '员工'
};
return roleMap[role] || role;
},
/**
* 清空消息
*/
clearMessages() {
this.setData({
errorMessage: '',
successMessage: ''
});
},
/**
* 返回上一页
*/
goBack() {
wx.navigateBack();
}
});