RdGenerateDeviceService.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. namespace App\Service;
  3. use App\Jobs\ProcessDataJob;
  4. use App\Model\RD;
  5. use Carbon\Carbon;
  6. use Illuminate\Support\Facades\DB;
  7. class RdGenerateDeviceService extends Service
  8. {
  9. const job_name = "rd_device_set";
  10. /**
  11. * 外部调用的入口 (保持原样,负责分发队列)
  12. */
  13. public function generate(array $data)
  14. {
  15. if (empty($data['month'])) {
  16. return [false, '请选择生成研发设备工时单年月'];
  17. }
  18. $monthStart = Carbon::createFromFormat('Y-m', $data['month'])->startOfMonth()->timestamp;
  19. $calendar = DB::table('calendar')
  20. ->where('del_time', 0)
  21. ->where('time', $monthStart)
  22. ->first();
  23. if (!$calendar) return [false, '当月日历未配置'];
  24. $hasWorkDays = DB::table('calendar_details')
  25. ->where('del_time', 0)
  26. ->where('calendar_id', $calendar->id)
  27. ->where('is_work', 1)
  28. ->exists();
  29. if (!$hasWorkDays) return [false, '当月无工作日,无法生成'];
  30. // try {
  31. // DB::transaction(function () use($data) {
  32. // $this->doGenerate($data['month']);
  33. // });
  34. // } catch (\Exception $e) {
  35. // // 只有这里 throw 了,任务才会进入 failed_jobs 表
  36. // return [false, $e->getMessage()];
  37. //
  38. // }dd(2);
  39. $key = self::job_name . $data['month'];
  40. $data['lock_key'] = $key;
  41. list($status, $msg) = $this->limitingSendRequest($key);
  42. if (!$status) return [false, '该月设备数据已在后台处理,请勿重复操作'];
  43. ProcessDataJob::dispatch($data)->onQueue(self::job_name);
  44. return [true, '任务已放到后台运行'];
  45. }
  46. public function delTableKey($key) {
  47. $this->dellimitingSendRequest($key);
  48. }
  49. /**
  50. * 队列真正执行的逻辑
  51. */
  52. public function doGenerate(string $month)
  53. {
  54. $monthStart = Carbon::createFromFormat('Y-m', $month)->startOfMonth()->timestamp;
  55. $monthEnd = Carbon::createFromFormat('Y-m', $month)->endOfMonth()->timestamp;
  56. // 1. 获取日历和工作日
  57. $calendar = DB::table('calendar')->where('del_time', 0)->where('time', $monthStart)->first();
  58. if (!$calendar) throw new \Exception('当月日历未配置');
  59. $workDays = DB::table('calendar_details')
  60. ->where('del_time', 0)->where('calendar_id', $calendar->id)->where('is_work', 1)
  61. ->orderBy('time')->pluck('time')->toArray();
  62. // 2. 获取当月有效项目
  63. $items = DB::table('item')->where('del_time', 0)->where('is_use', 1)
  64. ->where('start_time', '<=', $monthEnd)->where('end_time', '>=', $monthStart)
  65. ->orderBy('id', 'desc')->get();
  66. if ($items->isEmpty() || empty($workDays)) return;
  67. // 3. 清理旧数据
  68. $rds = DB::table('rd')->where('del_time', 0)->where('type', RD::type_two)
  69. ->whereBetween('order_time', [$monthStart, $monthEnd])->pluck('id')->toArray();
  70. if (!empty($rds)) {
  71. foreach (array_chunk($rds, 1000) as $chunk) {
  72. DB::table('rd_details')->whereIn('rd_id', $chunk)->delete();
  73. DB::table('rd')->whereIn('id', $chunk)->delete();
  74. }
  75. }
  76. // 4. 获取设备配置
  77. $deviceConfigs = DB::table('device_details')->where('del_time', 0)
  78. ->where('time', $calendar->time)->where('total_hours_2', '>', 0)->get();
  79. // --- 核心:按槽位合并逻辑开始 ---
  80. // 5. 内存计算:将所有设备的工时分配到槽位中合并
  81. // $slots[日期][项目ID][时间槽Key] = ['start'=>Carbon, 'end'=>Carbon, 'device_ids'=>[]]
  82. $slots = [];
  83. foreach ($deviceConfigs as $config) {
  84. $this->assignDeviceToSlots($config, $items, $workDays, $slots);
  85. }
  86. // 6. 构造主表批量插入数组
  87. $pendingRds = [];
  88. $rdToDevicesMap = []; // order_number => ['device_ids' => [], 'crt_time' => ...]
  89. foreach ($slots as $day => $projectGroups) {
  90. $baseCrtTime = $day + 59400; // 创建时间从 16:30 开始递增
  91. $sequence = 0;
  92. foreach ($projectGroups as $itemId => $timeBlocks) {
  93. foreach ($timeBlocks as $timeKey => $data) {
  94. $orderNumber = 'RD' . $day . 'P' . $itemId . 'S' . $sequence . uniqid();
  95. $crtTime = $baseCrtTime + ($sequence * 10) + mt_rand(0, 5);
  96. $pendingRds[] = [
  97. 'crt_time' => $crtTime,
  98. 'order_time' => $day,
  99. 'item_id' => $itemId,
  100. 'start_time_hour' => $data['start']->hour,
  101. 'start_time_min' => $data['start']->minute,
  102. 'end_time_hour' => $data['end']->hour,
  103. 'end_time_min' => $data['end']->minute,
  104. 'total_hours' => 60,
  105. 'order_number' => $orderNumber,
  106. 'type' => RD::type_two,
  107. 'del_time' => 0
  108. ];
  109. $rdToDevicesMap[$orderNumber] = [
  110. 'device_ids' => $data['device_ids'],
  111. 'crt_time' => $crtTime
  112. ];
  113. $sequence++;
  114. }
  115. }
  116. }
  117. // 7. 批量插入并同步详情
  118. if (empty($pendingRds)) return;
  119. foreach (array_chunk($pendingRds, 1000) as $chunk) {
  120. DB::table('rd')->insert($chunk);
  121. }
  122. // 通过 order_number 找回生成的 ID
  123. $insertedRds = DB::table('rd')->whereIn('order_number', array_keys($rdToDevicesMap))
  124. ->select('id', 'order_number')->get();
  125. $pendingDetails = [];
  126. foreach ($insertedRds as $rd) {
  127. $mapData = $rdToDevicesMap[$rd->order_number];
  128. foreach ($mapData['device_ids'] as $deviceId) {
  129. $pendingDetails[] = [
  130. 'rd_id' => $rd->id,
  131. 'data_id' => $deviceId,
  132. 'type' => RD::type_two,
  133. 'crt_time' => $mapData['crt_time'],
  134. 'upd_time' => $mapData['crt_time'],
  135. 'del_time' => 0
  136. ];
  137. }
  138. }
  139. foreach (array_chunk($pendingDetails, 1000) as $chunk) {
  140. DB::table('rd_details')->insert($chunk);
  141. }
  142. }
  143. /**
  144. * 计算并分配每个设备的工时到公共槽位
  145. */
  146. protected function assignDeviceToSlots($config, $items, $workDays, &$slots)
  147. {
  148. $totalMinutes = intval(round($config->total_hours_2 * 60) / 60) * 60;
  149. // 筛选有效天
  150. $validDays = [];
  151. foreach ($workDays as $day) {
  152. $dayItems = [];
  153. foreach ($items as $item) {
  154. if ($day >= $item->start_time && $day <= $item->end_time) $dayItems[] = $item;
  155. }
  156. if (!empty($dayItems)) $validDays[$day] = $dayItems;
  157. }
  158. if (empty($validDays)) return;
  159. $dailyMinutesMap = $this->distributeMinutes(count($validDays), $totalMinutes, array_keys($validDays));
  160. foreach ($validDays as $day => $dayItems) {
  161. $dailyMinutes = $dailyMinutesMap[$day];
  162. if ($dailyMinutes <= 0) continue;
  163. // 为了让不同设备能合并,使用固定的 8:00 作为参考起点
  164. $currentTimePointer = Carbon::createFromTimestamp($day)->setTime(8, 0);
  165. $lunchStart = Carbon::createFromTimestamp($day)->setTime(11, 30);
  166. $lunchEnd = Carbon::createFromTimestamp($day)->setTime(12, 0);
  167. $totalHoursToday = $dailyMinutes / 60;
  168. for ($h = 0; $h < $totalHoursToday; $h++) {
  169. // 如果是多个设备同一时间做同一个项目,这里最好保证选择项目的随机种子在同一天内是对齐的,
  170. // 或者业务允许随机。这里按设备随机选一个。
  171. $item = $dayItems[array_rand($dayItems)];
  172. $start = $currentTimePointer->copy();
  173. // 跳过午休起始点
  174. if ($start->gte($lunchStart) && $start->lt($lunchEnd)) {
  175. $start = $lunchEnd->copy();
  176. }
  177. $end = $start->copy()->addMinutes(60);
  178. // 跨午休处理
  179. if ($start->lt($lunchStart) && $end->gt($lunchStart)) {
  180. $end->addMinutes(30);
  181. }
  182. // 生成用于合并的槽位 Key
  183. $timeKey = $start->format('Hi') . '-' . $end->format('Hi');
  184. // 存入合并缓冲区
  185. $slots[$day][$item->id][$timeKey]['start'] = $start;
  186. $slots[$day][$item->id][$timeKey]['end'] = $end;
  187. $slots[$day][$item->id][$timeKey]['device_ids'][] = $config->device_id;
  188. // 指针移动(接力)
  189. $currentTimePointer = $end->copy();
  190. }
  191. }
  192. }
  193. private function distributeMinutes($daysCount, $totalMinutes, $dayKeys) {
  194. $avg = (intval(floor($totalMinutes / $daysCount) / 60)) * 60;
  195. $res = array_fill_keys($dayKeys, $avg);
  196. $rem = ($totalMinutes - ($avg * $daysCount)) / 60;
  197. for($i=0; $i<$rem; $i++) { $res[$dayKeys[$i % $daysCount]] += 60; }
  198. return $res;
  199. }
  200. }