<?php

namespace App\Exports;

use App\Models\Talk;
use App\Models\TalkComment;
use App\Models\TalkStar;
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 TalkExport 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 Talk::STATUS_CLOSE:
                    $status = '关闭';
                    break;
                default:
                    $status = '开启';
                    break;
            }

            switch ($value->type){
                case Talk::TYPE_VOTE:
                    $type = '投票';
                    break;
                default:
                    $type = '讨论';
                    break;
            }
            $star = TalkStar::where('talk_id',$value->id)
                ->count();
            $comment = TalkComment::where('talk_id',$value->id)
                ->count();

            $items[] = [
                $value->id,
                $value->title,
                $star,
                $comment,
                $type,
                $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();
            },
        ];
    }
}
