<?php

namespace App\Admin\Controllers\Activity;

use App\Models\ActivityRule;
use App\Models\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Support\MessageBag;
use RuLong\Identity\Models\Identity;

class RuleController extends AdminController
{
    protected $title = '规则管理';

    protected function grid(): Grid
    {
        $grid = new Grid(new ActivityRule);

        $grid->actions(function ($actions) {
            $actions->disableView();
        });

        $grid->column('id', '#ID#');
        $grid->column('title', '规则名称');
        $grid->column('code', '规则编号');
        $grid->column('full', '满足金额');
        $grid->column('take', '扣除金额');
        $grid->status('状态')->switch([
            'on'  => ['value' => 1, 'text' => '正常', 'color' => 'primary'],
            'off' => ['value' => 0, 'text' => '关闭', 'color' => 'danger'],
        ]);

        $grid->column('created_at', '创建时间');
        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form(): Form
    {
        $form = new Form(new ActivityRule);

        $form->text('title', '规则名称')->required();
        $form->text('code', '规则编号')->required()->help('列：YSD-full100-15');

        $form->hidden('full', '满足金额')->required()->default(0);
        $form->hidden('take', '抵扣金额')->required()->default(0);

        $form->switch('status', '状态')->default(1);
        $form->saving(function (Form $form) {
            if ($form->code) {
                $code = $form->code;

                $ticket = explode('-', $code);
                if (! is_array($ticket) || count($ticket) != 3) {
                    $error = new MessageBag([
                        'title'   => '错误',
                        'message' => '规则编号格式错误',
                    ]);

                    return back()->withInput()->with(compact('error'));
                }

                $full  = $ticket[1]; //full100
                $price = $ticket[2];
                preg_match('/\d+/', $full, $match);

                $form->full = $match[0];
                $form->take = $price;
            }

        });

        return $form;
    }
}
