<?php

namespace App\Imports;

use App\Exceptions\ImportError;
use App\Models\Device;
use App\Models\DeviceName;
use App\Models\InnerDevice;
use App\Models\InnerDeviceNamesModel;
use App\Models\Option;
use App\Models\Project;
use App\Models\ProjectZone;
use App\Models\Road;
use App\Models\Spec;
use App\Models\WorkPoint;
use App\Models\Zone;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use PhpOffice\PhpSpreadsheet\Shared\Date;

class SpecImport implements ToCollection
{
    protected $model;

    protected $zone;

    protected $road;

    protected $project_zone;

    public function __construct()
    {
        $this->model = new Spec();
    }

    public function collection(Collection $rows)
    {
        if(count($rows) <= 1) {
            /** @noinspection PhpUnhandledExceptionInspection */
            return false;
        };
        foreach ($rows as $key => $row) {
            if($key == 0) continue;
            if(empty($row[0])&&empty($row[1])&&empty($row[2]))
            {
                break;
            }
            //设备类型
            if ($row[1] == "项目自填（必须填写）" || $row[2] == "项目自填（必须填写）")
            {
                continue;
            }
            $device_id = null;
            $device_name_id = null;
            //设备类型
            if ($row[0])
            {
                $device_id = Device::firstOrCreate([
                    'name' => $row[0],
                    'sort' => 1,
                ]);
            }
            //设备名称
            if ($row[1])
            {
                if($device_id && $row[1]) {
                    $device_name_id = DeviceName::firstOrCreate([
                        'device_id' => $device_id->id,
                        'name' => $row[1],
                        'sort' => 1,
                        'status' => 1
                    ]);
                }
            }
            //规格型号
            if ($row[2])
            {
                $data = [
                    'name' => $row[2],
                    'device_name_id' => $device_name_id ? $device_name_id->id : '',
                    'device_id' => $device_id ? $device_id->id : '',
                    'sort' => 1
                ];
                $this->model->create($data);
            }
        }
        return true;
    }
}
