RdGenerateDeviceService.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. // 1. 获取当月第一天的时间戳
  91. $belongMonth = strtotime(date('Y-m-01', $day));
  92. $baseCrtTime = $day + 59400; // 创建时间从 16:30 开始递增
  93. $sequence = 0;
  94. foreach ($projectGroups as $itemId => $timeBlocks) {
  95. foreach ($timeBlocks as $timeKey => $data) {
  96. // ... 循环内部 ...
  97. $dateStr = date('Ymd', $day);
  98. // 结合项目ID、循环序列和4位随机字符,兼顾了短小和唯一性
  99. $orderNumber = sprintf("RD%s%d%s%s",
  100. $dateStr,
  101. $itemId,
  102. dechex($sequence),
  103. substr(md5(mt_rand()), 0, 4)
  104. );
  105. // $orderNumber = 'RD' . $day . 'P' . $itemId . 'S' . $sequence . uniqid();
  106. $crtTime = $baseCrtTime + ($sequence * 10) + mt_rand(0, 5);
  107. $pendingRds[] = [
  108. 'crt_time' => $crtTime,
  109. 'order_time' => $day,
  110. 'item_id' => $itemId,
  111. 'start_time_hour' => $data['start']->hour,
  112. 'start_time_min' => $data['start']->minute,
  113. 'end_time_hour' => $data['end']->hour,
  114. 'end_time_min' => $data['end']->minute,
  115. 'total_hours' => 60,
  116. 'order_number' => $orderNumber,
  117. 'type' => RD::type_two,
  118. 'del_time' => 0,
  119. 'belong_month' => $belongMonth,
  120. ];
  121. $rdToDevicesMap[$orderNumber] = [
  122. 'device_ids' => $data['device_ids'],
  123. 'crt_time' => $crtTime
  124. ];
  125. $sequence++;
  126. }
  127. }
  128. }
  129. // 7. 批量插入并同步详情
  130. if (empty($pendingRds)) return;
  131. foreach (array_chunk($pendingRds, 1000) as $chunk) {
  132. DB::table('rd')->insert($chunk);
  133. }
  134. // 通过 order_number 找回生成的 ID
  135. $insertedRds = DB::table('rd')->whereIn('order_number', array_keys($rdToDevicesMap))
  136. ->select('id', 'order_number')->get();
  137. $pendingDetails = [];
  138. foreach ($insertedRds as $rd) {
  139. $mapData = $rdToDevicesMap[$rd->order_number];
  140. foreach ($mapData['device_ids'] as $deviceId) {
  141. $pendingDetails[] = [
  142. 'rd_id' => $rd->id,
  143. 'data_id' => $deviceId,
  144. 'type' => RD::type_two,
  145. 'crt_time' => $mapData['crt_time'],
  146. 'upd_time' => $mapData['crt_time'],
  147. 'del_time' => 0
  148. ];
  149. }
  150. }
  151. foreach (array_chunk($pendingDetails, 1000) as $chunk) {
  152. DB::table('rd_details')->insert($chunk);
  153. }
  154. }
  155. /**
  156. * 计算并分配每个设备的工时到公共槽位
  157. */
  158. protected function assignDeviceToSlots($config, $items, $workDays, &$slots)
  159. {
  160. $totalMinutes = intval(round($config->total_hours_2 * 60) / 60) * 60;
  161. // 筛选有效天
  162. $validDays = [];
  163. foreach ($workDays as $day) {
  164. $dayItems = [];
  165. foreach ($items as $item) {
  166. if ($day >= $item->start_time && $day <= $item->end_time) $dayItems[] = $item;
  167. }
  168. if (!empty($dayItems)) $validDays[$day] = $dayItems;
  169. }
  170. if (empty($validDays)) return;
  171. $dailyMinutesMap = $this->distributeMinutes(count($validDays), $totalMinutes, array_keys($validDays));
  172. foreach ($validDays as $day => $dayItems) {
  173. $dailyMinutes = $dailyMinutesMap[$day];
  174. if ($dailyMinutes <= 0) continue;
  175. // 为了让不同设备能合并,使用固定的 8:00 作为参考起点
  176. $currentTimePointer = Carbon::createFromTimestamp($day)->setTime(8, 0);
  177. $lunchStart = Carbon::createFromTimestamp($day)->setTime(11, 30);
  178. $lunchEnd = Carbon::createFromTimestamp($day)->setTime(12, 0);
  179. $totalHoursToday = $dailyMinutes / 60;
  180. for ($h = 0; $h < $totalHoursToday; $h++) {
  181. // 如果是多个设备同一时间做同一个项目,这里最好保证选择项目的随机种子在同一天内是对齐的,
  182. // 或者业务允许随机。这里按设备随机选一个。
  183. $item = $dayItems[array_rand($dayItems)];
  184. $start = $currentTimePointer->copy();
  185. // 跳过午休起始点
  186. if ($start->gte($lunchStart) && $start->lt($lunchEnd)) {
  187. $start = $lunchEnd->copy();
  188. }
  189. $end = $start->copy()->addMinutes(60);
  190. // 跨午休处理
  191. if ($start->lt($lunchStart) && $end->gt($lunchStart)) {
  192. $end->addMinutes(30);
  193. }
  194. // 生成用于合并的槽位 Key
  195. $timeKey = $start->format('Hi') . '-' . $end->format('Hi');
  196. // 存入合并缓冲区
  197. $slots[$day][$item->id][$timeKey]['start'] = $start;
  198. $slots[$day][$item->id][$timeKey]['end'] = $end;
  199. $slots[$day][$item->id][$timeKey]['device_ids'][] = $config->device_id;
  200. // 指针移动(接力)
  201. $currentTimePointer = $end->copy();
  202. }
  203. }
  204. }
  205. private function distributeMinutes($daysCount, $totalMinutes, $dayKeys) {
  206. $avg = (intval(floor($totalMinutes / $daysCount) / 60)) * 60;
  207. $res = array_fill_keys($dayKeys, $avg);
  208. $rem = ($totalMinutes - ($avg * $daysCount)) / 60;
  209. for($i=0; $i<$rem; $i++) { $res[$dayKeys[$i % $daysCount]] += 60; }
  210. return $res;
  211. }
  212. }