<?php

namespace App\Imports;

use App\Models\CompanyContactsModel;
use App\Models\CompanyInfoModel;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class CompanyInfoImport implements ToCollection
{
    /**
    * @param Collection $collection
    */
    public function collection(Collection $collection)
    {
        foreach ($collection as $key => $row){
            if ($key == 0 ) continue;
            if(strpos($row[0],'国税局')){
                \Log::info('start');
                $isExisted = CompanyInfoModel::where('companyName',$row[3])->first();

                if($isExisted){
                    \Log::info('1');
                    $company_id = $isExisted->id;
                }else{
                    \Log::info('2');
                    $data['companyName'] = $row[3];
                    $data['legalPerson'] = $row[5];
                    $data['startDate'] = str_replace('/','-',$row[1]);
                    $data['regAddr'] = $row[4];
                    $data['scope'] = $row[7];
                    $data['industry'] = $row[10];
                    $data['regNo'] = $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('companyName',$row[1])->first();

                if($isExisted){
                    $company_id = $isExisted->id;
                }else{
                    $data['companyName'] = $row[1];
                    $data['legalPerson'] = $row[8];
                    $data['startDate'] = $row[9];
                    $data['regCapital'] = (int)$row[10];
                    $data['regAddr'] = $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]
                ]);
            }

        }
    }
}
