<?php

namespace App\Exports;

use App\Models\Partner;
use App\Models\User;
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 UserExport implements FromArray,WithHeadings,WithStyles,WithEvents
{
    public function __construct($data)
    {
        $this->keyword = $data['keyword']??null;
    }

    public function array():array
    {
        $items = [];
        $keyword = $this->keyword;
        $list = User::when($keyword,function ($query) use ($keyword){
            $query->where(function ($query)use ($keyword){
                $query->where("name", 'like', '%'.$keyword.'%')
                    ->orWhere('mobile', 'like', '%'.$keyword.'%');
            });
        })->join('wechats','wechats.user_id','=','users.id')
            ->select('users.*')
            ->where('wechats.type','mp')
            ->orderByDesc('id')
            ->get();

        foreach ($list as $value){
            $sex = '男';
            if($value->sex == 2){
                $sex = '女';
            }
            $items[] = [
                $value->id,
                $value->name,
                $value->mobile,
                $value->avatar,
                $sex,
                $value->birthday,
                $value->unit,
                $value->is_subscribe,
                $value->stature,
                $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();
            },
        ];
    }
}
