<?php

namespace App\Exports;

use App\Models\Order;
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 OrdersExport implements FromArray,WithHeadings,WithStyles,WithEvents
{
    protected $keyword;
    protected $pay_status;
    protected $status;
    protected $agency_id;
    protected $header;

    public function __construct($data)
    {
        $this->keyword = $data['keyword']??null;
        $this->pay_status = $data['pay_status']??null;
        $this->status = $data['status']??null;
        $this->agency_id = $data['agency_id']??null;
    }

    public function array():array
    {
        $orders = [];
        Order::query()
            ->with([
                'user:id,name,mobile,avatar',
                'service:id,title,pic',
                'agency:id,name,mobile',
                'commission' => function($commission){
                    $commission->with(['service_user:user_id,name,mobile'])->select('id','order_id','role','user_id');
                },
                "recommendUser",
            ])
            ->serviceOrder()
            ->when($this->keyword !== null,function ($query){
                $query->where(function ($query){
                    $query->where('name', 'like', '%' . $this->keyword . '%')
                        ->orWhere('mobile', 'like', '%' . $this->keyword . '%');
                });
            })
            ->when($this->pay_status !== null,function ($query){
                $query->where('pay_status',$this->pay_status);
            })
            ->when($this->status !== null,function ($query){
                $query->where('status',$this->status);
            })
            ->when($this->agency_id !== null,function ($query){
                $query->where('agency_id',$this->agency_id);
            })
            ->orderByDesc('id')
            ->get()
            ->each(function ($order) use (&$orders){
                $commission_arr = [
                    1=>'',
                    2=>'',
                    3=>'',
                    4=>'',
                    5=>'',
                ];
                foreach ($order->commission as $commission){
                    $commission_arr[$commission->role] .= $commission->service_user?$commission->service_user->name:'' .',';
                }
                $order_item = [
                    $order->id,
                    $order->price,
                    ['UNPAID'=>'未支付','PAID'=>'已支付'][$order->pay_status],
                    $order->offline_order?'虚拟订单':'线上订单',
                    ['NOTSTART'=>'未开始','STARTING'=>'进行中','FINISHED'=>'已结束', 'SUSPEND'=>"暂停中"][$order->status],
                    $order->trade_no.' ',
                    $order->desc,
                    $order->user?->name??null,
                    $order->user?->mobile??null,
                    $order->agency?->name??null,
                    $order->agency?->mobile??null,
                    $order->recommendUser->name??"",
                    $order->recommendUser->mobile??"",
                    $commission_arr[2],
                    $commission_arr[3],
                    $commission_arr[4],
                    $commission_arr[5],
                ];
                $orders[] = $order_item;
            });
        return $orders;
    }


    public function headings(): array
    {
        return [
            ['订单信息', '', '', '', '', '', '', '联系人', '', '子公司信息', '', '服务人员', '', '', '', ''],
            ['订单id', '订单价格', '订单状态', '订单类型', '服务状态', '订单号', '订单描述', '姓名', '电话', '负责人姓名', '电话', '推荐人-姓名', "推荐人-手机号", '主教练', '副教练', '客服', '企业介绍人']
        ];
    }


    public function styles(Worksheet $sheet)
    {
        $sheet->getStyle('F')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);

        $sheet->mergeCells('A1:G1');
        $sheet->mergeCells('H1:I1');
        $sheet->mergeCells('J1:K1');
        $sheet->mergeCells('L1:P1');

        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();
            },
        ];
    }
}
