<?php

namespace App\Exports;

use App\Models\Office;
use App\Models\Restaurant;
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 OrderSchemeExport implements FromArray,WithHeadings,WithStyles,WithEvents
{
    public function __construct($data)
    {
        $this->data = $data;
    }

    public function array():array
    {
        $items = [];
        foreach ($this->data as $value){
            $name  = "";
            $num = $price = "";
            if(isset($value['scheme']) && !empty($value['scheme'])){
                $scheme = json_decode($value['scheme']);
                foreach ($scheme as $item){
                    $new_name = $item->name??"";
                    $new_num = $item->num??"0";
                    $new_price = $item->price??"0";
                    $name .= $new_name."\n";
                    $num .= $new_num."\n";
                    $price .= $new_price."\n";
                }
            }
            $items[] = [
                $value['id']??0,
                $value['trade_no']." ",
                $value['name'],
                $value['mobile'],
                $name,
                $num,
                $price,
                $value['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();
            },
        ];
    }
}
