<?php

namespace Modules\Project\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Encore\Admin\Form\Field\Embeds;
use Modules\Project\Entities\Coupon;
use Modules\Project\Services\CouponService;
use SMG\Admin\Controllers\ModelForm;
use SMG\Admin\Facades\Admin;
use SMG\Admin\Form;
use SMG\Admin\Grid;
use SMG\Admin\Layout\Content;

class CouponController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return mixed
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('优惠券');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     *
     * @return Content|\Encore\Admin\Layout\Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('优惠券');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return mixed
     */
    public function create()
    {
        if (($type = request('coupon_type')) && request()->method() == 'GET') {
            $embeds = new Embeds('config', ['配置', $this->getTypeConfig($type)]);
            $embeds->setForm($this->form());
            $content = $embeds->render()->render();
            $content .= Admin::script();

            return $content;
        }

        return Admin::content(function (Content $content) {
            Admin::addJs('/js/admin/coupon.js');

            $content->header('优惠券');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Coupon::class, function (Grid $grid) {
            $grid->model()->withCount('users');

            $grid->id('ID')->sortable();
            $grid->column('name', '名称');
            $grid->column('users_count', '领取数量');
            $grid->column('disabled', '启用状态')->display(function ($val) {
                return $val == 1 ? '<code color="red">否</code>' : '<code>是</code>';
            });

            $grid->created_at();
            $grid->updated_at();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Coupon::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->text('name', '名称')->rules('required');

            if ($id = request()->route('coupon')) {
                $type = $form->model()->findOrFail($id)->type;
                $form->html(CouponService::getTypeOptions()[$type], '优惠券类型');
            } else {
                $form->select('type', '优惠券类型')->options(CouponService::getTypeOptions())->attribute('id', 'coupon_type');
                $type = request('type', old('type'));
            }
            if ($type) {
                $form->embeds('config', '配置', $this->getTypeConfig($type));
            }

            $form->number('limit', '每人获取数量')->default('1')->rules('required|min:1');
            $form->datetime('start', '开始使用时间');
            $form->datetime('end', '过期时间');
            $form->number('expire_after_days', '领取后多少天内有效')->default('0')->help('如果此值大于0则覆盖上面的过期时间');
            $form->switch('disabled', '禁用？');
        });
    }

    /**
     * 获取类型配置
     *
     * @param $type
     *
     * @return \Closure
     */
    protected function getTypeConfig($type)
    {
        $config = CouponService::getConfig($type);

        return function ($form) use ($config) {
            if (!is_array($config)) {
                return;
            }
            foreach ($config as $key => $one) {
                $elemnt = null;
                foreach ($one as $method => $args) {
                    if (!$elemnt) {
                        $elemnt = $form->$method(...$args);
                    } else {
                        $elemnt->$method(...$args);
                    }
                }
            }
        };
    }

    /**
     * 删除
     *
     * @param $id
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $coupon = Coupon::findOrFail($id);
        if ($coupon->users()->count() > 0) {
            return response()->json([
                'status' => false,
                'message' => '被领用过的优惠券不能删除',
            ]);
        }

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