<?php

namespace App\Admin\Extensions\ToolBar\BatchActions;

use Dcat\Admin\Grid\BatchAction;
use Illuminate\Http\Request;

class CopyBatchAction extends BatchAction
{
    // 模型类名
    protected $model;

    // 复制弹窗标题
    protected $copyTitle;

    // 不需要复制的字段
    protected $except;

    public function __construct(?string $model = null, string $copyTitle = '', ?array $except = null)
    {
        $this->model = $model;
        $this->copyTitle = $copyTitle;
        $this->except = $except;
    }

    /**
     * 标题
     *
     * @return string
     */
    public function title()
    {
        return "<i class='fa fa-copy'></i>&nbsp;批量复制&nbsp;";
    }

    // 确认弹窗信息
    public function confirm()
    {
        return "您确定要批量复制{$this->copyTitle}吗？";
    }

    // 处理请求
    public function handle(Request $request)
    {
        // 获取选中ID数组
        $keys = $this->getKey();

        // 获取 parameters 方法传递的参数
        $model = $request->get('model');
        $except = $request->get('except');

        // 复制数据
        $newIds = [];
        foreach ($keys as $primaryId) {
            $qb = $model::find($primaryId)->replicate($except);
            $qb->save();
            $newIds[] = $qb->id;
        }

        // 返回响应结果并刷新页面
        $newIdsString = implode(',', $newIds);

        return $this->response()->alert(true)->success('批量复制成功。新ID：')->detail($newIdsString)->refresh();
    }

    /**
     * 设置要POST到接口的数据
     *
     * @return array
     */
    public function parameters()
    {
        return [
            // 把模型类名传递到接口
            'model' => $this->model,
            // 不需要复制的字段
            'except' => $this->except,
        ];
    }
}
