<?php
namespace App\Domains\Virtual\Http\Controllers;

use App\Core\Controller;
use Illuminate\Http\Request;
use App\Exceptions\NotAllowedException;
use App\Domains\Virtual\Exports\CardExport;
use App\Domains\Virtual\Services\CardService;
use App\Domains\Export\Services\ExportService;
use App\Domains\Virtual\Repositories\OrderCardPartitionRepository;

class CardController extends Controller
{
    protected $request;
    protected $cardService;

    /**
     * 构造函数，自动注入.
     */
    public function __construct(Request $request, CardService $cardService)
    {
        $this->request = $request;
        $this->cardService = $cardService;
    }

    /**
     * 列表.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $conditions = $this->request->all();
        $conditions['limit'] = $this->request->get('limit', 20);

        if ($conditions['id']) {
            $conditions['id'] = intval(str_replace('No', '', $conditions['id']));
        }

        $cards = $this->cardService->index($conditions);

        return res($cards, '卡列表', 201);
    }

    /**
     * 导出.
     *
     * @return \Illuminate\Http\Response
     */
    public function export()
    {
        $conditions = $this->request->except(['page', 'limit']);

        if ($conditions['id']) {
            $conditions['id'] = intval(str_replace('No', '', $conditions['id']));
        }

        $conditions['type'] = 0;
        $total =  app(OrderCardPartitionRepository::class)->withConditions($conditions)->applyConditions()->count();

        if ($total > 250000) {
            throw new NotAllowedException('一次性导出数据超过25万条，请添加筛选条件后重试');
        }

        try {
            $export = new CardExport($conditions);
            $queue = $total > 30000;
            $url = ExportService::store($export, $disk = 'public', $queue);
        } catch (\Exception $e) {
            throw $e;
        }

        return res($url, '导出成功', 201);
    }
}
