<?php

namespace App\Domains\Stats\Exports;

use App\Core\AbstractExport;
use App\Exceptions\NotAllowedException;
use Dipper\Excel\Concerns\WithHeadings;
use Dipper\Excel\Concerns\FromCollection;
use App\Domains\Stats\Services\OrderService;

class OrderExport extends AbstractExport implements FromCollection, WithHeadings
{
    public $conditions;

    public static $types = ['销售', '续费', '续费包', '加油包'];

    public function __construct(array $conditions = [])
    {
        $this->conditions = $conditions;
        parent::__construct();
    }

    public function collection()
    {
        $orders = app(OrderService::class)->index($this->conditions)->map(function ($item) {
            return collect([
                'company_name' => $item->company_name,
                'package_name' => $item->package_name,
                'pay_channel_name' => $item->pay_channel_name,
                'unit_price' => $item->unit_price,
                'members' => $item->members,
                'counts' => $item->counts,
                'custom_price' => $item->custom_price,
            ]);
        });

        $orders->push([
            '总计',
            '',
            '',
            '',
            array_sum($orders->pluck('members')->toArray()) ?: 0,
            array_sum($orders->pluck('counts')->toArray()) ?: 0,
            array_sum($orders->pluck('custom_price')->toArray()) ?: 0,
        ]);

        return $orders;
    }

    public function headings(): array
    {
        return [
            '企业名称',
            '套餐名称',
            '支付方式',
            '单价',
            '人数',
            '数量',
            '总金额',
        ];
    }

    /**
     * 类型
     *
     * @return void
     */
    protected function tag()
    {
        if ((!$tag = self::$classes[get_class($this)]) || !self::$types[$this->conditions['type']]) {
            throw new NotAllowedException('类型不允许');
        }

        $tag = self::$types[$this->conditions['type']] . $tag;

        return $tag;
    }
}
