<?php

namespace App\Exports;

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

    public function array():array
    {
        $items = [];
        foreach ($this->data as $value){
            switch ($value->operate_type){
                case OperateStockLog::OPERATE_TYPE_OUT:
                    $type = '出库';
                    break;
                default:
                    $type = '入库';
                    break;
            }
            $operate_name = $value->operate_name;
            if(empty($operate_name)){
                $operate_name = $value->order_id;
            }
            $items[] = [
                $value->name,
                $type,
                $operate_name,
                $value->operate_mobile,
                $value->num,
                $value->remark,
                $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();
            },
        ];
    }
}
