<?php
namespace App\Domains\Export\Services;

use App\Dicts;
use App\Core\Service;
use App\Core\AbstractExport;
use Dipper\Excel\Facades\Excel;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use App\Domains\Export\Repositories\ExportRepository;

class ExportService extends Service
{
    protected $exportRepository;

    protected static $status = ['数据准备中', '开始写入', '写入结束', '保存成功', '任务失败'];

    /**
     * 构造函数
     *
     * @return void
     */
    public function __construct(ExportRepository $exportRepository)
    {
        $this->exportRepository = $exportRepository;
    }

    /**
     * 导出记录
     *
     * @param array $conditions
     * @return void
     */
    public function index(array $conditions = [])
    {
        $limit = $conditions['limit'] ?? 20;

        $exports = $this->exportRepository->withConditions($conditions)->applyConditions()->paginate($limit);

        $status = app(Dicts::class)->get('export_status');

        $exports->transform(function ($item) use ($classes, $status) {
            $exists = Storage::disk($item->disk)->exists($item->filename);

            if ($item->status === 3) {
                if (!$exists = Storage::disk($item->disk)->exists($item->filename)) {
                    $item->status = 5;
                }
            }

            $url = $item->status === 3 ? Storage::disk($item->disk)->url($item->filename) : '';

            $conditions = json_encode(array_except($item->conditions ?? [], ['page', 'limit', 'orderBy', 'sortedBy']), 256);

            return [
                'id' => $item->id,
                'tag' => $item->tag,
                'filesize' => human_filesize($item->filesize),
                'dateline' => !$item->conditions['starttime'] ? '所有' : $item->conditions['starttime'] . ' 至 ' . $item->conditions['endtime'],
                'conditions' => $conditions,
                'status' => $item->status,
                'status_name' => $status[$item->status],
                'url' => $url,
                'created_at' => (string)$item->created_at,
                'updated_at' => (string)$item->updated_at,
            ];
        });

        return $exports;
    }

    /**
     * 删除
     *
     * @return bool
     */
    public function destroy($ids)
    {
        $ids = is_array($ids) ? $ids : [$ids];

        $this->exportRepository->destroy($ids);

        return true;
    }

    /**
     * 导出
     */
    public static function store($export, $disk, $queue = false)
    {
        if (!$queue) {
            Excel::store($export, $export->filename, $disk);
            $url = Storage::disk($disk)->url($export->filename);
            return $url;
        }

        Excel::queue($export, $export->filename, $disk);
    }
}
