InnerDeviceImport.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace App\Imports;
  3. use App\Exceptions\ImportError;
  4. use App\Models\DeviceName;
  5. use App\Models\InnerDevice;
  6. use App\Models\Option;
  7. use App\Models\Project;
  8. use App\Models\ProjectZone;
  9. use App\Models\Road;
  10. use App\Models\Spec;
  11. use App\Models\WorkPoint;
  12. use App\Models\Zone;
  13. use Illuminate\Support\Collection;
  14. use Illuminate\Support\Facades\Auth;
  15. use Illuminate\Support\Facades\Log;
  16. use Maatwebsite\Excel\Concerns\ToCollection;
  17. use PhpOffice\PhpSpreadsheet\Shared\Date;
  18. class InnerDeviceImport implements ToCollection
  19. {
  20. protected $model;
  21. protected $zone;
  22. protected $road;
  23. protected $project_zone;
  24. public function __construct()
  25. {
  26. $this->model = new InnerDevice();
  27. }
  28. public function formatDate($date)
  29. {
  30. if(empty($date)) return '';
  31. return Date::excelToDateTimeObject($date)->format('Y-m-d');
  32. }
  33. public function collection(Collection $rows)
  34. {
  35. if(count($rows) <= 1) {
  36. /** @noinspection PhpUnhandledExceptionInspection */
  37. // throw new ImportError('表格为空');
  38. return false;
  39. };
  40. foreach ($rows as $key => $row) {
  41. if($key == 0) continue;
  42. if(!isset($row[0])) break;
  43. $device_name = DeviceName::firstOrCreate([
  44. 'name' => $row[1]
  45. ]);
  46. $spec = Spec::firstOrCreate([
  47. 'device_name_id' => $device_name->id,
  48. 'name' => $row[2]
  49. ]);
  50. $project = null;
  51. $work_point = null;
  52. if($row[7]) {
  53. $project = Project::firstOrCreate([
  54. 'name' => $row[7]
  55. ]);
  56. }
  57. if($project && $row[8]) {
  58. $work_point = WorkPoint::firstOrCreate([
  59. 'project_id' => $project->id,
  60. 'name' => $row[8]
  61. ]);
  62. }
  63. $status = Option::where([
  64. ['table', '=', 'inner_devices'],
  65. ['column', '=', 'status'],
  66. ['name', '=', $row[9]]
  67. ])->first();
  68. $data = [
  69. 'number' => $row[0],
  70. 'device_name_id' => $device_name ? $device_name->id : '',
  71. 'spec_id' => $spec ? $spec->id : '',
  72. 'produce_date' => $this->formatDate($row[3]),
  73. 'buy_origin' => $row[4],
  74. 'manufacturer' => $row[5],
  75. 'shape' => $row[6],
  76. 'project_id' => $project ? $project->id : '',
  77. 'work_point_id' => $work_point ? $work_point->id : '',
  78. 'status' => $status ? $status->id : ''
  79. ];
  80. $this->model->create($data);
  81. // $num = (int)$row[7];
  82. // for($i = 0; $i < $num; ++$i) {
  83. // $this->model->create($data);
  84. // }
  85. }
  86. return true;
  87. }
  88. }