where('media_channel_code', $mediaChannelCode); if ($supportsDeptBinding) { $existsQuery->where('dept_id', $deptId); } if ($existsQuery->count() > 0) { self::setError($supportsDeptBinding ? '该日期下所选渠道和部门的账户消耗已存在,请直接编辑' : '该日期下所选渠道的账户消耗已存在,请直接编辑'); return false; } $payload = [ 'cost_date' => $costDate, 'media_channel_code' => $mediaChannelCode, 'media_channel_name' => $mediaChannelName, 'amount' => round((float) $params['amount'], 2), 'remark' => (string) ($params['remark'] ?? ''), 'creator_id' => $adminId, 'creator_name' => $adminName, 'updater_id' => $adminId, 'updater_name' => $adminName, ]; if ($supportsDeptBinding) { $payload['dept_id'] = $deptId; $payload['dept_name'] = $deptName; } AccountCost::create($payload); return true; } catch (\Throwable $e) { self::setError($e->getMessage()); return false; } } public static function edit(array $params, int $adminId, string $adminName): bool { try { $model = AccountCost::find($params['id']); if (!$model) { self::setError('记录不存在'); return false; } $mediaChannelCode = trim((string) ($params['media_channel_code'] ?? '')); $mediaChannelName = MediaChannelService::getNameByCode($mediaChannelCode); $supportsDeptBinding = AccountCost::supportsDeptBinding(); $deptId = $supportsDeptBinding ? (int) ($params['dept_id'] ?? 0) : 0; $deptName = $supportsDeptBinding ? self::resolveDeptName($deptId) : ''; if ($supportsDeptBinding && $deptName === '') { self::setError('请选择绑定部门'); return false; } if ($supportsDeptBinding) { if (AccountCost::where('id', '<>', (int) $params['id']) ->where('cost_date', (string) $model->cost_date) ->where('media_channel_code', $mediaChannelCode) ->where('dept_id', $deptId) ->count() > 0) { self::setError('该日期下所选渠道和部门的账户消耗已存在,请直接编辑'); return false; } } $model->media_channel_code = $mediaChannelCode; $model->media_channel_name = $mediaChannelName; if ($supportsDeptBinding) { $model->dept_id = $deptId; $model->dept_name = $deptName; } $model->amount = round((float) $params['amount'], 2); $model->remark = (string) ($params['remark'] ?? ''); $model->updater_id = $adminId; $model->updater_name = $adminName; $model->save(); return true; } catch (\Throwable $e) { self::setError($e->getMessage()); return false; } } public static function detail(int $id): array { return AccountCost::findOrEmpty($id)->toArray(); } public static function delete(int $id): bool { try { $model = AccountCost::find($id); if (!$model) { self::setError('记录不存在'); return false; } $model->delete(); return true; } catch (\Throwable $e) { self::setError($e->getMessage()); return false; } } private static function resolveDeptName(int $deptId): string { if ($deptId <= 0) { return ''; } $dept = Dept::find($deptId); if (!$dept) { return ''; } return (string) ($dept->name ?? ''); } }