<?php

namespace App\Http\Controllers\V1;

use App\Models\ChatTeam;
use App\Services\TencentImGroupService;
use App\Models\Game;
use App\Models\GameUser;
use Illuminate\Http\Request;
use App\Models\Course;
use App\Models\CourseHole;
use App\Models\User;
use App\Services\JPushService;
use App\Services\TencentImAccountService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class TestController extends Controller
{
    //定义比赛日期，计算历史最佳总杆，历史最好成绩
    protected $gameDate = [

        '2022-01-15 10:30:00',
        '2022-01-25 10:30:00',

        '2022-02-05 10:30:00',
        '2022-02-15 10:30:00',
        '2022-02-25 10:30:00',

        '2022-03-01 10:30:00',
        '2022-03-04 10:30:00',
    ];

    //定义比赛图片
    protected $gamePic = [
        'https://easygolf.oss-ap-southeast-6.aliyuncs.com/golf/2022-03/08/45966d66b954cb251395.jpeg',
        'https://easygolf.oss-ap-southeast-6.aliyuncs.com/golf/2022-03/08/9747823459b01e1cfe16.png',
        'https://easygolf.oss-ap-southeast-6.aliyuncs.com/golf/2022-03/08/dd69097ff0a2ef78cf49.png',
        'https://easygolf.oss-ap-southeast-6.aliyuncs.com/golf/images/5bf95963cc0647cae394d650e18f40e6.png',
        'https://easygolf.oss-ap-southeast-6.aliyuncs.com/golf/images/d402b91ed49155b2f3fa25b34685094c.png',
        'https://easygolf.oss-ap-southeast-6.aliyuncs.com/golf/images/7becd9a1175f8f809f2d2b55b4d1d5fc.png',
        'https://easygolf.oss-ap-southeast-6.aliyuncs.com/golf/2022-03/08/00f29945de472e4c53c9.png',
        'https://easygolf.oss-ap-southeast-6.aliyuncs.com/golf/2022-03/08/0fd625677bf98c6daabc.jpeg',
    ];

    //创建球场球洞
    public function index(Request $request)
    {
        $regID = $request->reg_id;
        $response = JPushService::getDevices($regID);

        print_r($response['alias']);
    }

    //入口文件
    public function createGameAllData(Request $request)
    {
        DB::beginTransaction();
        try{
            $creator = $request->creator;
            $gameDate = $this->gameDate;
            foreach ($gameDate as $date) {
                self::createGame($creator, $date);
            }
            DB::commit();
            return $this->success();
        }catch (\Exception $exception){
            DB::rollBack();
            Log::error($exception->getMessage());
            return $this->error();
        }
    }

    //创建比赛
    protected function createGame($creator, $created_at)
    {
        $num = Game::query()->orderBy('id', 'desc')->value('id');
        $num = $num ? $num + 1 : 1;
        $courseIds = self::getCourseIds(4);
        $gamePics = $this->gamePic;

        $data['name'] = 'This is game'.$num;

        $data['scale'] = rand(4, 20);
        $data['game_type_id'] = rand(1, 2);
        $data['creator'] = $creator ?: 9;
        $data['forbid_look'] = rand(0, 1);
        $data['forbid_join'] = rand(0, 1);
        $data['img'] = $gamePics[array_rand($gamePics)];;
        $data['lookers'] = 0;
        $data['members'] = $data['scale'] - rand(0, 3);
        $data['course_id'] = $courseIds[array_rand($courseIds)];
        $data['created_at'] = $created_at;
        $data['updated_at'] = $created_at;
        $begin_time = strtotime($created_at) + rand(3, 7) * 24 * 3600;
        $data['begin_time'] = date('Y-m-d H:i:s', $begin_time);
        $data['end_time'] = date('Y-m-d H:i:s', $begin_time + 6 * 3600);

        $game_id = DB::table('games')->insertGetId($data);

        //随机获取几个用户作为球员
        $userIds = self::getUserIds(4);
        array_push($userIds, $creator);
        $userIds = array_unique($userIds);

        //创建 群聊 线上才可以创建，本地要注释
        $group_name = 'This is game'.$num;
        //self::createChatTeam($game_id, $userIds, $group_name);

        //添加比赛球员
        foreach ($userIds as $user_id) {
            DB::table('game_users')->insertGetId([
                'game_id' => $game_id,
                'user_id' => $user_id,
                'status' => 1,
                'level' => rand(1, 4),
                'type' => 1,
                'created_at' => $created_at,
                'updated_at' => $created_at,
            ]);
            //随机抽取一个球员作为分数修改人
            $change_user_id = $userIds[array_rand($userIds)];

            //新增球员打球分数数据  $userIds是
            self::createGameUserScores($game_id, $user_id, $change_user_id, $created_at);
        }

        return $this->success($game_id);
    }

    //随机获取几个球场
    public static function getCourseIds($num)
    {
        $courseIds = Course::query()
            ->whereNull('deleted_at')
            ->pluck('id')
            ->toArray();
        //随机获取几个比赛球员(返回下标)
        $keys = array_rand($courseIds, $num);
        $newCourseIds = [];
        foreach ($keys as $key) {
            $newCourseIds[] = $courseIds[$key];
        }

        return $newCourseIds;
    }

    //随机获取几个用户
    protected function getUserIds($num)
    {
        $userIds = User::query()
            ->where('status', 1)
            ->whereNull('deleted_at')
            ->pluck('id')
            ->toArray();
        //随机获取几个比赛球员(返回下标)
        $keys = array_rand($userIds, $num);
        $newUserIds = [];
        foreach ($keys as $key) {
            $newUserIds[] = $userIds[$key];
        }

        return $newUserIds;
    }

    //创建比赛群聊
    protected function createChatTeam($game_id, $userIds, $group_name)
    {
        $group_service = new TencentImGroupService();
        $group_data = array();

        $game_users = User::query()->whereIn('id', $userIds)->select('tencent_im_user_id')->get()->toArray();

        $group_data['member_list'] = $game_users;
        $group_data['Owner_Account'] = $this->user->tencent_im_user_id;
        $group_data['group_name'] = $group_name;
        $group_data['avatar'] = 'https://zhengda.oss-accelerate.aliyuncs.com/golf/images/7c352d1bd0c6545c9e2440548772468c.png';
        $group_res = $group_service->createGroup($group_data);
        if ($group_res['ActionStatus'] == 'OK' && $group_res['ErrorCode'] == 0) {
            $game = Game::find($game_id);
            $game->GroupId = $group_res['GroupId'];
            $game->save();
        }

        $chatTeam = new ChatTeam();
        $chatTeam->user_id = $this->user->id;
        $chatTeam->Owner_Account = $this->user->tencent_im_user_id;
        $chatTeam->group_name = $group_name;
        $chatTeam->GroupId = $group_res['GroupId'];
        $chatTeam->FaceUrl = 'https://zhengda.oss-accelerate.aliyuncs.com/golf/images/7c352d1bd0c6545c9e2440548772468c.png';
        $chatTeam->MaxMemberCount = 20;
        $chatTeam->ApplyJoinOption = 'FreeAccess';
        $chatTeam->save();
    }

    //生成球员比赛成绩
    protected function createGameUserScores($game_id, $user_id, $change_user_id, $created_at)
    {
        $game_user_id = GameUser::where([
            'game_id' => $game_id,
            'user_id' => $user_id,
            'status' => 1,
        ])->whereNull('deleted_at')->value('id');

        $course_id = Game::where('id', $game_id)->value('course_id');
        $hole_ids = CourseHole::where('course_id', $course_id)->pluck('id');

        foreach ($hole_ids as $hole_id) {
            $val['game_user_id'] = $game_user_id;
            $val['hole_id'] = $hole_id;
            $val['change_user_id'] = $change_user_id; //随机抽取比赛成员作为成绩修改人
            $val['score'] = rand(2, 12); //产生随机杆数
            $val['created_at'] = date('Y-m-d H:i:s', strtotime($created_at));
            $val['updated_at'] = date('Y-m-d H:i:s', strtotime($created_at));

            DB::table('game_user_scores')->insert($val);
        }

        return $this->success();
    }

    //获取比赛中的球员
    protected function getGameUserIds($game_id)
    {
        $userIds = GameUser::query()
            ->where('game_id', $game_id)
            ->where('status', 1)
            ->whereNull('deleted_at')
            ->pluck('user_id')
            ->toArray();

        return $userIds;
    }

    //同步成员数
    public function addMembers()
    {
        $list = GameUser::query()
            ->whereNull('deleted_at')
            ->where('status',1)
            ->select('game_id', DB::raw('count(game_id) as members'))
            ->groupBy('game_id')
            ->get()
            ->toArray();
        $data = [];
        foreach ($list as $key=>$val){
            $data[] = [
                'id' => $val['game_id'],
                'members' => $val['members'],
            ];
        }
        $gameInstance = new Game;
        $index = 'id';
        batch()->update($gameInstance, $data, $index);
    }

    //获取第一个用户记录
    public function getFirstUserInfo()
    {
       $info =  User::query()->first();

       return $this->success($info);
    }

    //清空数据表
    public function clearTable()
    {
        DB::table('users')->truncate();
        DB::table('user_extras')->truncate();
        DB::table('user_follows')->truncate();
        DB::table('user_joins')->truncate();
        DB::table('user_message')->truncate();
        DB::table('user_feedback')->truncate();
        DB::table('user_identify')->truncate();

        DB::table('games')->truncate();
        DB::table('game_users')->truncate();
        DB::table('game_user_scores')->truncate();
        DB::table('game_lookers')->truncate();
        DB::table('game_fictitious')->truncate();

        DB::table('feeds')->truncate();
        DB::table('feed_like')->truncate();
        DB::table('feed_comment')->truncate();
        DB::table('feed_forward')->truncate();

        DB::table('teams')->truncate();
        DB::table('team_users')->truncate();
        DB::table('team_photos')->truncate();

        DB::table('chat_team')->truncate();
        DB::table('course_users')->truncate();
        DB::table('black_lists')->truncate();
        DB::table('sms_records')->truncate();
        DB::table('email_codes')->truncate();
        DB::table('base_attachments')->truncate();

        //用户ID、比赛ID、球队ID、球场ID 从 100001 开始增加
        DB::unprepared("alter table users AUTO_INCREMENT=100001");
        DB::unprepared("alter table games AUTO_INCREMENT=100001");
        DB::unprepared("alter table teams AUTO_INCREMENT=100001");
        DB::unprepared("alter table courses AUTO_INCREMENT=100001");

        //DB::table('courses')->where('id', '>', 0)->increment('id', 100000);
        //DB::table('course_holes')->where('id', '>', 0)->increment('course_id', 100000);

        return $this->success();
    }


}
