import { Provide, Inject } from "@midwayjs/core"; import { InjectRepository } from "@midwayjs/sequelize"; import SysDict from "../entity/sysDict.entity"; import { Op } from "sequelize"; @Provide() export class DictService { @InjectRepository(SysDict) dictModel!: typeof SysDict; async list(query: { page?: number; pageSize?: number; dictType?: string; keyword?: string; status?: number; }): Promise { const page = query.page || 1; const pageSize = query.pageSize || 10; const where: any = {}; if (query.dictType) { where.dictType = query.dictType; } if (query.keyword) { where[Op.or] = [ { dictLabel: { [Op.like]: `%${query.keyword}%` } }, { dictValue: { [Op.like]: `%${query.keyword}%` } }, ]; } if (query.status !== undefined && query.status !== null) { where.status = query.status; } const { count, rows } = await this.dictModel.findAndCountAll({ where, order: [["sort_order", "ASC"], ["id", "ASC"]], limit: Number(pageSize), offset: (Number(page) - 1) * Number(pageSize), }); return { code: 200, message: "获取字典列表成功", data: { list: rows, total: count, page: Number(page), pageSize: Number(pageSize), }, }; } async types(): Promise { const rows = await this.dictModel.findAll({ attributes: ["dictType"], group: ["dictType"], order: [["dictType", "ASC"]], }); const types = rows.map(row => row.dictType); return { code: 200, message: "获取字典类型成功", data: types, }; } async create(data: any): Promise { const { dictType, dictLabel, dictValue, sortOrder = 0, status = 1 } = data; if (!dictType || !dictLabel || !dictValue) { return { code: 400, message: "字典类型、字典标签、字典键值不能为空", data: null, }; } const dict = await this.dictModel.create({ dict_type: dictType, dict_label: dictLabel, dict_value: dictValue, sort_order: sortOrder, status, }); return { code: 200, message: "创建字典成功", data: dict, }; } async update(id: string, data: any): Promise { const dict = await this.dictModel.findByPk(Number(id)); if (!dict) { return { code: 404, message: "字典不存在", data: null, }; } const updateData: any = {}; if (data.dictType !== undefined) updateData.dict_type = data.dictType; if (data.dictLabel !== undefined) updateData.dict_label = data.dictLabel; if (data.dictValue !== undefined) updateData.dict_value = data.dictValue; if (data.sortOrder !== undefined) updateData.sort_order = data.sortOrder; if (data.status !== undefined) updateData.status = data.status; await dict.update(updateData); return { code: 200, message: "更新字典成功", data: dict, }; } async remove(id: string): Promise { const dict = await this.dictModel.findByPk(Number(id)); if (!dict) { return { code: 404, message: "字典不存在", data: null, }; } await dict.destroy(); return { code: 200, message: "删除字典成功", data: null, }; } }