<?php

namespace App\Admin\Controllers;

use App\Admin\Renderable\DistDistributorTable;
use App\Admin\Repositories\DistAdminUser;
use App\Models\DistAdminDistributor;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;

class DistAdminUserController extends AdminController
{
    public function title()
    {
        return admin_trans( 'admin.distro_user');
    }
    /**
     * page index
     */
    public function index(Content $content)
    {
        return $content
            ->header($this->title())
            ->description('')
            ->breadcrumb(['text'=>'list','url'=>''])
            ->body($this->grid());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(DistAdminUser::with(['distributor']), function (Grid $grid) {
            //默认分页条数
            $grid->paginate(config('admin.per_page'));
            //指定表格视图，去掉右上角的操作按钮
            $grid->view('admin.grid.table');
            //设置列表
            $grid->column('id')->sortable();
            $grid->column('username');
            $grid->column('name');
            $grid->column('distributor.client_code',admin_trans_label('distributor_code'))->width('15%');
            //$grid->column('language')->using(config('dictionary.languages'));
            $grid->column('enabled')->switch();
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            //设置过滤器
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->equal('username')->width(2);
                $filter->equal('name',)->width(2);
                $filter->like('distributor.client_code', admin_trans_label('distributor_code'))->width(2);
                $filter->equal('enabled', )->select(admin_trans_array(config('dictionary.enabled')))->width(2);
            });
            //排序
            $grid->model()->orderBy("id",'desc');
            //按钮
            $grid->showQuickEditButton();
            $grid->enableDialogCreate();
            $grid->disableEditButton();
            $grid->disableDeleteButton();
            $grid->disableBatchDelete();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, DistAdminUser::with(['distributor']), function (Show $show) {
            $show->row(function ($show) {
                $show->width(6)->field('username');
                $show->width(6)->field('name');
                $show->width(6)->field('distributor.client_code', admin_trans_label('distributor_code'));
                $show->width(6)->field('enabled')->using(config('dictionary.enabled'));
                $show->width(6)->field('created_at');
                $show->width(6)->field('updated_at');
            });

            // 按钮
            $show->disableDeleteButton();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(DistAdminUser::with(['distributor']), function (Form $form) {
            //$form->display('id');
            $form->text('username')->help(admin_trans_label('username_tips'))->required();
            $form->password('password')->customFormat(function ($v) {
                return "";
            });
            $form->text('name',)->help(admin_trans_label('name_tips'))->required();
            //$form->select('language')->options(config('dictionary.languages'))->required();
            $form->selectTable('dist_id', admin_trans_label('distributor'))
                ->title('distId')
                ->from(DistDistributorTable::make())
                ->model(DistAdminDistributor::class, 'id', 'client_code')
                ->required();
            $form->switch('enabled')->default(1);
            //保存前回调
            $form->saving(function (Form $form) {
                //判断用户名是否重复
                $count = DistAdminUser::findCountByUsername($form->getKey(), $form->username);
                if ($count > 0) {
                    return $form->response()->error('Username already exists');
                }
                if($form->isCreating() && ($form->password === null || $form->password === '')) {
                    return $form->response()->error('Password cannot be empty');
                }
                //密码加密
                if ($form->password) {
                    $form->password = bcrypt($form->password);
                } else {
                    $form->deleteInput('password');
                }
            });
            //保存后回调
            $form->saved(function (Form $form, $result) {
                if ($form->isCreating()) {
                    //添加角色
                    $newId = $form->getKey();
                    if (! $newId) {
                        return $form->response()->error('Failed to save data');
                    }
                    DistAdminUser::addRoleUser($newId, config('dictionary.dist_role_id'));//分销商角色ID 2
                }
            });
        });
    }
}
