<?php

namespace App\Imports;

use App\Models\Group;
use App\Models\Export;
use App\Models\Category;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Events\AfterImport;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Concerns\WithEvents;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;

class ExportsImport implements OnEachRow, WithStartRow, WithMultipleSheets, WithEvents, WithChunkReading, ShouldQueue
{
    public $id;
    public $group;
    public $locale;
    public $category;
    public $currency;
    public $categories;

    public function __construct(int $id, Group $group, string $locale)
    {
        $this->id = $id;
        $this->group = $group->id;
        $this->locale = $locale;
        $this->categories = Category::all();
    }

    public function sheets(): array
    {
        return [
            0 => $this,
        ];
    }

    public function startRow(): int
    {
        return 4;
    }

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

    public function registerEvents(): array
    {
        return [
            BeforeImport::class => function (BeforeImport $event) {
                $totalRows = $event->getReader()->getTotalRows();

                if (filled($totalRows)) {
                    cache()->forever("total_rows_{$this->id}", array_values($totalRows)[0]);
                    cache()->forever("start_date_{$this->id}", now()->unix());
                }
            },
            AfterImport::class => function (AfterImport $event) {
                cache(["end_date_{$this->id}" => now()], now()->addMinute());
                cache()->forget("total_rows_{$this->id}");
                cache()->forget("start_date_{$this->id}");
                cache()->forget("current_row_{$this->id}");
            },
        ];
    }

    public function onRow(Row $row)
    {
        $rowIndex = $row->getIndex();
        $row      = array_map('trim', $row->toArray());
        cache()->forever("current_row_{$this->id}", $rowIndex);
        // sleep(0.2);

        if (empty($row[0])) {
            $this->setCategory($row);
            $this->setCurrency($row);
            $this->setType($row);

            return;
        }

        $row['group'] = $this->group;
        $row['category'] = $this->category;
        $row['currency'] = $this->currency;
        $row['locale'] = $this->locale;
        $row['type'] = $this->type;

        try {
            Export::create([
                'locale' => $row['locale'],
                'category_id' => $row['category'],
                'group_id' => $row['group'],
                'type' => $row['type'],
                'currency' => $row['currency'],
                'title' => $row[1],
                'unit' => $row[2],
                'amount' => $row[3],
                'price' => $row[4],
                'payment' => $row[6],
                'send' => $row[7],
                'point' => $row[8],
                'country' => $row[9],
                'seller' => $row[10],
                'place' => $row[11],
            ]);
        } catch (\Throwable $th) {
            info($th->getMessage());
            // dd($row);
        }
    }

    protected function setCategory($row)
    {
        if ($category = $this->categories->first(fn ($c) => data_get($c->getOriginal('title'), $this->locale) == $row[1])) {
            $this->category = $category->id;
        }
    }

    protected function setCurrency($row)
    {
        if (in_array($row[1], [
            'Доллар США',
            'ABŞ-nyň dollary',
            'US dollar',
            'in US dollars',
        ])) {
            $this->currency = 'USD';
        }

        if (in_array($row[1], [
            'türkmen manady',
            'Туркменский манат',
            'turkmen manats',
        ])) {
            $this->currency = 'TMT';
        }
    }

    protected function setType($row)
    {
        if (in_array($row[1], [
            'External',
            'Foreign',
            'Внешний',
            'Daşarky',
        ])) {
            $this->type = 'external';
        }

        if (in_array($row[1], [
            'Internal',
            'internal',
            'Внутренний',
            'Içerki'
        ])) {
            $this->type = 'internal';
        }
    }
}
