<?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 ShopOrderExport implements FromArray,WithHeadings,WithStyles,WithEvents
{
    public function __construct($data)
    {
        $this->data = $data;
    }

    public function array():array
    {
        $items = [];
        foreach ($this->data->toArray() as $value){
            $items[] = [
                $value['user']['name']??'',
                $value["name"],
                $value["mobile"],
                $value['recommend_user']["name"]??"",
                $value['recommend_user']["mobile"]??"",
                $value['shop_info']['title']??'',
                $value['shop_info']['sku']['name']??"",
                $value['price'],
                $value['num'],
                $value['trade_no'],
                $value['created_at']
            ];

        }
        return $items;
    }

    public function headings(): array
    {
        return [
            ['昵称', "收件人-姓名", "收件人-手机号", "推荐人-姓名","推荐人-手机号", '商品名称', '商品规格','商品价格','购买数量','订单号','购买时间']
        ];
    }

    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();
            },
        ];
    }
}
