<?php

namespace App\Domains\Virtual\Exports;

use App\Core\AbstractExport;
use Illuminate\Support\Facades\DB;
use Dipper\Excel\Concerns\WithRows;
use Dipper\Excel\Concerns\FromQuery;
use Dipper\Excel\Concerns\WithHeadings;
use Illuminate\Database\Eloquent\Collection;
use App\Domains\Virtual\Services\CardService;
use Dipper\Excel\Concerns\WithColumnFormatting;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use App\Domains\Virtual\Repositories\OrderCardPartitionRepository;

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

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

    public function query()
    {
        $this->conditions['type'] = 0;
        $builder = app(OrderCardPartitionRepository::class)->forceNoReset()->withConditions($this->conditions)->orderBy('sim')->applyConditions();

        return $builder;
    }

    /**
     * @param mixed $row
     *
     * @return mixed
     */
    public function rows($rows)
    {
        $rows = CardService::transformer(new Collection($rows));

        $array = [];

        foreach ($rows as $item) {
            $array[] = [
                $item['id'],
                $item['sim']."\t",
                $item['imsi']."\t",
                $item['iccid']."\t",
                $item['carrier_operator'],
                $item['company_name'],
                $item['package_name'],
                $item['virtual_activated_at'],
                $item['status_name'],
                $item['created_at'],
                $item['service_start_at'],
                $item['service_end_at'],
            ];
        }

        return $array;
    }

    public function headings(): array
    {
        return [
            '客户编号',
            'SIM',
            'IMSI',
            'ICCID',
            '运营商',
            '企业名称',
            '套餐名称',
            '激活时间',
            '状态',
            '创建时间',
            '服务开始时间',
            '服务结束时间',
        ];
    }

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