<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class SchemeExport implements FromArray,WithHeadings,WithStyles,WithEvents
{
    public function __construct($data)
    {
        $this->data = $data;
    }

    public function array():array
    {
        $items = [];
        $created_at = $this->data->created_at;
        $scheme = $this->data->scheme;
        foreach ($scheme as $value){
            $items[] = [
                $value->id,
                $value->icon,
                $value->name,
                $value->unit,
                $value->num,
                $value->price,
                $created_at
            ];
        }

        return $items;
    }


    public function headings(): array
    {
        return [
            ['id','图片', '名称','单位','数量','价格','设置时间']
        ];
    }

    public function styles(Worksheet $sheet)
    {
        $sheet->getStyle('A')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
        $sheet->getStyle('C')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);

        return [
            1 => [
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_CENTER,
                ],
                'font' => [
                    'bold' => true,
                ],
                'borders' => [
                    'allBorders' => [
                        'borderStyle' => Border::BORDER_THIN,
                    ],
                ],
            ],
        ];
    }

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                $event->sheet->getDelegate()->calculateColumnWidths();
            },
        ];
    }
}
