<?php

namespace App\Admin\Controllers\Episode;

/* 设置内存 保证上传到 OSS */
ini_set('memory_limit', '512M');

use App\Models\Episode;
use App\Models\EpisodesList;
use Dcat\Admin\Form;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Http\Controllers\AdminController;

class EpisodesBatchUploadController extends AdminController
{
    private $id;

    public function index(Content $content, $id = 0)
    {
        $this->id = $id;
        $episode  = Episode::find($id);
        $form     = $this->form();

        return $content
            ->title($episode->name)
            ->breadcrumb(
                ['text' => $episode->name, 'url' => "/episodes/{$episode->id}/lists"],
                ['text' => '剧集上传'],
            )
            ->body($form)
            ->description('剧集上传');
    }

    public function store($id = 0)
    {
        $req      = request()->post();
        $form     = new Form();
        $response = $form->response();
        if (isset($req['lists']) && empty($req['lists'])) {
            return $response->error('请上传剧集');
        } elseif (!isset($req['lists'])) {
            return $this->form()->store();
        }
        $lists = explode(',', $req['lists']);
        $sort  = EpisodesList::where('episodes_id', $id)->max('sort');

        foreach ($lists as $list) {
            $episode              = new EpisodesList();
            $episode->episodes_id = $id;
            $episode->sort        = ++$sort;
            $episode->url         = $list;
            $episode->save();
        }

        return $response->success(__('admin.save_succeeded'))
            ->redirect(admin_url("/episodes/{$id}/lists"));
    }

    public function form()
    {
        $id = $this->id;

        return new Form(new EpisodesList(), function (Form $form) use ($id) {
            $form->action(admin_url("/episodes/batch/{$id}/upload"));
            $form->tools(
                function (Form\Tools $tools) {
                    $tools->disableList();
                }
            );
            $form->disableHeader();
            $form->disableCreatingCheck();
            $form->disableEditingCheck();
            $form->disableViewCheck();

            $form->multipleFile('lists', '剧集')
                ->mimeTypes('video/*')
                ->chunkSize(4096)
                ->maxSize(1024 * 1024)
                ->saveFullUrl()
                ->uniqueName()
                ->autoUpload()
                ->autoSave(false)
                ->removable(false)
                ->required();

            $form->saved(function (Form $form) use ($id) {
                return $form
                    ->response()
                    ->success(trans('admin.update_succeeded'))
                    ->redirect(admin_url("/episodes/{$id}/lists"));
            });
        });
    }
}
