<?php

namespace App\Admin\Extensions\ToolBar\BatchActions;

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

class CopyIdsAction extends BatchAction
{
    /**
     * 标题
     *
     * @return string
     */
    public function title()
    {
        return "<i class='fa fa-copy'></i>&nbsp;获取选中ID&nbsp;";
    }

    // 确认弹窗信息
    public function confirm()
    {
        return '已复制到粘贴板！';
    }

    // 处理请求
    public function handle(Request $request) {}

    /**
     * 设置动作发起请求前的回调函数，返回false可以中断请求.
     *
     * @return string
     */
    public function actionScript()
    {
        $warning = __('No data selected!');

        return <<<JS
function (data, target, action) { 
    var key = {$this->getSelectedKeysScript()}
    if (key.length === 0) {
        Dcat.warning('{$warning}');
        return false;
    }

    // 设置主键为复选框选中的行ID数组
    action.options.key = key;
    var keyStr = key.join(',');
    const input = document.createElement('textarea');
    document.body.appendChild(input);
    input.value = keyStr;
    input.select();
    if (document.execCommand('copy')) {
        document.execCommand('copy');
        Dcat.success('复制成功');
    }
    input.remove();
}
JS;
    }
}
