<?php

namespace addons\webman\controller;

use addons\webman\Admin;
use addons\webman\model\Channel;
use addons\webman\model\Game;
use addons\webman\model\GamePlatform;
use addons\webman\model\Player;
use addons\webman\model\Prize;
use ExAdmin\ui\component\common\Button;
use ExAdmin\ui\component\common\Html;
use ExAdmin\ui\component\form\Form;
use ExAdmin\ui\component\grid\grid\Grid;
use ExAdmin\ui\component\grid\image\Image;
use ExAdmin\ui\response\Msg;
use ExAdmin\ui\response\Notification;
use ExAdmin\ui\response\Response;
use ExAdmin\ui\support\Request;
use support\Db;
use ExAdmin\ui\component\grid\grid\Editable;
use ExAdmin\ui\component\grid\grid\Actions;
use addons\webman\model\GameType;
use Tinywan\Jwt\JwtToken;

/**
 * 游戏平台
 * @group channel
 */
class GameController
{
    protected $model;
    protected $game;

    public function __construct()
    {
        $this->game = plugin()->webman->config('database.game_model');
        $this->prize = plugin()->webman->config('database.prize_model');
    }

    /**
     * 游戏列表
     * @auth true
     * @return Grid
     */
    public function index(): Grid
    {
        return Grid::create(new $this->game(), function (Grid $grid) {
            $grid->title(admin_trans('game.title'));
            if (plugin()->webman->config('admin_auth_id') != Admin::id()){
                $grid->model()->where('status', 1);
            }
            $grid->model()->orderBy('status', 'desc')->orderBy('id', 'asc');
            $grid->bordered(true);
            $grid->autoHeight();
            $grid->column('id', admin_trans('game.fields.id'))->align('center');
            $grid->column('logo', 'LOGO')->display(function ($val, $data) {
                $image = Image::create()
                    ->width(50)
                    ->height(50)
                    ->style(['border-radius' => '50%', 'objectFit' => 'cover'])
                    ->src($data['logo']);
                return Html::create()->content([
                    $image,
                ]);
            })->align('center');
            $grid->column('name', admin_trans('game.fields.name'))->align('center');
            $grid->column('game_image', admin_trans('game.fields.game_image'))->display(function ($val, $data) {
                $image = Image::create()
                    ->width(50)
                    ->height(50)
                    ->style(['border-radius' => '50%', 'objectFit' => 'cover'])
                    ->src($data['game_image']);
                return Html::create()->content([
                    $image,
                ]);
            })->align('center');
            $grid->column('consume', admin_trans('game.fields.consume'))->align('center');
            $grid->column('prize_num', admin_trans('game.fields.prize_num'))->align('center');
            $grid->column('description', admin_trans('game.fields.description'))->align('center');
            $grid->column('game_url', admin_trans('game.fields.game_url'))->align('center');
            if (plugin()->webman->config('admin_auth_id') != Admin::id()){
                $grid->column('status', admin_trans('game_platform.fields.status'))->switch()->align('center');
            }
            $grid->column('updated_at', admin_trans('game.fields.updated_at'))->align('center');
            $grid->expandFilter();
            $grid->setForm()->drawer($this->form());
            $grid->actions(function (Actions $actions, $data) {
                $actions->hideDel();
                $actions->prepend(
                    Button::create(admin_trans('game.enter_game'))->ajax([$this, 'enterGame'],
                        ['id' => $data['id']])
                );
                $actions->prepend(
                    Button::create(admin_trans('game.view_prize'))->modal([$this, 'getPrizeList'],
                        ['id' => $data['id']])->width('100%')
                );
            })->align('center');
            $grid->hideDelete();
            $grid->hideSelection();
            $grid->hideAdd();
            $grid->hideTrashed();
        });
    }

    /**
     * 进入游戏
     * @param $id
     * @auth true
     * @return Notification
     */
    public function enterGame($id): Notification
    {
        $game = Game::query()->where('id', $id)->first();
        $url = $game->test_url;
        return notification_success(admin_trans('admin.success'),
            admin_trans('game_platform.action_success'))->redirect($url);
    }

    /**
     * 游戏详情
     * @auth true
     * @return Form
     */
    public function form(): Form
    {
        return Form::create(new $this->game(), function (Form $form) {
            $form->title(admin_trans('prize.title'));
            $form->text('name', admin_trans('game.fields.name'))->required()->maxlength(50);
            $form->image('logo', admin_trans('game.fields.logo'))->required();
            $form->image('game_image', admin_trans('game.fields.game_image'))->required();
            $form->number('consume', admin_trans('game.fields.consume'))->required();
            $form->number('prize_num', admin_trans('game.fields.prize_num'))->required();
            $form->textarea('description', admin_trans('game.fields.description'))->maxlength(500)->bindAttr('rows', 10);
            $form->text('game_url', admin_trans('game.fields.game_url'))->required()->maxlength(500);
            $form->switch('status', admin_trans('game_platform.fields.status'))->required()->span(11);
            $form->layout('vertical');
        });
    }

    /**
     * 查看奖品
     * @param $id
     * @return Grid
     * @auth true
     */
    public function getPrizeList($id): Grid
    {
        return Grid::create(new $this->prize(), function (Grid $grid) use($id) {
            $grid->title(admin_trans('prize.title'));
            $grid->model()->where('game_id', $id)->orderBy('probability');
            $grid->bordered(true);
            $grid->autoHeight();
            $grid->column('id', admin_trans('prize.fields.id'))->align('center')->width('5%');
            $grid->column('name', admin_trans('prize.fields.name'))->align('center')->width('10%');
            $grid->column('pic', admin_trans('prize.fields.pic'))->display(function ($val, $data) {
                $image = Image::create()
                    ->width(50)
                    ->height(50)
                    ->src($data['pic']);
                return Html::create()->content([
                    $image,
                ]);
            })->align('center');
            $grid->column('probability', admin_trans('prize.fields.probability'))->align('center')->width('10%');
            $grid->column('total_stock', admin_trans('prize.fields.total_stock'))->align('center')->width('8%');
            $grid->column('daily_stock', admin_trans('prize.fields.daily_stock'))->align('center')->width('8%');
            $grid->column('total_remaining', admin_trans('prize.fields.total_remaining'))->align('center')->width('8%');
            $grid->column('daily_remaining', admin_trans('prize.fields.daily_remaining'))->align('center')->width('8%');
            $grid->column('description', admin_trans('prize.fields.description'))->align('center')->width('20%');
            if (plugin()->webman->config('admin_auth_id') != Admin::id()) {
                $grid->column('status', admin_trans('prize.fields.status'))->switch()->align('center')->width('8%');
            }
            $grid->column('admin_name', admin_trans('prize.fields.admin_name'))->align('center')->width('8%');
            $grid->column('updated_at', admin_trans('prize.fields.updated_at'))->align('center')->width('8%');
            $grid->expandFilter();
            $grid->setForm()->drawer($this->editPrize($id));
            $grid->actions(function (Actions $actions, $data) {
                $actions->hideDel();
                $actions->hideEdit();
                $actions->prepend(
                    Button::create(admin_trans('prize.replenish_daily_stock'))->ajax([$this, 'replenishDailyStock'],
                        ['id' => $data['id']])
                );
            })->align('center');
            $grid->hideDelete();
            $grid->hideAdd();
            $grid->hideSelection();
            $grid->hideTrashed();
        });
    }

    /**
     * 补充每日库存
     * @param $id
     * @auth true
     * @return Msg
     */
    public function replenishDailyStock($id): Msg
    {
        /** @var Prize $prize */
        $prize = Prize::query()->where('id', $id)->first();

        if ($prize->daily_remaining < $prize->daily_stock) {
            $diff = $prize->daily_stock - $prize->daily_remaining;
            $prize->daily_remaining = $prize->daily_stock;
            $prize->total_remaining = $prize->total_remaining + $diff;
            $prize->total_stock = $prize->total_stock + $diff;
        }
        $prize->save();
        return message_success(admin_trans('prize.action_success'));
    }

    /**
     * 奖品详情
     * @auth true
     * @param $gameId
     * @return Form
     */
    public function editPrize($gameId): Form
    {
        return Form::create(new $this->prize(), function (Form $form) use ($gameId) {
            $form->title(admin_trans('prize.title'));
            $form->text('name', admin_trans('prize.fields.name'))->required()->maxlength(50);
            $form->image('pic', admin_trans('prize.fields.pic'));
            $form->hidden('game_id')->default($gameId);
            $form->number('probability', admin_trans('prize.fields.probability'))->min(1)->max(999)->required();
            $form->number('total_stock', admin_trans('prize.fields.total_stock'))->min(1)->max(100000)->required();
            $form->number('daily_stock', admin_trans('prize.fields.daily_stock'))->min(1)->max(100000)
                ->help(admin_trans('prize.daily_stock_help'))->required();
            $form->textarea('description', admin_trans('prize.fields.description'))->maxlength(500)->bindAttr('rows', 10);
            $form->switch('status', admin_trans('prize.fields.status'))->default(true)->required()->span(11);
            $form->layout('vertical');
            $form->saving(function (Form $form) {
                try {
                    if (!$form->isEdit()) {
                        $prize = new Prize();
                        $prize->game_id = $form->input('game_id');
                        $prize->total_remaining = $form->input('total_stock');
                        $prize->daily_remaining = $form->input('daily_stock');
                    } else {
                        $prizeId = $form->driver()->get('id');
                        $prize = Prize::query()->find($prizeId);
                    }
                    $prize->name = $form->input('name');
                    $prize->pic = $form->input('pic');
                    $prize->probability = $form->input('probability');
                    $prize->total_stock = $form->input('total_stock');
                    $prize->daily_stock = $form->input('daily_stock');
                    if ($prize->daily_stock > $prize->total_stock) {
                        return message_error(admin_trans('prize.daily_stock_help'));
                    }
                    $prize->description = $form->input('description');
                    $prize->status = $form->input('status');
                    $prize->admin_id = Admin::id();
                    $prize->admin_name = !empty(Admin::user()) ? Admin::user()->toArray()['username'] : trans('system_automatic', [], 'message');
                    $prize->save();
                } catch (\Exception $e) {
                    return message_error(admin_trans('form.save_fail'));
                }
                return message_success(admin_trans('form.save_success'));
            });
        });
    }

    /**
     * 筛选游戏平台
     * @return mixed
     */
    public function getGamePlatformOptions()
    {
        $request = Request::input();
        $gamePlatform = GamePlatform::query()->orderBy('created_at', 'desc');
        if (!empty($request['search'])) {
            $gamePlatform->where('name', 'like', '%' . $request['search'] . '%');
        }
        $channelList = $gamePlatform->get();
        $data = [];
        /** @var GamePlatform $gamePlatform */
        foreach ($channelList as $gamePlatform) {
            $data[] = [
                'value' => $gamePlatform->id,
                'label' => $gamePlatform->name,
            ];
        }
        return Response::success($data);
    }

    /**
     * 游戏类型列表
     * @auth true
     */
    public function serviceList(): Grid
    {
        return Grid::create(new GameType(), function (Grid $grid) {
            $grid->title(admin_trans('game_type.title'));
            $grid->autoHeight();
            $grid->bordered(true);
            $grid->column('game_type', admin_trans('game_type.fields.game_type'))->display(function ($val) {
                return $val ? admin_trans('game_type.game_type.' . $val) : admin_trans('game_type.nu_set');
            })->align('center');

            $grid->column('ratio', admin_trans('game_type.fields.ratio'))->display(function ($value) {
                return $value . '%';
            })->editable(
                (new Editable)->number('ratio')
                    ->min(1)
                    ->max(100)
                    ->addonAfter('%')
            )->align('center')->ellipsis(true);

            $grid->column('updated_at', admin_trans('game_type.fields.updated_at'))->align('center')->display(function ($val) {
                return $val ? date('Y-m-d H:i:s', strtotime($val)) : '';
            })->ellipsis(true);
            $grid->actions(function (Action $actions) {
                $actions->hideDel();
                $actions->hideEdit();
            });
            $grid->hideDelete();
            $grid->hideSelection();
            $grid->hideAdd();
        });
    }

    /**
     * 游戏类型
     * @auth true
     */
    public function serviceForm(): Form
    {
        return Form::create(new GamePlatform, function (Form $form) {
            $form->title(admin_trans('game_platform.game_platform'));
            $form->text('name', admin_trans('game_platform.fields.name'));
            $form->text('title', admin_trans('game_platform.fields.title'));
            $form->number('service_ratio', admin_trans('game_platform.fields.service_ratio'))->addonAfter('%');
            
            $form->layout('vertical');
            $form->saving(function (Form $form) {
                if (!$form->isEdit()) {
                    return message_error(admin_trans('game_platform.save_error'));
                    DB::beginTransaction();
                    try {
                        $gamePlatform = new GamePlatform();
                        $gamePlatform->name = $form->input('name');
                        $gamePlatform->title = $form->input('title');
                        $gamePlatform->service_ratio = $form->input('service_ratio');
                        $gamePlatform->status = 1;
                        $gamePlatform->save();
                        DB::commit();
                    } catch (\Exception $e) {
                        DB::rollBack();
                        return message_error($e->getMessage());
                    }
                    return message_success(admin_trans('game_platform.save_success'));
                } else {
                    $gamePlatform = GamePlatform::find($form->input('id'));
                    if (empty($gamePlatform)) {
                        return message_error(admin_trans('game_platform.not_fount'));
                    }
                    DB::beginTransaction();
                    try {
                        $gamePlatform->name = $form->input('name');
                        $gamePlatform->title = $form->input('title');
                        $gamePlatform->service_ratio = $form->input('service_ratio');
                        $gamePlatform->save();
                        DB::commit();
                    } catch (\Exception $e) {
                        DB::rollBack();
                        return message_error($e->getMessage());
                    }
                    return message_success(admin_trans('game_platform.save_success'));
                }
            });
        });
    }
}
