GenerateKey.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Good;
  4. use App\Trace;
  5. use Carbon\Carbon;
  6. use Vinkla\Hashids\Facades\Hashids;
  7. use Illuminate\Console\Command;
  8. use Illuminate\Support\Facades\Artisan;
  9. class GenerateKey extends Command
  10. {
  11. /**
  12. * The name and signature of the console command.
  13. *
  14. * @var string
  15. */
  16. protected $signature = 'generate:key {gid}';
  17. /**
  18. * The console command description.
  19. *
  20. * @var string
  21. */
  22. protected $description = '生成key';
  23. /**
  24. * Create a new command instance.
  25. *
  26. * @return void
  27. */
  28. public function __construct()
  29. {
  30. parent::__construct();
  31. }
  32. /**
  33. * Execute the console command.
  34. *
  35. * @return mixed
  36. */
  37. public function handle()
  38. {
  39. $gid = $this->argument('gid');
  40. $good = Good::where('id', $gid)->first();
  41. $good->is_key = 'D';
  42. $good->save();
  43. $keyNum = Trace::where('gid', $gid)->count();
  44. $jishu = $good->group ?? $good->number;
  45. $leijia = 0;
  46. //生成key
  47. if (($num = ($good->number - $keyNum)) > 0) {
  48. $zNum = floor($num / 1000);
  49. $yNum = $num % 1000;
  50. $i = 0;
  51. while ($i < $zNum) {
  52. $data = [];
  53. for ($j = 0; $j < 1000; $j++) {
  54. $key = $good->skey . $this->num_random($good->bit);
  55. $data[] = [
  56. 'gid' => $gid,
  57. 'key' => $key,
  58. 'group' => floor($leijia / $jishu),
  59. 'created_at' => Carbon::now(),
  60. 'updated_at' => Carbon::now(),
  61. ];
  62. $leijia++;
  63. }
  64. Trace::insert($data);
  65. $i++;
  66. }
  67. for ($m = 0; $m < $yNum; $m++) {
  68. Trace::create([
  69. 'gid' => $gid,
  70. 'key' => $good->skey . $this->num_random($good->bit),
  71. 'group' => floor($leijia / $jishu),
  72. ]);
  73. $leijia++;
  74. }
  75. }
  76. $keyNum = Trace::where('gid', $gid)->count();
  77. if ($keyNum < $good->number) {
  78. Artisan::call("generate:key", ['gid' => $good->id]);
  79. } else {
  80. $ids = Trace::whereNull('slug')->pluck('id');
  81. foreach ($ids as $id) {
  82. Trace::where('id', $id)->update(['slug' => Hashids::encode($id)]);
  83. }
  84. $good->is_key = 'T';
  85. $good->save();
  86. }
  87. }
  88. private function num_random($len = 16)
  89. {
  90. $num = '';
  91. for ($i = 0; $i < $len; $i++) {
  92. $num .= rand(0, 9);
  93. }
  94. return $num;
  95. }
  96. }