<?php

namespace App\Admin\Controllers;

use App\Models\ShareConfig;
use Dcat\Admin\Form;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Box;
use Dcat\Admin\Widgets\Form as WidgetForm;

class ShareConfigController extends AdminController
{

    public function index(Content $content)
    {

        return $content
            ->title(trans('share-config.title'))
            ->body(function (Row $row) {
                $row->column(8, function (Column $column) {
                    $form = new WidgetForm();
                    $shareConfig = ShareConfig::orderBy('id','asc')->first()->toArray();
                    $form->width(9, 2);
                    $form->text('id','ID')->value($shareConfig['id'])->readOnly();
                    $form->text('price','推荐奖励')->value($shareConfig['price']);
                    $form->text('share_desc','分销说明')->value($shareConfig['share_desc']);
                    $form->text('withdraw_discount','提现手续费,百分比')->value($shareConfig['withdraw_discount']);
                    $form->text('withdraw_desc','提现说明')->value($shareConfig['withdraw_desc']);
                    $form->switch('is_open', '是否开启？')->default($shareConfig['is_open']);
                    $form->action('shareSetting/save');
                    $column->append(Box::make(trans('admin.edit'), $form));
                });
            });
    }

    public function save()
    {
        $req = request()->post();
        $shareConfig = ShareConfig::orderBy('id','asc')->first();
        $shareConfig->price = $req['price'];
        $shareConfig->share_desc = $req['share_desc'];
        $shareConfig->withdraw_discount = $req['withdraw_discount'];
        $shareConfig->withdraw_desc = $req['withdraw_desc'];
        $shareConfig->is_open = $req['is_open'];
        $shareConfig->save();
        $form = new Form();
        $response = $form->response();
        return $response->success(__('admin.save_succeeded'));
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new ShareConfig(), function (Form $form) {
            $id = $form->getKey();
            $form->text('id', 'ID');
            $form->text('price','推荐奖励');
            $form->text('share_desc','分销说明');
            $form->text('withdraw_discount','提现手续费,百分比');
            $form->text('withdraw_desc','提现说明');
            $form->switch('is_open', '是否开启？')->default(1);

        })->saved(function (Form $form, $result) {
            $response = $form->updates()->response();

            if ($result) {
                return $response->success(__('admin.save_succeeded'));
            }

            return $response->info(__('admin.nothing_updated'));
        });
    }
}
