<?php

namespace App\Classes\Modules\Exports\Services;

use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Illuminate\Http\Request;

class ExportsAnalyticBillingTransactions implements FromCollection, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{
    use Exportable;

    private $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function headings(): array
    {
        return [
            'Booking Id',
            'Service Type',
            'Payment Method',
            'Company Id',
            'Customer Segment',
            'Company Create Date',
            'Company Type',
            'Supplier Id',
            'Customer Payment',
            'Customer Rate',
            'Customer Service Charge',
            'Customer Payment Date',
            'Original Amount',
            'Supplier Payment',
            'Supplier Rate',
            'Supplier Service Charge',
            'Supplier Payment Date'
        ];
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function collection()
    {
        return Transaction::where('type', 3)
        ->where('created_at', '>=', Carbon::now()->subYear())
        ->orderBy('created_at', 'desc')
        ->take(500)
        ->get();
    }

    /**
     * @param $transaction
     * @return array
     */
    public function map($transaction): array
    {

        $bill = $transaction;
        $payment = $transaction->owner;
        $booking = $payment->owner;
        $bank = $booking->bank;
        if($payment->bank){
            $bank = $payment->bank;
        }
        $company = $booking->company;
        $ecommerce = str::contains($bank->bank_name, ['浙江网商银行']);

        return [
            $booking->id,
            $ecommerce ? '1688' : ($booking->service->id === 4 ? '1688' : $booking->service->name ),
            PaymentMethodType::PAYMENT_METHODS_ID[$payment->payment_method],
            $company->id,
            $company->segments->implode('name', ', '),
            $company->created_at,
            $company->type === 0 ? 'Personal' : 'Company',
            $bill->issuerCompany->name,
            $payment->amount,
            $payment->currency_rate,
            $payment->service_charge,
            $payment->created_at,
            $payment->original_amount,
            $bill->amount,
            $bill->currency_rate,
            $bill->service_charge,
            $bill->created_at
        ];
    }
}
