<?php

namespace App\Domains\Stats\Exports;

use App\Dicts;
use App\Core\AbstractExport;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Dipper\Excel\Concerns\WithRows;
use Dipper\Excel\Concerns\FromQuery;
use App\Exceptions\NotAllowedException;
use Dipper\Excel\Concerns\WithHeadings;
use Illuminate\Database\Eloquent\Builder;
use Dipper\Excel\Concerns\WithColumnFormatting;
use App\Domains\Virtual\Services\CompanyService;
use App\Domains\Virtual\Services\PackageService;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use App\Domains\Virtual\Repositories\OrderCardPartitionRepository;

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

    public static $types = ['用户', '用户', '增值包', '增值包'];

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

    /**
     * @return Builder
     */
    public function query()
    {
        $repository = app(OrderCardPartitionRepository::class);

        $select = [
            'sim',
            'company_id',
            'package_id',
            'type',
            DB::raw('CASE "type" WHEN 3 THEN SUM(counts) ELSE count(*)  END AS counts'),
            'unit_price'
        ];

        $builder = $repository->forceNoReset()->select($select)
            ->withConditions($this->conditions)
            ->groupBy('company_id', 'package_id', 'type', 'unit_price', 'sim')
            ->orderBy('sim');

        return $builder;
    }

    public function headings(): array
    {
        $headings = [
            'SIM',
            '运营商',
            '企业名称',
            '套餐名称',
            '数量',
            '套餐单价(元/月)',
        ];

        return $headings;
    }

    /**
     * @param mixed $row
     *
     * @return mixed
     */
    public function rows($rows)
    {
        $carrierOperators = app(Dicts::class)->get('carrier_operator');

        $array = [];

        foreach ($rows as $item) {
            $company = CompanyService::load($item->company_id);
            $package = PackageService::load($item->package_id);
            $month_price = sprintf('%.02f', $item->unit_price/100/$package['service_months']);

            $array[] =  [
                $item['sim'],
                $carrierOperators[$package['carrier_operator']],
                $company['name'],
                $package['name'],
                $item['counts'],
                $month_price,
            ];
        }

        return $array;
    }

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

    /**
     * 表格标题
     *
     * @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;
    }
}
