diff --git a/app/Console/Commands/CreateParkingUtilizationRate.php b/app/Console/Commands/CreateParkingUtilizationRate.php new file mode 100644 index 0000000..a000fbe --- /dev/null +++ b/app/Console/Commands/CreateParkingUtilizationRate.php @@ -0,0 +1,144 @@ +pluck('id'); + if ($ParkingSpaceIds) { + foreach ($ParkingSpaceIds as $space_id) { + // 小时 + $this->createRate($start_time, $end_time, $space_id); + + // 天 + if ($now_hours == '01') { + $this->createRate( + $day_start_time, + $day_end_time, + $space_id, + 2 + ); + } + } + } + DB::commit(); + } catch (Exception $e) { + DB::rollBack(); + dd($e); + } + } + + private function createRate( + $start_time, + $end_time, + $space_id, + $date_type = 1 + ) { + $where = [ + 'start_time' => $start_time, + 'end_time' => $end_time, + 'space_id' => $space_id, + 'date_type' => $date_type + ]; + if (!ParkingUtilizationRate::query()->where($where)->exists() + ) { + $create = $where; + $create['rate'] = $this->getRate( + $start_time, + $end_time, + $space_id, + $date_type + ); + $create['created_at'] = date("Y-m-d H:i:s", time()); + ParkingUtilizationRate::query()->create($create); + } + } + + private function getRate( + $start_time, + $end_time, + $space_id, + $date_type + ): string { + $rate = 0; + + $sumSecond = 3600; + if ($date_type == 2) { + $sumSecond = 3600 * 24; + } + + $start_times = strtotime($start_time); + $end_times = strtotime($end_time); + + $model = ParkingAccessRecord::query()->where('space_id', $space_id) + ->where( + function ($query) use ($start_times, $end_times) { + $query->whereRaw( + " enter_time < {$end_times}" + . + " AND (leave_time IS NULL OR leave_time > {$start_times})" + ); + } + )->select(['enter_time', 'leave_time'])->get(); + if ($model) { + $list = $model->toArray(); + foreach ($list as $item) { + $enter_time = strtotime($item['enter_time']); + $leave_time = $item['leave_time'] ? strtotime( + $item['leave_time'] + ) : $end_times; + + if ($enter_time < $start_times) { + $enter_time = $start_times; + } + if ($leave_time > $end_times) { + $leave_time = $end_times; + } + + $second = $leave_time - $enter_time; + + if ($second > 0) { + $rate = round($second / $sumSecond, 4); + } + } + } + return $rate * 100; + } +}