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

    public function array():array
    {
        $items = [];
        foreach ($this->data as $value){
            switch ($value->status){
                case 0:
                    $status = '已提交';
                    break;
                case 1:
                    $status = '处理中';
                    break;
                case 2:
                    $status = '已处理';
                    break;
                case 3:
                    $status = '已取消';
                    break;
                default:
                    $status = '已提交';
                    break;
            }
            $items[] = [
                $value->work_order,
                $value->group_id,
                $value->group_name,
                $value->user_name,
                $value->user_mobile,
                $status,
                $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();
            },
        ];
    }
}
