where('code', 'like', '%' . $params['code'] . '%'); } // 模板名称搜索 if (!empty($params['name'])) { $query->where('name', 'like', '%' . $params['name'] . '%'); } // 类型筛选 if (isset($params['type']) && $params['type'] !== '') { $query->where('type', $params['type']); } // 状态筛选 if (isset($params['status']) && $params['status'] !== '') { $query->where('status', $params['status']); } // 获取总数 $total = $query->count(); // 获取分页数据 $list = $query->order('id', 'desc') ->page($page, $limit) ->select() ->toArray(); return [ 'list' => $list, 'total' => $total, 'page' => $page, 'limit' => $limit, ]; } /** * 获取单个模板详情 * * @param int $id 模板ID * @return array|null */ public function getDetail(int $id) { return MessageTemplateEntity::find($id); } /** * 根据模板代码获取模板 * * @param string $code 模板代码 * @return array|null */ public function getByCode(string $code) { return MessageTemplateEntity::where('code', $code) ->where('status', 1) ->find(); } /** * 添加模板 * * @param array $data 模板数据 * @return int|bool */ public function add(array $data) { // 检查模板代码是否已存在 $exists = MessageTemplateEntity::where('code', $data['code'])->find(); if ($exists) { return false; } $entity = new MessageTemplateEntity(); $result = $entity->save($data); // 确保保存成功并返回ID if ($result) { return $entity->id ?: true; // 如果没有id属性,至少返回true表示成功 } return false; } /** * 更新模板 * * @param int $id 模板ID * @param array $data 更新数据 * @return bool */ public function update(int $id, array $data) { $entity = MessageTemplateEntity::find($id); if (!$entity) { return false; } // 检查模板代码是否已存在 if (isset($data['code']) && $data['code'] != $entity->code) { $exists = MessageTemplateEntity::where('code', $data['code'])->find(); if ($exists) { return false; } } return $entity->save($data); } /** * 删除模板 * * @param int $id 模板ID * @return bool */ public function delete(int $id) { $entity = MessageTemplateEntity::find($id); if (!$entity) { return false; } return $entity->delete(); } /** * 批量删除模板 * * @param array $ids 模板ID数组 * @return bool */ public function batchDelete(array $ids) { if (empty($ids)) { return false; } return MessageTemplateEntity::destroy($ids); } /** * 解析模板内容 * * @param string $code 模板代码 * @param array $data 替换数据 * @return array|null 解析后的标题和内容 */ public function parseTemplate(string $code, array $data) { $template = $this->getByCode($code); if (!$template) { return null; } return $template->parse($data); } }