<?php

namespace Modules\Mall\Http\Controllers\Admin;

use App\Admin\Traits\WithUploads;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Linker\Traits\WithLinker;
use Modules\Mall\Models\Address;
use Modules\Mall\Models\Banner;
use Modules\Mall\Models\Region;
use Modules\User\Models\User;

class AddressController extends AdminController
{

    use WithUploads,
        WithLinker;

    public $title = "收货地址";

    protected function grid(): Grid
    {
        $grid = new Grid(new Address());

        $grid->filter(function (Grid\Filter $filter) {
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->equal('user_id', '所属用户')->select()->ajax(route('admin.user.users.ajax'));
            });
        });

        $grid->model()->with(['user']);

        $grid->column('id', '#ID#');
        $grid->column('user.username', '所属用户');
        $grid->column('name', '姓名');
        $grid->column('mobile', '手机号');
        $grid->column('province.name', '省');
        $grid->column('city.name', '市');
        $grid->column('district.name', '区');
        $grid->column('address', '详细地址');
        $grid->column('is_default', '默认？')->bool();
        $grid->column('created_at', '创建时间');

        return $grid;
    }

    protected function form(): Form
    {
        $form = new Form(new Address);

        $form->select('user_id', '所属用户')
            ->options(function ($userId) {
                $user = User::find($userId);
                if ($user) {
                    return [$user->id => $user->username.' ['.$user->info->nickname.']'];
                }
            })
            ->value(request()->user_id ?? '')
            ->ajax(route('admin.user.users.ajax'))
            ->required();
        $form->text('name', '姓名');
        $form->text('mobile', '手机号');
        $form->select('province_id', '省份')
            ->options(Region::where('parent_id', 1)->pluck('name', 'id'))
            ->load('city_id', route('admin.mall.regions.region'))
            ->required();
        $form->select('city_id', '城市')
            ->options(function ($option) {
                $parent = Region::where('id', $option)->value('parent_id');

                return Region::where(['parent_id' => $parent])->pluck('name', 'id');
            })
            ->load('district_id', route('admin.mall.regions.region'))
            ->required();
        $form->select('district_id', '区/县')
            ->options(function ($option) {
                $parent = Region::where('id', $option)->value('parent_id');

                return Region::where(['parent_id' => $parent])->pluck('name', 'id');
            })
            ->required();
        $form->text('address', '详细地址')
            ->required();

        $form->switch('is_default', '默认?')->default(1);

        return $form;
    }
}
