<?php

namespace App\Domains\Stats\Exports;

use App\Core\AbstractExport;
use Illuminate\Support\Carbon;
use App\Exceptions\NotAllowedException;
use Dipper\Excel\Concerns\WithHeadings;
use Dipper\Excel\Concerns\FromCollection;
use App\Domains\Stats\Services\CompanyReportService;

class CompanyReportExport 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(CompanyReportService::class)->index($this->conditions)->map(function ($item) {
            return collect([
                'company_name' => $item->company_name,
                'package_name' => $item->package_name,
                'service_months' => $item->service_months,
                'unit_price' => $item->unit_price,
                'month_price' => $item->month_price,
                'members' => $item->members,
                'counts' => $item->counts,
                'total_price' => $item->total_price,
                'type_name' => $item->type_name,
            ]);
        });

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

        return $orders;
    }

    public function headings(): array
    {
        return [
            '企业名称',
            '套餐名称',
            '套餐周期(月)',
            '套餐价格(元/周期)',
            '套餐单价(元/月)',
            '收费人数',
            '收费数',
            '收费总价(元)',
            '收费类型'
        ];
    }

    /**
     * 表格标题
     *
     * @return string
     */
    public function title(): string
    {
        $title = $this->tag();

        if (($conditions = $this->conditions) && $conditions['month']) {
            $title .= Carbon::parse($conditions['month'])->format('Ym');
        }

        return $title ?? '列表';
    }

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

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

        return $tag;
    }
}
