<?php

namespace Modules\User\Http\Controllers\Admin;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\User\Http\Controllers\Admin\Actions\JoinIdentity;
use Modules\User\Http\Controllers\Admin\Actions\RemoveIdentity;
use Modules\User\Http\Controllers\Admin\Actions\UpdateRelation;
use Modules\User\Models\Identity;
use Modules\User\Models\User;
use Vinkla\Hashids\Facades\Hashids;

class IndexController extends AdminController
{

    protected $title = '用户管理';

    /**
     * Notes   : 用户管理列表
     *
     * @Date   : 2021/3/11 1:59 下午
     * @Author : <Jason.C>
     * @return Grid
     */
    public function grid(): Grid
    {
        $grid = new Grid(new User());

        if (config('user.create_user_by_admin')) {
            $grid->quickCreate(function (Grid\Tools\QuickCreate $create) {
                $create->text('username', '用户名')->required();
                $create->password('password', '登录密码')->required();
                $create->text('info.nickname', '用户昵称')->required();
            });
        } else {
            $grid->disableCreateButton();
        }

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            ! config('user.create_user_by_admin') && $actions->disableEdit();
            $actions->disableDelete();
            $actions->disableView();
            $actions->add(new JoinIdentity());
            $actions->add(new RemoveIdentity());
            $actions->add(new UpdateRelation());
        });

        $grid->quickSearch('username')->placeholder('快速搜索用户名');

        $grid->filter(function (Grid\Filter $filter) {
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('username', '用户名');
            });

            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('info.nickname', '用户昵称');
                $filter->like('identityMiddle.serial', '会员编号（数字）');
            });
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->equal('identities.id', '身份')->select(Identity::pluck('name', 'id'));
                $filter->equal('parent.username', '推荐人');
            });
        });

        $grid->model()->withCount('addresses')->with(['info', 'parent', 'identities', 'addresses']);

        $grid->column('info.avatar', '头像')->image('', 32);
        $grid->column('id', '用户ID');
        $grid->column('username', '用户名');
        $grid->column('info.nickname', '用户昵称');
      
//        $grid->column('addresses_count', '收货地址')
//            ->link(function () {
//                return route('admin.mall.addresses.index', ['user_id' => $this->id]);
//            }, '_self');
        $grid->column('推荐人')->display(function () {
            return $this->parent->username ?? '无';
        });
        $grid->column('identities', '用户身份')
            ->display(function () {
                $data = [];
                foreach ($this->identities as $identity) {
                    $data[] = $identity->name.' : '.$identity->serial_prefix.$identity->getOriginal('pivot_serial');
                }

                return $data;
            })
            ->label();

     
        $grid->column('是否关注')
            ->display(function () {
                return $this->isOfficialSubscribe();
            })
            ->bool();
//        $grid->column('邀请码')
//            ->display(function () {
//                return Hashids::connection('code')->encode($this->id);
//            });
        $grid->column('created_at', '注册时间');

        return $grid;
    }

    /**
     * Notes   : 编辑表单
     *
     * @Date   : 2021/7/15 5:09 下午
     * @Author : <Jason.C>
     * @return Form
     * @throws Exception
     */
    public function form(): Form
    {
        $form = new Form(new User());

        if ($form->isCreating() && ! config('user.create_user_by_admin')) {
            throw new Exception('不运允许添加用户');
        }

        if ($form->isCreating() && ! config('user.edit_user_by_admin')) {
            throw new Exception('不运允许编辑用户');
        }

        $form->text('username', '用户名')
            ->required()
            ->rules('unique:users,username,{{id}}');
        $form->password('password', '登录密码')
            ->required()
            ->rules('min:6');
        $form->text('info.nickname', '用户昵称');

        return $form;
    }

    /**
     * Notes   : User 列表选择, 这里没有判断，用户是否已经有店铺了，如果判断的情况，可能导致当前用户 无法被选中
     *
     * @Date   : 2021/5/6 4:35 下午
     * @Author : <Jason.C>
     */
    public function ajax(Request $request)
    {
        $q = $request->get('q');

        return User::leftJoin('user_infos as info', 'users.id', '=', 'info.user_id')
            ->where('username', 'like', "%$q%")
            ->orWhere('info.nickname', 'like', "%$q%")
            ->select('id', DB::raw('CONCAT(username, " [", info.nickname, "]") as text'))
            ->paginate();
    }

}
