<?php

namespace App\Admin\Actions;

use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Replicate extends RowAction
{

    public $name = '复制活动';

    public function dialog()
    {
        $this->confirm('确定复制活动链接么？');
    }

    public function handle(Model $model)
    {
        try {
            DB::transaction(function () use ($model) {
                $new         = $model->replicate();
                $new->status = 0;
                $new->save();
                foreach ($model->items as $item) {
                    $new->items()->create([
                        'name'  => $item->name,
                        'cover' => $item->cover,
                        'desc'  => $item->desc,
                        'desc2' => $item->desc2,
                    ]);
                }
            });

            return $this->response()->success('活动链接复制完成')->refresh();
        } catch (\RuntimeException $exception) {
            return $this->response()->error('活动链接复制出错了')->refresh();
        }
    }

}
