<?php

namespace App\Imports;

use App\Components\AsyncResponse;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

HeadingRowFormatter::default('none');
class AppointmentDetail implements ToCollection,WithMultipleSheets,WithHeadingRow
{
    use AsyncResponse;
    protected $row = ["条码","商品名称","数量"];
    public function sheets(): array
    {
        return [
            0 => $this,
        ];
    }

    /**
    * @param Collection $collection
    */
    public function collection(Collection $collection)
    {
        $header = $collection->first();
        foreach ($this->row as $row)if (!isset($header[$row]))$this->error("表头不存在“".$row."”");
        $errors = Validator::make($collection->toArray(),[
            "*.条码" => ["required_without:*.商品名称"],
            "*.商品名称" => ["required_without:*.条码"],
            "*.数量" => ["required_without:*.条码","integer","min:1"],
        ],[
            'required_without'=>':attribute 条码与商品名称,数量至少存在一组',
            'integer'=>':attribute 必须为数字',
            'min'=>':attribute 非法',
        ],[
            "*.条码" => "条码",
            "*.商品名称" => "商品名称",
            "*.数量" => "数量",
        ])->errors();
        if (count($errors)>0){
            $temp = [];
            foreach ($errors->toArray() as $key=>$arr){
                $key = explode(".",$key,2)[0];
                unset($collection[$key]);
                $key = $key+2;
                if (array_key_exists($key,$temp))$temp[$key] = array_merge($temp[$key],$arr);
                else $temp[$key] = $arr;
            }
            $errors = $temp;
        }
        $this->success(["data"=>$collection,"errors"=>$errors]);
    }
}
