<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Teams\TeamFeeds;
use App\Admin\Actions\Teams\TeamPhotos;
use App\Admin\Actions\Teams\TeamUsers;
use App\Models\ChatTeam;
use App\Models\Team;
use App\Models\TeamUser;
use App\Models\User;
use App\Services\TencentImGroupService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Modal;
use Illuminate\Support\Facades\DB;

class TeamController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Team());
        $grid->model()->with(['creator_s:id,name,avatar'])->orderByDesc('id');
        $grid->column('id')->sortable();
        $grid->column('img')->image('', 50);
        $grid->column('name');
//        $grid->column('creator');
        $grid->column('creator_s.name', trans('team.fields.creator'));
        $grid->column('address');
        $grid->column('member_counts')->display(function ($res) {
            $form = TeamUsers::make()->payload(['id' => $this->id]);
            return Modal::make()
                ->lg()
                ->title(trans('team.fields.Member_list'))
                ->body($form)
                ->button('<i class="feather icon-align-right"></i> ' . $res);

        });
        $grid->column('slogan');
        $grid->column('desc');

        $grid->column('allow_join')->switch('success', true);
        $grid->column('set_date');
//        $grid->column('created_at');
//        $grid->column('updated_at')->sortable();

        $grid->filter(function (Grid\Filter $filter) {
            $filter->equal('id');
            $filter->like('name');
        });

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->append(new TeamFeeds(User::class));
            $actions->append(new TeamPhotos(User::class));
            $actions->disableView();
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Team(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('img');
            $show->field('address');
            $show->field('member_counts');
            $show->field('slogan');
            $show->field('desc');
            $show->field('creator');
            $show->field('allow_join');
            $show->field('set_date');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Team(), function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->image('img')->saveFullUrl()->autoUpload();
            $form->text('address')->default('');
            $form->text('member_counts')->default(10);
            $form->text('slogan')->default('');
            $form->text('desc')->default('');

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

            $form->display('created_at');
            $form->display('updated_at');

            $form->saved(function (Form $form) {
                if ($form->isCreating()) {
                    $teamId = $form->getKey();
                    $teamUser = new TeamUser();
                    $teamUser->team_id = $teamId;
                    $teamUser->user_id = $form->creator;
                    $teamUser->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);
                    if ($groupResult['ActionStatus'] == 'OK' && $groupResult['ErrorCode'] == 0) {
                        DB::table('teams')->where('id', $teamId)->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();
            });
        });
    }
}
