<?php

namespace App\Exports;

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

    public function array():array
    {
        $items = [];
        foreach ($this->data as $value){
            if($value->status == Activity::STATUS_CLOSE){
                $status = "下架";
            }else{
                $status = "下架";
            }
            if($value->is_free == Activity::FREE){
                $is_free = "免费";
            }else{
                $is_free = "付费";
            }
            if($value->is_online == Activity::ONLINE){
                $is_online = "线上";
            }else{
                $is_online = "线下";
            }
            $items[] = [
                $value->id,
                $value->title,
                $value->sub_title,
                $value->start_time,
                $value->end_time,
                $value->apply_end_time,
                $status,
                $is_free,
                $is_online,
                $value->address,
                $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();
            },
        ];
    }
}
