<?php

namespace App\Domains\Virtual\Exports;

use Carbon\Carbon;
use App\Core\AbstractExport;
use Dipper\Excel\Concerns\WithRows;
use Dipper\Excel\Concerns\FromQuery;
use App\Exceptions\NotExistException;
use App\Models\Virtual\FlowPoolMonth;
use Dipper\Excel\Concerns\WithHeadings;
use Dipper\Excel\Concerns\WithColumnFormatting;
use App\Domains\Virtual\Services\PackageService;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use App\Domains\Virtual\Services\FlowPoolService;
use App\Domains\Virtual\Repositories\FlowPoolRepository;

class FlowPoolExportDetailExport extends AbstractExport implements FromQuery, WithHeadings, WithRows, WithColumnFormatting
{
    public $conditions;

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

    /**
     * @return Builder
     */
    public function query()
    {
        $pool_id = $this->conditions['pool_id'];
        $month = Carbon::parse($this->conditions['month']);

        $table = app(FlowPoolMonth::class)->getTable() . '_' . $month->format('Ym');

        return app(FlowPoolMonth::class)->setTable($table)->where('pool_id', $pool_id)->select(['package_id', 'sim', 'mebibyte'])->orderBy('sim');
    }

    public function headings(): array
    {
        $headings = [
            'SIM',
            '套餐名称',
            '保底流量(M)',
            '已用流量(M)',
        ];

        return $headings;
    }

    /**
     * @param mixed $row
     *
     * @return mixed
     */
    public function rows($rows)
    {
        $pool_id = $this->conditions['pool_id'];
        $month = Carbon::parse($this->conditions['month']);

        if (!$flowPool = app(FlowPoolRepository::class)->find($pool_id)) {
            throw new NotExistException('流量池不存在或已删除');
        }

        $flowPool = FlowPoolService::transformer(collect([$flowPool]), $month)->first();

        $minimum_settings = $flowPool['settings'][0]['minimum_settings'] ?? [];

        $minimum_flows =  array_pluck($minimum_settings, 'flows', 'package_id');

        $array = [];

        foreach ($rows as $item) {
            $array[] =  [
                $item['sim'],
                PackageService::load($item['package_id'])['name'],
                $minimum_flows[$item['package_id']] ?? 0,
                $item['mebibyte'],
            ];
        }

        return $array;
    }

    /**
     * @return array
     */
    public function columnFormats(): array
    {
        return [
            'A' => NumberFormat::FORMAT_NUMBER,
        ];
    }
}
