<?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 Modules\Mall\Http\Controllers\Admin\Action\Shop\Close;
use Modules\Mall\Http\Controllers\Admin\Action\Shop\Open;
use Modules\Mall\Http\Controllers\Admin\Action\Shop\Pass;
use Modules\Mall\Http\Controllers\Admin\Action\Shop\Reject;
use Modules\Mall\Http\Controllers\Admin\Selectable\Expresses;
use Modules\Mall\Http\Controllers\Admin\Selectable\Reasons;
use Modules\Mall\Models\Region;
use Modules\Mall\Models\Shop;
use Modules\User\Models\User;

class ShopController extends AdminController
{

    use WithUploads;

    protected $title = '店铺管理';

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

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
            // $actions->disableEdit();
            $actions->disableDelete();
            if ($actions->row->status == Shop::STATUS_APPLYING) {
                $actions->add(new Pass);
                $actions->add(new Reject);
            }
            if ($actions->row->status == Shop::STATUS_NORMAL) {
                $actions->add(new Close);
            }

            if ($actions->row->status == Shop::STATUS_CLOSE) {
                $actions->add(new Open);
            }
        });

        $grid->filter(function (Grid\Filter $filter) {
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('name', '店铺名称');
            });
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('user.info.nickname', '用户昵称');
            });
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->equal('mobile', '联系电话');
            });
        });

        $grid->model()->withCount(['versions', 'staffers'])->with(['user.info']);

        $grid->column('name', '店铺名称');
        $grid->column('所属用户')->display(fn() => $this->user->username . '[' . $this->user->info->nickname . ']');
        $grid->column('is_self', '类型')
             ->using([
                 0 => '合作',
                 1 => '自营',
             ])->label([
                0 => 'info',
                1 => 'danger',
            ]);
        $grid->column('mobile', '联系电话');
        $grid->column('address', '地址')->display(fn() => $this->getFullAddress());
        $grid->column('status', '状态')
             ->using(Shop::STATUS_MAP)
             ->label(Shop::LABEL_MAP);
        $grid->column('order', '排序')->sortable()->editable();
        $grid->column('versions_count', '操作记录')->link(fn() => route('admin.mall.versions', [
            'model' => get_class($this),
            'key'   => $this->id,
        ]), '_self');
        $grid->column('staffers_count', '员工数量')->link(fn() => route('admin.mall.shops.staffers.index', $this), '_self');
        $grid->column('created_at', '创建时间');

        return $grid;
    }

    public function form(): Form
    {
        $form = new Form(new Shop());
        $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'))
             ->creationRules([
                 'required',
                 "unique:mall_shops",
             ], [
                 'unique' => '用户已存在店铺',
             ])
             ->updateRules([
                 'required',
                 "unique:mall_shops,user_id,{{id}}",
             ], [
                 'unique' => '用户已存在店铺',
             ])
             ->required();
        $form->text('name', '店铺名称')
             ->creationRules(['required', "unique:mall_shops"], ['unique' => '店铺名称已存在'])
             ->updateRules(['required', "unique:mall_shops,name,{{id}}"], ['unique' => '店铺名称已存在'])
             ->required();
        $form->switch('is_self', '自营店铺');
        $form->textarea('description', '店铺简介')
             ->required();
        $form->text('mobile', '联系电话')
             ->rules([
                 'size:11',
                 'phone:CN',
             ], [
                 'size'  => '手机号格式不正确',
                 'phone' => '手机号格式不正确',
             ])
             ->creationRules(['required', "unique:mall_shops"], ['unique' => '店铺联系电话已存在'])
             ->updateRules(['required', "unique:mall_shops,name,{{id}}"], ['unique' => '店铺联系电话已存在'])
             ->required();
        $form->divider('地址信息');
        $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->divider('其他信息');
        $this->cover($form, 'cover', '店铺LOGO');
        $form->radio('status', '店铺状态')
             ->options(Shop::STATUS_MAP);
        $form->number('order', '排序')
             ->default('9999')
             ->help('仅后台可见，用于店铺推荐序列');
        $form->belongsToMany('expresses', Expresses::class, '发货物流');
        $form->belongsToMany('reasons', Reasons::class, '退款原因');

        return $form;
    }

    /**
     * Notes   : 获取店铺AJAX
     * @Date   : 2021/5/7 4:39 下午
     * @Author : < Jason.C >
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function ajax(Request $request)
    {
        $key = $request->get('q');

        return Shop::where('name', 'like', "%$key%")->paginate(null, ['id', 'name as text']);
    }

}
