<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Item;
use App\Models\Vote;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;

class ItemController extends Controller
{

    public function index(Content $content, Vote $vote)
    {
        return $content
            ->header($vote->title)
            ->description('投票列表')
            ->body($this->grid($vote));
    }

    protected function grid($vote)
    {
        $grid = new Grid(new Item);
        $grid->filter(function (Grid\Filter $v) {
            $v->column(1 / 2, function (Grid\Filter $f) {
                $f->like('name', '姓名');
            });
        });
        $grid->model()->where('vote_id', $vote->id)->orderBy('sort');
        $grid->column('cover')->image('', 80);
        $grid->column('id', '#ID#');
        $grid->column('name');
        $grid->column('sort');
        $grid->column('得票数')->display(function () {
            return $this->logs()->where('result', 1)->count();
        });
        $grid->column('created_at', '创建时间')->date('Y-m-d H:i:s');

        return $grid;
    }

    function create(Content $content, Vote $vote)
    {
        return $content
            ->header($vote->title)
            ->description('新增条目')
            ->body($this->form($vote));
    }

    function form($vote)
    {
        $form = new Form(new Item);

        $form->hidden('vote_id')->value($vote->id);
        $form->text('name', '姓名');
        $form->number('sort', '排序')
            ->default(1)
            ->help('正序排序');
        $form->textarea('desc', '竞选岗位');
        $form->textarea('desc2', '服务队');
        $form->image('cover', '照片')
            ->uniqueName();

        return $form;
    }

    function store(Vote $vote)
    {
        return $this->form($vote)->store();
    }

    function edit(Content $content, Vote $vote, $id)
    {
        return $content
            ->header($vote->title)
            ->description('新增条目')
            ->body($this->form($vote)->edit($id));
    }

    function update(Vote $vote, $id)
    {
        return $this->form($vote)->update($id);
    }

}
