<?php

namespace Encore\Admin\Controllers;

use App\Models\Admin\AdminPermission;
use App\Models\Admin\AdminRole;
use App\Models\Subsite;
use Encore\Admin\Auth\Database\Administrator;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Routing\Controller;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use App\Validators\Rules\PasswordRule;

class UserController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header(trans('admin.administrator'))
            ->description(trans('admin.list'))
            ->body($this->grid()->render());
    }

    /**
     * Show interface.
     *
     * @param mixed   $id
     * @param Content $content
     *
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header(trans('admin.administrator'))
            ->description(trans('admin.detail'))
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param $id
     *
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header(trans('admin.administrator'))
            ->description(trans('admin.edit'))
            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header(trans('admin.administrator'))
            ->description(trans('admin.create'))
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $userModel = config('admin.database.users_model');

        $grid = new Grid(new $userModel());

        // 添加默认查询条件
        $grid->model()->when(get_subsite_id() > 0, function ($query) {
            $query->where('subsite_id', get_subsite_id());
        });

        if (Admin::user()->isAdministrator()) {
            $grid->disableCreateButton(false);
        }
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            if (Admin::user()->isAdministrator()) {
                $actions->disableDelete(false);
                $actions->disableEdit(false);
            }
        });

        $grid->tools(function (Grid\Tools $tools) {
            $tools->batch(function (Grid\Tools\BatchActions $batch) {
                if (Admin::user()->isAdministrator()) {
                    $batch->disableDelete(false);
                }
            });
        });

        $grid->id('ID')->sortable();
        $grid->username(trans('admin.username'))->width(250);
        $grid->name(trans('admin.name'))->width(250);

        if (get_subsite_open()) {
            $subsites = Subsite::pluck('sitename', 'id')->toArray();
            $subsites=[0 => '总站'] + $subsites;
            $grid->subsite_id("所属分站")->display(function ($subsite_id) use ($subsites) {
                if (isset($subsites[$subsite_id])) {
                    return $subsites[$subsite_id];
                }
                return "";
            })->label('primary');
        }

        $grid->roles(trans('admin.roles'))->display(function ($roles) {
            $str = collect($roles)->take(5)->map(function ($role) {
                return "<div style='margin-bottom: 5px;'><span class='label label-success'>{$role['name']}</span></div>";
            })->implode("");
            if (count($roles) > 5) {
                $str = $str . "<div style='margin-bottom: 5px;'><span class='label label-success'>...</span></div>";
            }
            return $str;
        });

        if (get_subsite_open()) {
            $subsite_array = Subsite::pluck('sitename', 'id')->toArray();
            $subsite_array=[0 => '总站'] + $subsite_array;
            $grid->subsites("分站权限")->display(function ($subsites) use ($subsite_array) {
                $str = collect($subsites)->take(5)->map(function ($subsite) use ($subsite_array) {
                    if (!isset($subsite_array[$subsite['subsite_id']])) {
                        return "";
                    }
                    return "<span style='margin-left: 5px' class='label label-success'>{$subsite_array[$subsite['subsite_id']]}</span>";
                })->implode("");

                return $str;
            });
        }

        $grid->created_at(trans('admin.created_at'));

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            if ($actions->getKey() == 1) {
                $actions->disableDelete();
            }
            $actions->disableView();
        });
        $grid->disableFilter();
        $grid->tools(function (Grid\Tools $tools) {
            $tools->batch(function (Grid\Tools\BatchActions $actions) {
                //$actions->disableDelete();
            });
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        $userModel = config('admin.database.users_model');

        $show = new Show($userModel::findOrFail($id));

        $show->id('ID');
        $show->username(trans('admin.username'));
        $show->name(trans('admin.name'));

        $show->roles(trans('admin.roles'))->as(function ($roles) {
            return $roles->pluck('name');
        })->label();
        $show->permissions("单独权限")->as(function ($permission) {
            return $permission->pluck('name');
        })->label();

        if (get_subsite_open()) {
            $subsite_array = Subsite::pluck('sitename', 'id')->toArray();
            $subsite_array=[0 => '总站'] + $subsite_array;
            $show->subsite_id("所属分站")->as(function ($subsite_id) use ($subsite_array) {
                if (!isset($subsite_array[$subsite_id])) {
                    return "";
                }
                return $subsite_array[$subsite_id];
            })->label('primary');


            $show->subsites("分站权限")->as(function ($subsites) use ($subsite_array) {
                return collect($subsites)->map(function ($subsite) use ($subsite_array) {
                    if (!isset($subsite_array[$subsite['subsite_id']])) {
                        return "";
                    }
                    return $subsite_array[$subsite['subsite_id']];
                });
            })->label();
        }
        $show->created_at(trans('admin.created_at'));
        $show->updated_at(trans('admin.updated_at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form($id = 0)
    {
        $userModel = config('admin.database.users_model');

        $form = new Form(new $userModel());

        $form->display('id', 'ID');

        if (request()->isMethod('POST')) {
            $userTable = config('admin.database.users_table');
            $userNameRules = "required|min:3|max:16|unique:{$userTable}";
        } elseif (request()->isMethod('PUT')) {
            $userTable = config('admin.database.users_table');
            $userNameRules = ["required", 'min:3','max:16',Rule::unique($userTable)->ignore($id)];
        } else {
            $userNameRules = 'required|min:3|max:16';
        }

        $form->text('username', trans('admin.username'))->rules($userNameRules);

        $form->text('name', trans('admin.name'))->rules('required|min:2|max:16');
        $form->image('avatar', trans('admin.avatar'))->options(['layoutTemplates' => ['actionDelete'    => '']]);
        $form->password('password', trans('admin.password'))->rules(
            ['required', 'confirmed',new PasswordRule(request()->username, $id)],
            ['confirmed'=>'两次输入的密码不一致']
        )->help('(密码规则：8~16位，包含数字、大小写字母及特殊字符至少各一个，禁止包含账号)');
        $form->password('password_confirmation', trans('admin.password_confirmation'))->rules('required')
            ->default(function ($form) {
                return $form->model()->password;
            });

        $form->ignore(['password_confirmation']);

        $form->multipleSelect('roles', trans('admin.roles'))->options(AdminRole::roleArr());
        $form->multipleSelect('permissions', "单独权限")->options(AdminPermission::permissionArr());
        if (get_subsite_open()) {
            $subsite_array=array_column(get_all_subsite(), 'sitename', 'id');
            if (get_subsite_id() > 0) {
                $subsite_array = [get_subsite_id() => $subsite_array[get_subsite_id()]];
            }
            $column=$form->multipleSelect('relate_subsites', "分站权限")->options($subsite_array);
            if (Str::contains(request()->getPathInfo(), 'create')) {
                $column->default(get_subsite_id());
            }
            if (Str::contains(request()->getPathInfo(), 'edit')) {
                $id=request()->route()->parameter('user');
                $column->value(Administrator::find($id)->subsites()->pluck('subsite_id')->toArray());
            }
            $form->ignore(['relate_subsites']);

            if (get_subsite_id() == 0) {
                //添加所属分站
                $form->radio('subsite_id', '所属分站')->options(array_column(get_all_subsite(), 'sitename', 'id'))->default(0);
            }
        }

        $form->display('created_at', trans('admin.created_at'));
        $form->display('updated_at', trans('admin.updated_at'));

        $form->saving(function (Form $form) {
            if ($form->password && $form->model()->password != $form->password) {
                $form->password = bcrypt($form->password);
            }
        });
        $form->saved(function (Form $form) {
            if (request()->has('relate_subsites')) {
                $subsites=request()->get('relate_subsites', []);

                $set_data = array();
                foreach ($subsites as $k => $v) {
                    if ($v !== null) {
                        $set_data[] = array(
                            'subsite_id'=> $v
                        );
                    }
                }
                $form->model()->subsites()->delete();
                $form->model()->subsites()->createMany($set_data);
            }

            if (!get_subsite_open()) {
                $form->model()->subsites()->delete();
                $form->model()->subsites()->create(['subsite_id'=> 0]);
            }

            if (get_subsite_id() > 0 && request()->isMethod('POST')) {
                $form->model()->subsite_id = get_subsite_id();
                $form->model()->save();
            }
        });
        return $form;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update($id)
    {
        return $this->form($id)->update($id);
    }

    /**
     * Destroy data entity and remove files.
     *
     * @param $id
     *
     * @return mixed
     */
    public function destroy($id)
    {
        //id=1的管理员不能删除
        $id_arr =  explode(',', $id);
        foreach ($id_arr as $k => $v) {
            if (in_array($v, [1])) {
                unset($id_arr[$k]);
            }
        }
        $filter_id = implode(',', $id_arr);

        if ($this->form()->destroy($filter_id)) {
            $data = [
                'status'  => true,
                'message' => trans('admin.delete_succeeded'),
            ];
        } else {
            $data = [
                'status'  => false,
                'message' => trans('admin.delete_failed'),
            ];
        }
        return response()->json($data);
    }
}
