<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Games\GameLookers;
use App\Admin\Actions\Games\GameMembers;
use App\Admin\Actions\Games\GameScores;
use App\Admin\Actions\Teams\TeamFeeds;
use App\Admin\Actions\Teams\TeamPhotos;
use App\Models\ChatTeam;
use App\Models\Course;
use App\Models\Game;
use App\Models\GameType;
use App\Models\GameUser;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Show;
use Dcat\Admin\Widgets\Modal;
use App\Services\TencentImGroupService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GamesController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Game());
        $grid->model()->with(['game_types', 'creator_s:id,name,avatar', 'course:id,name'])->orderByDesc('id');

        $grid->column('id')->sortable();
        $grid->column('img')->image('', 50);
        $grid->column('name');
        $grid->column('creator')->display(function ($res) {
            if($this->creator_s){
                $str = "";
                $str .= "<div style='margin-right:10px;display: flex;align-items: center'>";
                $str .= '<img data-action="preview-img" src="' . $this->creator_s->avatar . '" style="max-height:50px;cursor:pointer;margin-right:5px;" class="img img-thumbnail">';
                $str .= '<div>';
                $str .= '<p style="margin-bottom: 2px">ID：' . $this->creator_s->id . '</p>';
                $str .= '<p>' . trans('user.fields.name') . '：' . $this->creator_s->name . '</p>';
                $str .= "</div>";
                $str .= "</div>";
                return $str;
            }
        });
        $grid->column('game_types.name', trans('games.fields.game_type_id'));
        $grid->column('scale');
        $grid->column('members')->display(function ($res) {
            $form = GameMembers::make()->payload(['id' => $this->id]);
            return Modal::make()
                ->lg()
                ->title(trans('games.fields.Players'))
                ->body($form)
                ->button('<i class="feather icon-align-right"></i> ' . $res);
        });
        $grid->column('course.name', trans('games.fields.course_id'));
        $grid->column('forbid_look')->switch();
        $grid->column('forbid_join')->switch();
        $grid->column('lookers');
        $grid->column('begin_time')->display(function ($res) {
            return date('m-d H:i', strtotime($res));
        });
        $grid->column('end_time')->display(function ($res) {
            if(!empty($res)){
                return date('m-d H:i', strtotime($res));
            }else{
                return '';
            }

        });
        $grid->column('created_at')->display(function ($res) {
            return date('Y-m-d H:i', strtotime($res));
        });
        $grid->filter(function (Grid\Filter $filter) {
            $filter->equal('id');
            $filter->like('name');
            $game_type = GameType::query()->get();
            $game_type_arr = array();
            foreach ($game_type as $v) {
                $game_type_arr[$v['id']] = $v['name'];
            }
            $filter->equal('game_type_id')->select($game_type_arr);
            $course = Course::query()->get();
            $course_arr = array();
            foreach ($course as $v) {
                $course_arr[$v['id']] = $v['name'];
            }
            $filter->equal('course_id')->select($course_arr);
        });

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->append(new GameScores('game'));
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Game(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('begin_time');
            $show->field('end_time');
            $show->field('scale');
            $show->field('game_type_id');
            $show->field('creator');
            $show->field('forbid_look');
            $show->field('forbid_join');
            $show->field('img')->image('', 200);
            $show->field('lookers');
            $show->field('members');
            $show->field('course_id');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Game(), function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->datetime('begin_time')->required();
            $form->number('scale')
                ->attribute('min', 2)
                ->attribute('max', 50)
                ->required();
            $game_types = GameType::query()->get()->toArray();
            $types = array();
            foreach ($game_types as $key => $val) {
                $types[$val['id']] = $val['name'] . '(' . $val['scale'] . ')';
            }
            $form->select('game_type_id')->options($types);

            $form->switch('forbid_look')->default(0);
            $form->switch('forbid_join')->default(0);
            $form->image('img')->saveFullUrl()->autoUpload();
            $form->number('lookers')
                ->attribute('min', 0);
            $form->number('members')
                ->attribute('min', 0)->default(10);
            $course = Course::query()->get();
            $course_arr = array();
            foreach ($course as $v) {
                $course_arr[$v['id']] = $v['name'];
            }
            $form->select('course_id')->options($course_arr)->required();

            if($form->isCreating()){
                $users = User::query()->where('status', 1)->get();
                $users_arr = array();
                foreach ($users as $v) {
                    $users_arr[$v['id']] = $v['name'];
                }
                $form->select('creator')->options($users_arr);

                $form->saved(function (Form $form) {
                    $gameId = $form->getKey();
                    $gameUser = new GameUser();
                    $gameUser->game_id = $gameId;
                    $gameUser->user_id = $form->creator;
                    $gameUser->level = 4;
                    $gameUser->type = 1;
                    $gameUser->status = 1;
                    $gameUser->save();

                    //创建群聊
                    $user = User::query()->where('id', $form->creator)->first();
                    $groupService = new TencentImGroupService();
                    $data = array();
                    $data['member_list'] [] = $user;
                    $data['Owner_Account'] = $user->tencent_im_user_id;
                    $data['group_name'] = $form->name;
                    $data['avatar'] = $form->img;
                    $groupResult = $groupService->createGroup($data);
                    Log::info($user);
                    Log::info($groupResult);
                    if ($groupResult['ActionStatus'] == 'OK' && $groupResult['ErrorCode'] == 0) {
                        DB::table('games')->where('id', $gameId)->update(['GroupId'=>$groupResult['GroupId']]);
                    }
                    $chatTeam = new ChatTeam();
                    $chatTeam->user_id = $user->id;
                    $chatTeam->Owner_Account = $user->tencent_im_user_id;
                    $chatTeam->group_name = $form->name;
                    $chatTeam->GroupId = $groupResult['GroupId'];
                    $chatTeam->FaceUrl = $form->img;
                    $chatTeam->MaxMemberCount = 20;
                    $chatTeam->ApplyJoinOption = 'FreeAccess';
                    $chatTeam->save();
                });
            }

            $form->footer(function ($footer) {
                // 去掉`查看`checkbox
                $footer->disableViewCheck();
                // 去掉`继续编辑`checkbox
                $footer->disableEditingCheck();
                // 去掉`继续创建`checkbox
                $footer->disableCreatingCheck();
            });
        });
    }
}
