<?php

namespace App\Admin\Controllers\Activity;

use App\Admin\Renderable\Activity\Grants;
use App\Admin\Renderable\Activity\Verifications;
use App\Models\Activity;
use App\Models\ActivityRule;
use App\Models\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Support\MessageBag;

class IndexController extends AdminController
{

    protected $title = '活动管理';

    protected function grid(): Grid
    {
        $grid = new Grid(new Activity);
        $grid->model()->with(['rule', 'grants', 'verifications'])->withCount('coupons');

        $grid->actions(function ($actions) {
            $actions->disableView();
        });

        $grid->filter(function ($filter) {
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('status', '状态')->select(Activity::STATUS);
                $filter->equal('type', '类型')->select(Activity::TYPES);
                $filter->equal('code', '活动编号');
            });

            $filter->column(1 / 2, function ($filter) {
                $filter->between('start_at', '开始时间')->datetime();
                $filter->between('end_at', '结束时间')->datetime();
                $filter->equal('channel', '核销途径')->select(Activity::CHANNELS);
            });
        });

        $grid->column('id', '#ID#');
        $grid->column('title', '活动名称');
        $grid->column('code', '活动编号');
        $grid->column('total', '可发券总数');
        $grid->column('coupons_count', '已发券总数');
        $grid->column('rule.code', '卡券规则');
        $grid->column('类型')->display(function () {
            return $this->type_text;
        });
        $grid->column('channel', '核销途径')
            ->using(Activity::CHANNELS)
            ->label([
                Activity::CHANNEL_YSD   => 'info',
                Activity::CHANNEL_UNION => 'success',
            ]);
        $grid->column('days', '延期(天)');
        $grid->column('rule.full', '满足金额');
        $grid->column('rule.take', '扣除金额');
        $grid->column('发券渠道')->display(function ($title, $column) {
            return '查看';
        })->modal(Grants::class);
        $grid->column('核券渠道')->display(function ($title, $column) {
            return '查看';
        })->modal(Verifications::class);

        $grid->column('开始时间')->display(function () {
            return $this->type == Activity::TYPE_SCOPE ? $this->start_at->format('Y-m-d') : '---';
        });
        $grid->column('结束时间')->display(function () {
            return $this->type == Activity::TYPE_SCOPE ? $this->end_at->format('Y-m-d') : '---';
        });

        $grid->status('状态')->switch([
            'on'  => ['value' => 1, 'text' => '正常', 'color' => 'primary'],
            'off' => ['value' => 0, 'text' => '关闭', 'color' => 'danger'],
        ]);

        $grid->column('created_at', '创建时间');

        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form(): Form
    {
        $form = new Form(new Activity);

        $form->text('title', '活动名称')->required();
        $form->textarea('description', '活动说明')->required();

        $form->select('activity_rule_id', '所属规则')
            ->options(function ($option, $info) {
                return ActivityRule::where('status', 1)->pluck('title', 'id');
            })
            ->required();

        $form->number('total', '总数')
            ->help('可发券总数，0为不限制')
            ->default(10000)
            ->required();

        $form->radio('type', '类型')
            ->options(Activity::TYPES)
            ->when(Activity::TYPE_EXTEND, function (Form $form) {
                $form->number('days', '延期天数')->default(60)->help('到期日期=发券日期+延期天数');
            })
            ->when(Activity::TYPE_SCOPE, function (Form $form) {
                $form->dateRange('start_at', 'end_at', '有效时间');
            })
            ->help('当月券，领取的月底到期')
            ->required();

        $form->radio('channel', '核销途径')
            ->options(Activity::CHANNELS)
            ->default(Activity::CHANNEL_YSD)
            ->help('券码核销的途径：亿时代是自己核销，银联是银联pos核销')
            ->required();
        $form->number('day_times', '每天可用次数')->default(0)->help('每天可用次数，0未不限制');

        $form->switch('status', '状态')->default(1);
        $form->switch('need_check', '多次校验')
            ->default(1)
            ->help('同一订单，多次核销时校验，订单每满100元可核销一笔。');

        $users = User::query()
            ->with('info')
            ->whereHas('identity', function ($q) {
                $q->where('identity_id', 1);
            })
            ->orderBy('id', 'desc')
            ->get()
            ->pluck('nickname', 'id');

        $form->listbox('grants.user_id', '可发券渠道')
            ->options($users)
            ->default(function ($form) {
                if ($form->isEditing()) {
                    return $form->model()->grants()->pluck('user_id')->toArray();
                } else {
                    return [];
                }
            })
            ->required();

        $form->listbox('verifications.user_id', '可核券渠道')
            ->options($users)
            ->default(function ($form) {
                if ($form->isEditing()) {
                    return $form->model()->verifications()->pluck('user_id')->toArray();
                } else {
                    return [];
                }
            })
            ->required();

        $form->radio('verify_shop', '网点校验')
            ->options(Activity::VERIFY_SHOPS)
            ->default(Activity::VERIFY_SHOP_NO)
            ->when(Activity::VERIFY_SHOP_YES, function (Form $form) use ($users) {
                $form->listbox('shops.user_id', '可核券渠道')
                    ->options(function () {
                        return User::query()
                            ->with('info')
                            ->whereHas('identity', function ($q) {
                                $q->where('identity_id', 2);
                            })
                            ->where('status', 1)
                            ->orderBy('id', 'desc')
                            ->get()
                            ->pluck('nickname', 'id');
                    })
                    ->default(function ($form) {
                        if ($form->isEditing()) {
                            return $form->model()->shops()->pluck('user_id')->toArray();
                        } else {
                            return [];
                        }
                    });
            });

        $form->saving(function (Form $form) {
            $request = request();

            if ($request->total < 0) {
                $error = new MessageBag([
                    'title'   => '错误',
                    'message' => '可发券总数必须大于0',
                ]);

                return back()->withInput()->with(compact('error'));
            }

            if ($request->type == Activity::TYPE_EXTEND && empty($request->days)) {
                $error = new MessageBag([
                    'title'   => '错误',
                    'message' => '必须添加延期天数',
                ]);

                return back()->withInput()->with(compact('error'));
            }

            if ($request->type == Activity::TYPE_SCOPE && (empty($request->start_at) || empty($request->end_at))) {
                $error = new MessageBag([
                    'title'   => '错误',
                    'message' => '必须添加延期天数',
                ]);

                return back()->withInput()->with(compact('error'));
            }

            if (request()->start) {
                $form->start_at = $form->start_at.' 00:00:01';
            }

            if (request()->end_at) {
                $form->end_at = $form->end_at.' 23:59:59';
            }

            $shops = isset(request()->shops) ? array_filter(request()->shops['user_id']) : [];

            if (request()->verify_shop == Activity::VERIFY_SHOP_YES && empty($shops)) {
                $error = new MessageBag([
                    'title'   => '错误',
                    'message' => '必须设置可核销的网点',
                ]);

                return back()->withInput()->with(compact('error'));

            }

        });

        $form->saved(function (Form $form) {
            //设置发券渠道
            $users = [];
            foreach ($form->grants['user_id'] as $key => $user_id) {
                if ($user_id) {
                    $form->model()
                        ->grants()
                        ->updateOrCreate([
                            'user_id' => $user_id,
                        ]);
                    $users[] = $user_id;
                }
            }
            $form->model()->grants()->whereNotIn('user_id', $users)->delete();

            //设置核销渠道
            $users = [];
            foreach ($form->verifications['user_id'] as $key => $user_id) {
                if ($user_id) {
                    $form->model()
                        ->verifications()
                        ->updateOrCreate([
                            'user_id' => $user_id,
                        ]);
                    $users[] = $user_id;
                }
            }
            $form->model()->verifications()->whereNotIn('user_id', $users)->delete();

            $shops = isset(request()->shops) ? array_filter(request()->shops['user_id']) : [];

            if (! empty($shops)) {
                //设置核销网点
                $users = [];
                foreach ($form->shops['user_id'] as $key => $user_id) {
                    if ($user_id) {
                        $form->model()
                            ->shops()
                            ->updateOrCreate([
                                'user_id' => $user_id,
                            ]);
                        $users[] = $user_id;
                    }
                }
                $form->model()->shops()->whereNotIn('user_id', $users)->delete();
            }

        });

        return $form;
    }

}
