<?php

namespace Modules\Configuration\Actions;

use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Exception;
use Illuminate\Http\Request;
use Modules\Configuration\Models\Configuration;

class UpdateSource extends RowAction
{

    public $name = '更改配置项';

    public function handle(Configuration $model, Request $request): Response
    {
        try {
            $source = $request->source;
            $array  = explode("\r\n", $source);
            $data   = [];
            foreach ($array as $value) {
                $key        = explode("|", $value)[0];
                $params     = explode("|", $value)[1];
                $data[$key] = $params;
            }
            $model->source      = $data;
            $model->paramsValue = '';
            $model->save();

            return $this->response()->success('更改成功')->refresh();
        } catch (Exception $e) {
            return $this->response()->error($e->getMessage())->refresh();
        }
    }

    public function form()
    {
        $this->textarea('source', '配置项')->required();
        $this->textarea('示例')->disable()->value("key|value\r\nkey|value\r\n非必要请不要随意更改");
        $this->confirm('确认改变当前配置项？(删除值)');
    }

}
