<?php

namespace Dipper\Foundation\Http;

use Carbon\Carbon;
use Dipper\Foundation\Support\Time;
use Maatwebsite\Excel\Facades\Excel;
use Dipper\Foundation\Exceptions\InvalidArgumentException;

class RequestMixin
{
    /**
     * 获取ids
     *
     * @return array
     */
    public function ids()
    {
        return function ($field = 'ids') {
            $ids = $this->get($field);

            if (is_null($ids)) {
                return null;
            }

            $ids = is_array($ids) ? $ids : explode(',', $ids);

            foreach ($ids as $key => $value) {
                $value = trim($value);
            }
            
            return $ids;
        };
    }

    /**
     * 获取解析后的时间
     *
     * @return Carbon|null
     */
    public function time()
    {
        return function ($field) {
            return Time::parse($this->get($field));
        };
    }

    public function import()
    {
        return function (array $keys = []) {
            $import = $this->file('import');

            if (!$import || !$import->isValid()) {
                throw new InvalidArgumentException('无效的文件');
            }

            $filePath = $import->getPathname();

            $sheets = Excel::load($filePath, function ($reader) {
                $reader->ignoreEmpty();
            })->get()->toArray();
            
            // 提取字段
            if (!empty($keys)) {
                foreach ($sheets as $key => $row) {
                    $sheets[$key] = array_only($row, $keys);
                }
            }

            // 过滤空行
            foreach ($sheets as $key => $row) {
                $is_row_empty = true;
                foreach ($row as $cell) {
                    if ($cell !== '' &&  $cell !== null) {
                        $is_row_empty = false;
                        break;
                    }
                }

                if ($is_row_empty) {
                    unset($sheets[$key]);
                }
            }

            if (empty($sheets)) {
                throw new InvalidArgumentException('表格格式不正确');
            }

            return array_filter($sheets);
        };
    }
}
