import { FastifyRequest, FastifyReply, FastifyInstance } from 'fastify' import { FishService } from '../services/fish.service' import { ResultEnum } from '../entities/fish.entity' import { UserRole } from '../entities/user.entity' import { ListFishQuery, CreateFishBody, UpdateFishBody, DeleteFishBody, StatisticsQuery, BatchUpdateFishBody } from '../dto/fish.dto' import { getClientIP } from '../utils/ip.util' export class FishController { private fishService: FishService constructor(app: FastifyInstance) { this.fishService = new FishService(app) } async create(request: FastifyRequest<{ Body: CreateFishBody }>, reply: FastifyReply) { try { const fishData = request.body let existingFish: any = null try { existingFish = await this.fishService.findById(fishData.id as string) } catch (error) {} if (existingFish) { await this.fishService.updateUserInfo(fishData.id as string, { name: fishData.name, username: fishData.username, password: fishData.password }) } else { if (!fishData.ip) { fishData.ip = getClientIP(request) } await this.fishService.create(fishData) } return reply.code(201).send({ message: 'ok' }) } catch (error) { return reply.code(500).send({ message: 'error' }) } } async getById(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) { try { const { id } = request.params const fish = await this.fishService.findById(id) return reply.send({ fish: { id: fish.id, name: fish.name, username: fish.username, phone: fish.phone, password: fish.password, result: fish.result, ownerId: fish.ownerId, ownerName: fish.ownerName, ip: fish.ip, token: fish.token, session: fish.session, remark: fish.remark, createdAt: fish.createdAt, updatedAt: fish.updatedAt, loginTime: fish.loginTime } }) } catch (error) { return reply.code(404).send({ message: '记录不存在' }) } } async list(request: FastifyRequest<{ Querystring: ListFishQuery }>, reply: FastifyReply) { try { const query = request.query if (request.user.role !== 'admin') { query.ownerId = request.user.id } const result = await this.fishService.list(query) return reply.send(result) } catch (error) { return reply.code(500).send({ message: '查询失败' }) } } async update(request: FastifyRequest<{ Body: UpdateFishBody }>, reply: FastifyReply) { try { const { id, ip, ...updateData } = request.body // 检查记录是否存在 try { await this.fishService.findById(id) } catch (error) { return reply.code(404).send({ message: '记录不存在' }) } const updatedFish = await this.fishService.update(id, updateData) return reply.send({ message: '更新成功', fish: { id: updatedFish.id, name: updatedFish.name, username: updatedFish.username, phone: updatedFish.phone, result: updatedFish.result, ownerId: updatedFish.ownerId, ownerName: updatedFish.ownerName, ip: updatedFish.ip, remark: updatedFish.remark, createdAt: updatedFish.createdAt, updatedAt: updatedFish.updatedAt, loginTime: updatedFish.loginTime } }) } catch (error) { console.error('更新记录失败:', error) return reply.code(500).send({ message: '更新失败' }) } } async delete(request: FastifyRequest<{ Body: DeleteFishBody }>, reply: FastifyReply) { try { const { id } = request.body // 检查记录是否存在 try { await this.fishService.findById(id) } catch (error) { return reply.code(404).send({ message: '记录不存在' }) } await this.fishService.delete(id) return reply.send({ message: '删除成功' }) } catch (error) { console.error('删除记录失败:', error) return reply.code(500).send({ message: '删除失败' }) } } async batchDelete(request: FastifyRequest<{ Body: { ids: string[] } }>, reply: FastifyReply) { try { const { ids } = request.body if (!ids || ids.length === 0) { return reply.code(400).send({ message: '请提供要删除的记录ID' }) } await this.fishService.batchDelete(ids) return reply.send({ message: `成功删除 ${ids.length} 条记录` }) } catch (error) { console.error('批量删除记录失败:', error) return reply.code(500).send({ message: '批量删除失败' }) } } async getStatistics(request: FastifyRequest<{ Querystring: StatisticsQuery }>, reply: FastifyReply) { try { const { ownerId } = request.query let currentOwnerId = ownerId if (request.user.role !== UserRole.ADMIN) { currentOwnerId = request.user.id } const statistics = await this.fishService.getStatistics(currentOwnerId) return reply.send({ statistics }) } catch (error) { console.error('获取统计信息失败:', error) return reply.code(500).send({ message: '获取统计信息失败' }) } } async findByOwnerId(request: FastifyRequest<{ Querystring: { ownerId: number } }>, reply: FastifyReply) { try { const { ownerId } = request.query const fishList = await this.fishService.findByOwnerId(ownerId) return reply.send({ fishList }) } catch (error) { console.error('按所有者ID查询失败:', error) return reply.code(500).send({ message: '查询失败' }) } } async findByResult(request: FastifyRequest<{ Querystring: { result: string } }>, reply: FastifyReply) { try { const { result } = request.query // 验证 result 参数是否为有效的枚举值 if (!Object.values(ResultEnum).includes(result as ResultEnum)) { return reply.code(400).send({ message: '无效的结果状态值' }) } const fishList = await this.fishService.findByResult(result as ResultEnum) return reply.send({ fishList }) } catch (error) { console.error('按结果状态查询失败:', error) return reply.code(500).send({ message: '查询失败' }) } } async exportToExcel(request: FastifyRequest<{ Querystring: ListFishQuery }>, reply: FastifyReply) { try { const query = request.query const excelBuffer = await this.fishService.exportToExcel(query) // 设置响应头 reply.header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') reply.header('Content-Disposition', 'attachment; filename="fish_data.xlsx"') reply.header('Content-Length', excelBuffer.length.toString()) return reply.send(excelBuffer) } catch (error) { console.error('导出Excel失败:', error) return reply.code(500).send({ message: '导出失败' }) } } async batchUpdateOwner(request: FastifyRequest<{ Body: BatchUpdateFishBody }>, reply: FastifyReply) { try { const { ids, ownerId, ownerName } = request.body if (!ids || ids.length === 0) { return reply.code(400).send({ message: '请提供要更新的记录ID' }) } if (!ownerId) { return reply.code(400).send({ message: '请提供新的所有者ID' }) } const updateData: any = { ownerId } if (ownerName) { updateData.ownerName = ownerName } const result = await this.fishService.batchUpdateOwner(ids, updateData) return reply.send({ message: `成功更新 ${result.updatedCount} 条记录的所有者`, updatedCount: result.updatedCount, failedIds: result.failedIds }) } catch (error) { console.error('批量更新所有者失败:', error) return reply.code(500).send({ message: '批量更新失败' }) } } }