<?php

namespace App\Admin\Forms;

use App\Models\BlindBoxList;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\Log;

class CreateBlindBoxForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function CreateBox($form, $status)
    {
        BlindBoxList::query()->create([
            'projectName' => $form['projectName'],
            'price' => $form['price'],
            'max_participants_num' => $form['max_participants_num'],
            'min_participants_num' => $form['min_participants_num'],
            'start_time' => $form['start_time'],
            'end_time' => $form['end_time'],
            'winner_num' => $form['winner_num'],
            'project_icon' => $form['project_icon'],
            'box_num' => $form['box_num'],
            'rules' => $form['rules'],
            'status' => $status
        ]);
    }

    // 处理请求
    public function handle(array $form)
    {
        if (app()->isLocal()) {
            $form['project_icon'] = url("/uploads/{$form['project_icon']}");
        } else {
            # 线上环境
            $form['project_icon'] = url("/storage/{$form['project_icon']}");
        }
        $start_time = ToTimestamp($form['start_time']);
        $end_time = ToTimestamp($form['end_time']);
        $status = getBlindBoxStatus($start_time, $end_time);
        # 创建盲盒
        for ($i = 0; $i < $form['box_num']; $i++) {
            self::CreateBox($form, $status);
        }
        return $this->response()->success('添加成功')->redirect('/blindBoxSetting/setting');
    }

    public
    function form()
    {
        $this->text('projectName')->required();
        $this->text('price')->required();
        $this->number('max_participants_num')->default(5)->min(0);
        $this->number('min_participants_num')->default(1)->min(0);
        $this->datetime('start_time')->required();
        $this->datetime('end_time')->required();
        $this->number('winner_num', '中奖人数')->default(1)->min(0);
        $this->number('box_num', '生成盲盒数量')->default(1)->min(0);
        $this->number('can_invite_num', '最高邀请人数')->default(1)->min(0);
        $this->number('invite_up_rate', '单次邀请增加的几率')->default(1)->min(0);
        $this->file('project_icon', '项目图片')->accept('jpg,png,gif,jpeg', 'image/*')
            ->disk('admin')->autoUpload(true)->uniqueName()->required();
        $this->textarea('rules', '规则')->required();
    }
}
