<?php

namespace App\Imports;

use App\Models\CompanyContactsModel;
use App\Models\CompanyInfoModel;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;

class CompanyInfoImport implements ToCollection, WithChunkReading, ShouldQueue
{
    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {

        ini_set("memory_limit", "-1");
        set_time_limit(0);
        foreach ($collection as $key => $row) {
            ob_flush();
            flush();
            if ($key == 0) continue;
            if (strpos($row[0], '国税局') || strpos($row[0], '税务')) {

                $data['company_name'] = $row[3];
                $data['legal_person'] = $row[5];
                $data['start_date'] = str_replace('/', '-', $row[1]);
                $data['reg_addr'] = $row[4];
                $data['scope'] = $row[7];
                $data['industry'] = $row[10];
                $data['reg_no'] = $row[2];

                $res = CompanyInfoModel::create($data);
                $company_id = $res->id;

                if ($row[6]) {
                    CompanyContactsModel::create([
                        'company_id' => $company_id,
                        'linkman' => $row[5],
                        'phone' => $row[6],
                    ]);
                }
                if ($row[9]) {
                    CompanyContactsModel::create([
                        'company_id' => $company_id,
                        'linkman' => $row[8],
                        'phone' => $row[9],
                    ]);
                }


            } else {
                $isExisted = CompanyInfoModel::where('company_name', $row[1])->first();

                if ($isExisted) {
                    $company_id = $isExisted->id;
                } else {
                    $data['company_name'] = $row[1];
                    $data['legal_person'] = $row[8];
                    $data['start_date'] = $row[9];
                    $data['reg_capital'] = (int)$row[10];
                    $data['reg_addr'] = $row[11];
                    $res = CompanyInfoModel::create($data);
                    $company_id = $res->id;
                }

                CompanyContactsModel::create([
                    'company_id' => $company_id,
                    'linkman' => $row[2],
                    'phone' => $row[3] ? $row[3] : $row[4],
                    'email' => $row[5],
                    'qq' => $row[6]
                ]);
            }

        }

        unset($collection);
        ob_flush();
        flush();
    }


    public function chunkSize(): int
    {
        return 2000;
    }
}
