RdGenerateDeviceService.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. // 1. 基础校验
  16. if (empty($data['month'])) {
  17. return [false, '请选择生成研发设备工时单年月'];
  18. }
  19. $monthStart = Carbon::createFromFormat('Y-m', $data['month'])->startOfMonth()->timestamp;
  20. // 2. 业务状态校验 (提出来的校验逻辑)
  21. $calendar = DB::table('calendar')
  22. ->where('del_time', 0)
  23. ->where('time', $monthStart)
  24. ->first();
  25. if (!$calendar) return [false, '当月日历未配置'];
  26. $hasWorkDays = DB::table('calendar_details')
  27. ->where('del_time', 0)
  28. ->where('calendar_id', $calendar->id)
  29. ->where('is_work', 1)
  30. ->exists();
  31. if (!$hasWorkDays) return [false, '当月无工作日,无法生成'];
  32. // try {
  33. // DB::transaction(function () use($data) {
  34. // $this->doGenerate($data['month']);
  35. // });
  36. // } catch (\Exception $e) {
  37. // // 只有这里 throw 了,任务才会进入 failed_jobs 表
  38. // return [false, $e->getMessage()];
  39. //
  40. // }
  41. $key = self::job_name . $data['month'];
  42. $data['lock_key'] = $key;
  43. list($status,$msg) = $this->limitingSendRequest($key);
  44. if(! $status) return [false, '该月设备数据已在后台处理,请勿重复操作'];
  45. ProcessDataJob::dispatch($data)->onQueue(self::job_name);
  46. return [true, '任看'];
  47. }
  48. public function delTableKey($key){
  49. $this->dellimitingSendRequest($key);
  50. }
  51. // 内存缓冲区
  52. protected $pendingDetails = [];
  53. public function doGenerate(string $month)
  54. {
  55. $monthStart = Carbon::createFromFormat('Y-m', $month)->startOfMonth()->timestamp;
  56. $monthEnd = Carbon::createFromFormat('Y-m', $month)->endOfMonth()->timestamp;
  57. // 1. 基础数据准备
  58. $calendar = DB::table('calendar')->where('del_time', 0)->where('time', $monthStart)->first();
  59. if (!$calendar) throw new \Exception('当月日历未配置');
  60. $workDays = DB::table('calendar_details')
  61. ->where('del_time', 0)->where('calendar_id', $calendar->id)->where('is_work', 1)
  62. ->orderBy('time')->pluck('time')->toArray();
  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. // 2. 清理旧数据 (保持原样)
  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. DB::table('rd_details')->whereIn('rd_id', $rds)->delete();
  72. DB::table('rd')->whereIn('id', $rds)->delete();
  73. }
  74. $deviceConfigs = DB::table('device_details')->where('del_time', 0)
  75. ->where('time', $calendar->time)->where('total_hours_2', '>', 0)->get()->keyBy('device_id');
  76. // 3. 内存计算数据
  77. $pendingRds = [];
  78. $rdToDeviceMap = []; // 用于记录 order_number 对应哪个 device_id
  79. foreach ($deviceConfigs as $deviceId => $config) {
  80. $this->calculateData($deviceId, $items, $workDays, $config, $pendingRds, $rdToDeviceMap);
  81. }
  82. // 4. 批量插入主表 (分批写入,防止 SQL 过长)
  83. if (empty($pendingRds)) return;
  84. foreach (array_chunk($pendingRds, 1000) as $chunk) {
  85. DB::table('rd')->insert($chunk);
  86. }
  87. // 5. 核心:通过 order_number 批量找回生成的 ID
  88. $allOrderNumbers = array_keys($rdToDeviceMap);
  89. $insertedRds = DB::table('rd')
  90. ->whereIn('order_number', $allOrderNumbers)
  91. ->select('id', 'order_number', 'crt_time')
  92. ->get();
  93. // 6. 构造并批量插入详情表
  94. $pendingDetails = [];
  95. foreach ($insertedRds as $rd) {
  96. $pendingDetails[] = [
  97. 'rd_id' => $rd->id,
  98. 'data_id' => $rdToDeviceMap[$rd->order_number], // 从映射表找回设备ID
  99. 'type' => RD::type_two,
  100. 'crt_time' => $rd->crt_time,
  101. 'upd_time' => $rd->crt_time,
  102. 'del_time' => 0
  103. ];
  104. }
  105. foreach (array_chunk($pendingDetails, 1000) as $chunk) {
  106. DB::table('rd_details')->insert($chunk);
  107. }
  108. }
  109. protected function calculateData($device_id, $items, $workDays, $config, &$pendingRds, &$rdToDeviceMap)
  110. {
  111. $totalMinutes = intval(round($config->total_hours_2 * 60) / 60) * 60;
  112. // 筛选有效天数
  113. $validDays = [];
  114. foreach ($workDays as $day) {
  115. $dayItems = [];
  116. foreach ($items as $item) {
  117. if ($day >= $item->start_time && $day <= $item->end_time) $dayItems[] = $item;
  118. }
  119. if (!empty($dayItems)) $validDays[$day] = $dayItems;
  120. }
  121. if (empty($validDays)) return;
  122. // 计算每日工时分配 (略,保持您原本的分配逻辑...)
  123. $dailyMinutesMap = $this->distributeMinutes(count($validDays), $totalMinutes, array_keys($validDays));
  124. foreach ($validDays as $day => $dayItems) {
  125. $dailyMinutes = $dailyMinutesMap[$day];
  126. if ($dailyMinutes <= 0) continue;
  127. // 简单的随机项目分配
  128. $totalHoursToday = $dailyMinutes / 60;
  129. for ($h = 0; $h < $totalHoursToday; $h++) {
  130. $item = $dayItems[array_rand($dayItems)];
  131. // 生成时间点逻辑
  132. $start = Carbon::createFromTimestamp($day)->setTime(8, 0)->addMinutes(mt_rand(0, 7) * 60);
  133. $end = $start->copy()->addMinutes(60);
  134. // 生成绝对唯一的单号:时间戳 + 毫秒 + 设备ID + 随机
  135. // 这样既解决了速度问题,又保证了 order_number 的唯一索引不会崩
  136. $orderNumber = 'RD' . $day . 'D' . $device_id . 'S' . uniqid();
  137. $crtTime = $day + 59400 + mt_rand(0, 1800);
  138. $pendingRds[] = [
  139. 'crt_time' => $crtTime,
  140. 'order_time' => $day,
  141. 'item_id' => $item->id,
  142. 'start_time_hour' => $start->hour,
  143. 'start_time_min' => $start->minute,
  144. 'end_time_hour' => $end->hour,
  145. 'end_time_min' => $end->minute,
  146. 'total_hours' => 60,
  147. 'order_number' => $orderNumber,
  148. 'type' => RD::type_two,
  149. 'del_time' => 0
  150. ];
  151. // 记录这个单号属于哪个设备
  152. $rdToDeviceMap[$orderNumber] = $device_id;
  153. }
  154. }
  155. }
  156. private function distributeMinutes($daysCount, $totalMinutes, $dayKeys) {
  157. $avg = (intval(floor($totalMinutes / $daysCount) / 60)) * 60;
  158. $res = array_fill_keys($dayKeys, $avg);
  159. $rem = ($totalMinutes - ($avg * $daysCount)) / 60;
  160. for($i=0; $i<$rem; $i++) { $res[$dayKeys[$i % $daysCount]] += 60; }
  161. return $res;
  162. }
  163. }