<?php

namespace Modules\Mall\Http\Controllers\Admin;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Routing\Controller;
use Modules\Mall\Models\Job;
use Modules\Mall\Models\Shop;
use Modules\Mall\Models\ShopStaffer;
use Modules\User\Models\User;

class StafferController extends Controller
{

    public function index(Content $content, Shop $shop): Content
    {
        return $content
            ->header($shop->name)
            ->description('员工管理')
            ->body($this->grid($shop));
    }

    public function grid($shop): Grid
    {
        $grid = new Grid(new ShopStaffer());

        $grid->model()->byShop($shop);

        $grid->filter(function (Grid\Filter $filter) {
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('user.username', '用户名');
            });
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('user.info.nickname', '用户昵称');
            });
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->equal('job.name', '职位名称');
            });
        });

        $grid->column('所属用户')->display(fn() => $this->user->username . '[' . $this->user->info->nickname . ']');
        $grid->column('job.name', '职位名称');
        $grid->column('created_at', '创建时间');

        return $grid;
    }

    public function create(Content $content, Shop $shop): Content
    {
        return $content
            ->header($shop->name)
            ->description('新增员工')
            ->body($this->form($shop));
    }

    public function store(Shop $shop)
    {
        return $this->form($shop)->store();
    }

    public function form(Shop $shop): Form
    {
        $form = new Form(new ShopStaffer());

        $form->hidden('shop_id')->value($shop->getKey());

        $form->select('user_id', '所属用户')
             ->options(function ($userId) {
                 $user = User::find($userId);

                 if ($user) {
                     return [$user->id => $user->username . ' [' . $user->info->nickname . ']'];
                 }
             })
             ->ajax(route('admin.user.users.ajax'))
             ->required();

        $form->select('job_id', '职位')->options(fn() => Job::byShop($shop)->pluck('name', 'id'));

        return $form;
    }

    public function edit(Content $content, Shop $shop, ShopStaffer $staffer): Content
    {
        return $content
            ->header($shop->name)
            ->description('编辑员工')
            ->body($this->form($shop)->edit($staffer->getKey()));
    }

    public function update(Shop $shop, ShopStaffer $staffer)
    {
        return $this->form($shop)->update($staffer->getKey());
    }

}