<?php

namespace App\Admin\Actions\Form;

use App\Models\EpisodesList;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class BatchEditEpisodeListForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        // 选择的行
        $ids = explode(',', $input['id'] ?? null);
        if (empty($ids)) {
            return $this->response()->error('参数错误');
        }

        $isFree      = $input['is_free']      ?? null;
        $salePrice   = $input['sale_price']   ?? 0;
        $originPrice = $input['origin_price'] ?? 0;

        foreach ($ids as $id) {
            EpisodesList::where('id', $id)->update([
                'is_free'      => $isFree,
                'sale_price'   => $salePrice,
                'origin_price' => $originPrice,
            ]);
        }

        return $this->response()->success('修改成功')->refresh();
    }

    public function form()
    {
        $this->radio('is_free')
            ->options(config('global.episode_free'))
            ->when(0, function (Form $form) {
                $form->number('origin_price')->min(1);
                $form->number('sale_price')->min(1);
            })->default(1);

        $this->hidden('id')->attribute('id', 'batch-id');
    }

    public function default()
    {
    }
}
