<?php

namespace App\Domains\Export\Services;

use App\Core\Service;
use Illuminate\Http\UploadedFile;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Illuminate\Support\Facades\Validator;
use App\Exceptions\InvalidArgumentException;

class ImportService extends Service
{
    /**
     * 导出
     */
    public static function load(UploadedFile $file, $columns = null)
    {
        if ($columns !== null) {
            if (!is_array($columns)) {
                throw new InvalidArgumentException('columns not an array.');
            }

            $columns = array_map('strtolower', $columns);
        }

        $array = self::toArray($file);

        $title = [];
        $data = [];

        foreach ($array as $index => $item) {
            if (!$index) {
                $title = $item;
            } else {
                $row = [];
                foreach ($item as $key => $value) {
                    $column = strtolower($title[$key]);
                    if ($columns === null || in_array($column, $columns)) {
                        $row[$column] = trim($value);
                    }
                }

                array_push($data, $row);
            }
        }

        return $data;
    }

    /**
     * 导入转为数组
     *
     * @param UploadedFile $file
     * @return void
     */
    public static function toArray(UploadedFile $file)
    {
        if (!$file) {
            throw new InvalidArgumentException('文件不存在');
        }

        $extension = $file->getClientOriginalExtension();

        Validator::validate(['extension' => $extension], [
            'extension' => ['in:xls,xlsx,csv'],
        ], ['extension.in' => '文件类型不正确']);

        $type = ucfirst(strtolower($extension));

        $reader = IOFactory::createReader($type);

        $spreadsheet = $reader->load($file->getPathname());

        $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, false);

        return $sheetData;
    }
}
