<?php

namespace App\Exports;

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

    public function array():array
    {
        $items = [];
        foreach ($this->data as $value){
            $agency_type = "个人";
            if(!empty($value->agency_id) && !empty($value->agencyInfo)){
                $agency_type = "市级分公司:".$value->agencyInfo->city;
            }
            $items[] = [
                $value->collaboratorInfo->user_id,
                $value->collaboratorInfo->name,
                $value->collaboratorInfo->mobile,
                $value->num,
                $agency_type,
                $value->agreement_number,
                $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();
            },
        ];
    }
}
