HomeController.php 31.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
<?php


namespace App\Http\Container\AppSection\Controllers;

use App\Helpers\JsonResource;
use App\Http\Container\AppSection\Requests\GroupInviteRequest;
use App\Http\Container\AppSection\Requests\GroupOutRequest;
use App\Http\Container\AppSection\Requests\HandleInviteRequest;
use App\Http\Container\AppSection\Requests\HideOrIstopRequest;
use App\Http\Container\AppSection\Requests\MemberTopRequest;
use App\Http\Service\GroupDataService;
use App\Http\Service\GroupInviteService;
use App\Http\Service\UserService;
use App\Jobs\UserSingerLimitJob;
use App\Models\Activity;
use App\Models\ActivityUser;
use App\Models\GroupHasMember;
use App\Models\GroupInvite;
use App\Models\Groups;
use App\Models\Pivots\UserProjectPivot;
use App\Models\Project;
use App\Models\SystemConfig;
use App\Models\User;
use App\Models\UserAction;
use App\Models\UserFollowRelation;
use App\Models\Views\ActivitySubmitWork;
use App\Support\Controller;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;


class HomeController extends Controller
{
    public function onSiteWorks(Request $request)
    {
        $user_id = $request->get('id', 0);
        $size    = $request->get('size', 1);
        $self_id = Auth::id();
        $query   = ActivitySubmitWork::query();
        //如果不是本人,过滤掉隐藏的数据
        if ($self_id != $user_id) {
            $query->where('is_hide', 0);
        }
        $data   = $query->with(['activity.linkArranger:id,nick_name', 'activity.tags:id,name', 'activity.project:id,name', 'activity:id,project_id,expand,status,song_name,sub_title,cover,sex,speed,lang'])
            ->whereHas('activity', function ($q) {
                $q->where('deleted_at', NULL);
            })
//            ->select('id','user_id','demo_url','durations','type','status','is_top','is_hide','activity_id','created_at')
            ->withCount('like')
            ->withExists('isLike')
            ->addSelect([
                'total_song'  => Activity::query()->selectRaw('count(*)')->whereNotIn('activitys.status', [0, 2, 4])->where('activitys.audit_status', 1)->whereColumn('activitys.project_id', 'activity_user_submits.project_id'),
                'online_song' => Activity::query()->selectRaw('count(*)')->where('activitys.status', 1)->where('activitys.audit_status', 1)->whereColumn('activitys.project_id', 'activity_user_submits.project_id')
            ])
            ->where('user_id', $user_id)
            ->orderBy('is_top', 'desc')
            ->orderBy('submit_at', 'desc')
            ->paginate($size);
        $config = SystemConfig::query()->where('status', 1)
            ->whereHas('parent', fn(Builder $builder) => $builder->where('status', 1)->whereIn('identifier', ['activity_lang', 'activity_speed', 'activity_sex']))
            ->pluck('name', 'identifier');
        $data->map(function (ActivitySubmitWork $item) use ($config) {
            $item->activity->setAttribute('sex', $config->get($item->activity->sex));
            $item->activity->setAttribute('speed', $config->get($item->activity->speed));
            $item->activity->setAttribute('lang', \Arr::map($item->activity->lang ?? [], static fn($l) => $config->get($l)));

            //编曲
            $item->activity->setAttribute('arranger', ['in_side' => $item->activity->linkArranger, 'out_side' => $item->activity->expand['arranger']['supplement'] ?? NULL]);
            $item->activity->setHidden(['linkArranger', 'expand']);
        });
        return JsonResource::success(JsonResource::SUCCESS, ['works' => $data->items(), 'count' => $data->total()]);

    }

    public function workHideOrIstop(HideOrIstopRequest $request)
    {
        $data    = $request->validated();
        $user_id = Auth::id();
        $top_num = ActivityUser::query()->where(['user_id' => $user_id, 'type' => 'Submit', 'is_top' => 1])->count();
        if ($top_num < 3 || ($data['field'] !== 'is_top' || $data['status'] === 0)) {
            ActivityUser::query()
                ->where(['id' => $data['id']])
                ->update([$data['field'] => $data['status'], "updated_at" => date("Y-m-d H:i:s")]);
            return JsonResource::success(JsonResource::UPDATE_SUCCESS);
        }
        return JsonResource::fail(JsonResource::IS_TOP_LIMIT);

    }

    public function groupFollow(Request $request)
    {
        $user_id = Auth::id();
        $size    = $request->get('size', 20);
        $type    = $request->get('type', 'follow');
        if ($type === 'follow') {
            $feild       = 'follower_id';
            $pluck_feild = 'following_id';
        } else {
            $feild       = 'following_id';
            $pluck_feild = 'follower_id';
        }
        $follower_ids = UserFollowRelation::query()
            ->where($feild, $user_id)
            ->orderByDesc('created_at')
            ->pluck($pluck_feild)
            ->toArray();
        //去掉已经加入团队的用户
        $member_ids = GroupHasMember::query()->pluck('member_id')->toArray();
        //去掉成员
        $difference     = array_diff($follower_ids, $member_ids);
        $difference_str = implode(',', $difference);
        $data           = User::query()
            ->with([
                'authTags' => fn($query) => $query->orderByDesc('weight')->orderByDesc('updated_at'),
                'userTag:id,name,icon,frame'
            ])
            ->whereIn('id', $difference)
            ->orderByRaw(DB::raw("FIELD(id, {$difference_str})"))
            ->select(['id', 'nick_name', 'avatar', 'identity', 'user_tag_id'])
            ->paginate($size);
        foreach ($data as $item) {
            $item->is_invite = GroupInvite::query()->where('created_at', '>=', now()->subMinutes(5))->where(['invite_id' => Auth::id(), 'user_id' => $item['id'], 'type' => 1, 'status' => 1])->exists();
        }
        return JsonResource::success(JsonResource::SUCCESS, ['data' => $data->items(), 'count' => $data->total()]);
    }

    public function gropuInvite(GroupInviteRequest $request)
    {
        $data    = $request->validated();
        $user_id = $data['user_id'];
        $type    = $data['type'];
        //邀请加入
        if ($type == 1) {
            $invite_id   = Auth::id();
            $member_id   = $user_id;
            $limit_msg   = JsonResource::INVITE_LIMIT;
            $success_msg = JsonResource::INVITE_SUCCESS;
            $member_user = User::query()->find($member_id);
            $invite_user = User::query()->find($invite_id);
            $title1      = sprintf('%s:歌手额度已满', $invite_user?->getAttribute('nick_name'));
            $content1    = sprintf('邀请歌手加入:%s', $member_user->getAttribute('nick_name'));
            $title2      = sprintf('%s:邀请歌手加入', $invite_user->getAttribute('nick_name'));
            $content2    = sprintf('歌手:%s', $member_user->getAttribute('nick_name'));
            $code        = 402;
        } //申请加入
        else {
            $invite_id   = $user_id;
            $member_id   = Auth::id();
            $limit_msg   = JsonResource::APPLY_LIMIT;
            $success_msg = JsonResource::APPLY_SUCCESS;
            $member_user = User::query()->find($member_id);
            $invite_user = User::query()->find($invite_id);
            $title1      = sprintf('%s:歌手额度已满', $invite_user?->getAttribute('nick_name'));
            $content1    = sprintf('%s:申请加入团队', $member_user->getAttribute('nick_name'));
            $title2      = sprintf('%s:申请加入团队', $member_user->getAttribute('nick_name'));
            $content2    = sprintf('经纪人:%s', $invite_user->getAttribute('nick_name'));
            $code        = 406;
        };
        //判断被邀请人是否存在团队
        $is_group = GroupHasMember::query()->where('member_id', $member_id)->exists();
        if ($is_group) {
            return JsonResource::fail(JsonResource::JOINED_TEAM, code: $code);
        }
        //判断1天内是否重复邀请/申请
        $group_id     = Groups::query()->where('user_id', $invite_id)->first()->id ?? 0;
        $defaultLimit = SystemConfig::query()->where('identifier', 'bZ__e20DwVDbQKiVWlJYc')->value('content') ?? 1;
        $is_limit     = GroupInvite::where('created_at', '>=', now()->subDays($defaultLimit))->where(['invite_id' => $invite_id, 'user_id' => $member_id, 'type' => $type, 'status' => 1])->exists();
        if ($is_limit) {
            return JsonResource::fail($limit_msg);
        }
        //判断被邀请人是否有歌手标签且自己团队歌手标签没超过限制
        $singerTags       = explode(',', SystemConfig::query()->where('identifier', 'auth_singer_tag')->value('content') ?? '');
        $is_singer_tag    = User::query()->where('id', $member_id)->whereHas('authTags', fn(Builder $builder) => $builder->whereIn('system_tags.id', $singerTags))->exists();
        $ids              = GroupHasMember::query()->where(['group_id' => $group_id, 'role' => 3])->pluck('member_id')->toArray();
        $singer_tag_count = User::query()->whereIn('id', $ids)->whereHas('authTags', fn(Builder $builder) => $builder->whereIn('system_tags.id', $singerTags))->count();
        //邀请人有团队就一定要是是团长
        $is_group = GroupHasMember::query()->where('member_id', $invite_id)->exists();
        if ($is_group) {
            $is_master = GroupHasMember::query()->where(['member_id' => $invite_id, 'role' => 1])->exists();
            //邀请人有群,不是是团长
            if (!$is_master) {
                return JsonResource::fail(JsonResource::NO_PERMISSION);
            }

        }
        //判断歌手额度
        $maxSingerNum = User::query()->whereKey($invite_id)->value('business_singer_limit');
        if ($is_singer_tag and $singer_tag_count >= $maxSingerNum) {
            UserSingerLimitJob::dispatch([
                'title'   => $title1,
                'content' => $content1
            ], [
                'title'   => $title2,
                'content' => $content2,
                'limit'   => $maxSingerNum
            ]);
            return JsonResource::fail(JsonResource::TEAM_INVITE_SINGER_LIMIT, code: 403);
        }

        //创建邀请数据
        GroupInvite::updateOrCreate(['invite_id' => $invite_id, 'user_id' => $member_id], [
            'group_id'   => $group_id,
            'type'       => $type,
            'status'     => 1,
            'created_at' => date("Y-m-d H:i:s"),
            'updated_at' => date("Y-m-d H:i:s")
        ]);
        return JsonResource::success($success_msg);
    }

    public function handleInvite(HandleInviteRequest $request, GroupInviteService $groupInviteService)
    {
        $data    = $request->validated();
        $user_id = $data['user_id'];
        $type    = $data['type'];
        $status  = $data['status'];
        //成员处理邀请
        if ($type == 1) {
            $invite_id   = $user_id;
            $member_id   = Auth::id();
            $member_msg  = JsonResource::SELF_MEMBER_JOINED_TEAM;
            $invite_msg  = JsonResource::INVITE_JOINED_TEAM;
            $member_user = User::query()->find($member_id);
            $invite_user = User::query()->find($invite_id);
            //查看团长用户是否存在
            if (!$invite_user) {
                //修改团长所有的邀请/申请为无效
                $groupInviteService->InviteStatus($invite_id);
                return JsonResource::fail(JsonResource::JOIN_TEAM_INVALID, code: 407);
            }
            $title1   = sprintf('%s:歌手额度已满', $invite_user?->getAttribute('nick_name'));
            $content1 = sprintf('同意经纪人邀请:%s', $member_user->getAttribute('nick_name'));
            $title2   = sprintf('%s:同意经纪人邀请', $member_user->getAttribute('nick_name'));
            $content2 = sprintf('经纪人:%s', $invite_user->getAttribute('nick_name'));
            $code     = 406;
        } //团长处理申请
        else {
            $invite_id   = Auth::id();
            $member_id   = $user_id;
            $member_msg  = JsonResource::MEMBER_JOINED_TEAM;
            $invite_msg  = JsonResource::SELF_INVITE_JOINED_TEAM;
            $member_user = User::query()->find($member_id);
            $invite_user = User::query()->find($invite_id);
            //查看成员用户是否存在
            if (!$member_user) {
                //修改成员所有的邀请/申请为无效
                $groupInviteService->InviteStatus($member_id);
                return JsonResource::fail(JsonResource::JOIN_TEAM_INVALID, code: 408);
            }
            $title1   = sprintf('%s:歌手额度已满', $invite_user?->getAttribute('nick_name'));
            $content1 = sprintf('%s:同意歌手加入', $member_user->getAttribute('nick_name'));
            $title2   = sprintf('%s:同意歌手加入', $invite_user->getAttribute('nick_name'));
            $content2 = sprintf('歌手 :%s', $member_user->getAttribute('nick_name'));
            $code     = 402;
        }

        //先判断存在待处理的邀请或申请,再判断是否超过7天失效
        $is_handel = GroupInvite::query()->where(['invite_id' => $invite_id, 'user_id' => $member_id, 'type' => $type, 'status' => 1])->exists();
        if (!$is_handel) {
            return JsonResource::fail(JsonResource::INVALIDED);
        }
        $defaultLimit = SystemConfig::query()->where('identifier', '-gYt2-b4MIRRePHVXpMnD')->value('content') ?? 7;
        $is_invalid   = GroupInvite::query()->where(['invite_id' => $invite_id, 'user_id' => $member_id, 'type' => $type, 'status' => 1])->where('created_at', '<=', now()->subDays($defaultLimit))->exists();
        if ($is_invalid) {
            GroupInvite::query()->where(['invite_id' => $invite_id, 'user_id' => $member_id, 'type' => $type])->update(['status' => 4]);
            return JsonResource::fail(JsonResource::JOIN_TEAM_INVALID);
        }
        //同意入群
        if ($status == 2) {
            $group_id = Groups::query()->where('user_id', $invite_id)->first()->id ?? 0;
            //判断成员有无团队
            $is_group = GroupHasMember::query()->where('member_id', $member_id)->exists();
            if ($is_group) {
                GroupInvite::query()->where(['invite_id' => $invite_id, 'user_id' => $member_id, 'type' => $type])->update(['status' => 4]);
                return JsonResource::fail($member_msg, code: $code);
            }
            //判断预备团长是否在其他团队且是成员
            $is_member = GroupHasMember::query()->where(['member_id' => $invite_id])->whereNot('role', 1)->exists();
            if ($is_member) {
                GroupInvite::query()->where(['invite_id' => $invite_id, 'user_id' => $member_id, 'type' => $type])->update(['status' => 4]);
                return JsonResource::fail($invite_msg, code: 405);
            }
            //判断被邀请人是否有歌手标签且自己团队歌手标签没超过限制
            $singerTags       = explode(',', SystemConfig::query()->where('identifier', 'auth_singer_tag')->value('content') ?? '');
            $is_singer_tag    = User::query()->where('id', $member_id)->whereHas('authTags', fn(Builder $builder) => $builder->whereIn('system_tags.id', $singerTags))->exists();
            $ids              = GroupHasMember::query()->where(['group_id' => $group_id, 'role' => 3])->pluck('member_id')->toArray();
            $singer_tag_count = User::query()->whereIn('id', $ids)->whereHas('authTags', fn(Builder $builder) => $builder->whereIn('system_tags.id', $singerTags))->count();
            $is_master        = GroupHasMember::query()->where(['member_id' => $invite_id, 'role' => 1])->exists();
            if ($is_master) {
                $maxSingerNum = User::query()->whereKey($invite_id)->value('business_singer_limit');
                if ($is_singer_tag and $singer_tag_count >= $maxSingerNum) {
                    GroupInvite::query()->where(['invite_id' => $invite_id, 'user_id' => $member_id, 'type' => $type, 'status' => 1])->update(['status' => 4]);
                    UserSingerLimitJob::dispatch([
                        'title'   => $title1,
                        'content' => $content1
                    ], [
                        'title'   => $title2,
                        'content' => $content2,
                        'limit'   => $maxSingerNum
                    ]);
                    return JsonResource::fail(JsonResource::TEAM_JOIN_SINGER_LIMIT, code: 403);
                }
            }
            DB::transaction(function () use ($group_id, $invite_id, $member_id, $groupInviteService) {
                //没团队创建团队群主加入团队
                if ($group_id == 0) {
                    $group = Groups::create(['user_id' => $invite_id, 'created_at' => date("Y-m-d H:i:s"), 'updated_at' => date("Y-m-d H:i:s")]);
                    GroupHasMember::create(['group_id' => $group->id, 'member_id' => $invite_id, 'role' => 1, 'created_at' => date("Y-m-d H:i:s"), 'updated_at' => date("Y-m-d H:i:s")]);
                    $group_id = $group->id;
                }

                //用户表推business_id维护
                User::query()->find($member_id)->update(['business_id' => $invite_id]);
                //改变经纪人身份
                UserService::syncBusinessIdentity($invite_id);
                //入群
                GroupHasMember::create(['group_id' => $group_id, 'member_id' => $member_id, 'created_at' => date("Y-m-d H:i:s"), 'updated_at' => date("Y-m-d H:i:s")]);
                //修改成员所有的邀请/申请为无效
                $groupInviteService->InviteStatus($member_id);

            });
        }

        //修改邀请状态
        GroupInvite::query()->where(['invite_id' => $invite_id, 'user_id' => $member_id, 'type' => $type])->update(['status' => $status]);
        return JsonResource::success(JsonResource::HANDLE_SUCCESS);
    }

    public function groupMembers(Request $request)
    {
        $id       = $request->integer('id');
        $type     = $request->integer('type', 0);
        $text     = $request->get('text');
        $size     = $request->integer('size', 30);
        $group_id = GroupHasMember::query()->where('member_id', $id)->first()->group_id ?? 0;
        $query    = GroupHasMember::query()->where(['group_id' => $group_id])
            ->orderBy('role') //群主排最前面
            ->orderByDesc('is_top')
            ->orderByDesc('updated_at');
        //type=1 歌曲分享团队成员列表去掉自己
        if ($type === 1) {
            $query->whereNot('member_id', Auth::id());
        }
        $member_ids     = $query
            ->pluck('member_id')
            ->toArray();
        $member_ids_str = implode(',', $member_ids);
        $query          = User::query()
            ->with(['authTags:id,name', 'userTag:id,name,icon,frame'])
            ->whereIn('id', $member_ids);
        //搜索词搜索
        if ($text) {
            $query->whereLike('nick_name', $text);
        }
        $data = $query
            ->orderByRaw(DB::raw("FIELD(id, {$member_ids_str})"))
            ->select(['id', 'nick_name', 'avatar', 'identity', 'user_tag_id'])
            ->paginate($size);
        foreach ($data as $item) {
            $item->is_top  = GroupHasMember::query()->where(['group_id' => $group_id, 'member_id' => $item->id, 'is_top' => 1])->exists();
            $item->is_self = Auth::id() === $item->id;
            //当前用户是否是团长
            $is_master         = GroupHasMember::query()->where(['group_id' => $group_id, 'role' => 1, 'member_id' => Auth::id()])->exists();
            $item->is_showMore = ($item->is_self === false && $is_master && Auth::id() === $id);
        }
        return JsonResource::success(JsonResource::SUCCESS, ['data' => $data->items(), 'count' => $data->total()]);
    }

    public function memberTop(MemberTopRequest $request)
    {
        $data      = $request->validated();
        $member_id = $data['member_id'];
        $status    = $data['status'];
        $group_id  = GroupHasMember::query()->where('member_id', $member_id)->first()->group_id ?? 0;
        $top_count = GroupHasMember::query()->where(['group_id' => $group_id])->where('is_top', 1)->count();
        if ($top_count >= 5 and $status == 1) {
            return JsonResource::fail(JsonResource::MEMBER_TOP_LIMIT);
        }
        GroupHasMember::query()->where(['member_id' => $member_id])->update(['is_top' => $status, 'updated_at' => date("Y-m-d H:i:s")]);
        return JsonResource::success(JsonResource::UPDATE_SUCCESS);
    }

    public function groupOut(GroupOutRequest $request)
    {
        $data = $request->validated();
        $type = $data['type'];  //1:申请退出或取消退出 2:直接踢出,同意退出申请
        //成员申请退出或取消
        if ($type == 1) {
            try {
                $status = $data['status'];  // 1:取消退出  2:申请退出
            } catch (\Exception) {
                return JsonResource::fail('请填写status,确定是退出,还是取消退出');
            }
            $query = GroupHasMember::query()->where('member_id', Auth::id());
            $query->update(['status' => $status, 'updated_at' => date("Y-m-d H:i:s")]);
            $group_id  = $query->first()->group_id;
            $master_id = GroupHasMember::query()->where(['group_id' => $group_id, 'role' => 1])->first()->member_id;
            $master    = User::query()->find($master_id, ['id', 'nick_name', 'avatar']);

        } //团长直接踢人
        else {
            try {
                $user_id = $data['user_id'];  //被踢用户id
            } catch (\Exception) {
                return JsonResource::fail('请填写user_id,确定被移出群用户');
            }
            //处理退出申请团队
            if ($type == 2) {
                //判断是否已经处理,处于退群申请中
                $is_outing = GroupHasMember::query()->where(['member_id' => $user_id, 'status' => 2])->exists();
                if (!$is_outing) {
                    return JsonResource::fail(JsonResource::MEMBER_OUT_INVALID);
                }
            }
            //踢出团队 type=3,判断被踢的人是不是团长
            $query     = GroupHasMember::query()->where('member_id', Auth::id());
            $group_id  = $query->first()->group_id;
            $master_id = GroupHasMember::query()->where(['group_id' => $group_id, 'role' => 1])->first()->member_id;
            if ($master_id == $user_id) {
                return JsonResource::fail('团长不能踢出自己');
            }
            $user = User::query()->find($user_id);
            UserService::deleteGroupMember($user);
            $master = User::query()->find(Auth::id(), ['id', 'nick_name', 'avatar']);
        }
        return JsonResource::success(JsonResource::UPDATE_SUCCESS, $master);

    }

    public function blackList(Request $request)
    {
        $ids   = $request->get('id');
        $text  = $request->get('text');
        $query = User::query()->whereIn('id', $ids);
        if ($text) {
            $query->whereLike('nick_name', $text);
        }
        $data = $query
            ->select('id', 'avatar', 'nick_name', 'identity')
            ->orderBy('id')
            ->get();
        return JsonResource::success(JsonResource::SUCCESS, $data);

    }

    public function groupData(GroupDataService $groupDataService, Request $request)
    {
        $user_id  = Auth::id();
        $group_id = GroupHasMember::query()->where(['member_id' => $user_id, 'role' => 1])->value('group_id') ?? 0;
        if (!$group_id) {
            return JsonResource::fail(JsonResource::NO_PERMISSION);
        }
        $ids = GroupHasMember::query()->where(['group_id' => $group_id, 'role' => 3])->pluck('member_id')->toArray();
        //预览
        $overview = $groupDataService->overview($ids);
        //成员统计
        $member_statistics = $groupDataService->memberStatistics($ids);
        //成员认证情况
        $auth_info = $groupDataService->auth($ids);
        //折线图
        $chart = $groupDataService->trend($ids);
        $data  = ['overview' => $overview, 'member_statistics' => $member_statistics, 'auth_info' => $auth_info, 'trend' => $chart];
        return JsonResource::success(JsonResource::SUCCESS, $data);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function memberStatisticsDetail(Request $request): JsonResponse
    {
        $type    = $request->integer('type', 1);
        $size    = $request->integer('size', 20);
        $user_id = Auth::id();

        if (!$group_id = GroupHasMember::query()->where(['member_id' => $user_id, 'role' => 1])->value('group_id')) {
            return JsonResource::fail(JsonResource::NO_PERMISSION);
        }
        $ids = GroupHasMember::query()->where(['group_id' => $group_id, 'role' => 3])->pluck('member_id')->toArray();


        //1:昨日登录,2:昨日试听,3:昨日试唱,4:昨日合作
        $ids1 = match ($type) {
            1 => UserAction::query()->whereIn('user_id', $ids)
                ->whereBetween('created_at', [Carbon::yesterday()->startOfDay(), Carbon::yesterday()->endOfDay()])
                ->distinct()->pluck('user_id')->toArray(),
            2 => UserAction::query()->whereIn('user_id', $ids)
                ->whereIn('event_name', ["listen_clip", "listen_entire"])
                ->whereBetween('created_at', [Carbon::yesterday()->startOfDay(), Carbon::yesterday()->endOfDay()])
                ->distinct()->pluck('user_id')->toArray(),
            3 => UserAction::query()
                ->whereIn('user_id', $ids)
                ->whereIn('event_name', ["submit_piece_online", "submit_sing_offline", "submit_sing_online"])
                ->whereBetween('created_at', [Carbon::yesterday()->startOfDay(), Carbon::yesterday()->endOfDay()])
                ->distinct()->pluck('user_id')->toArray(),
            4 => ActivityUser::query()
                ->join('activitys', 'activity_has_users.activity_id', '=', 'activitys.id')
                ->whereDate('activitys.match_at', Carbon::yesterday())
                ->whereIn('activity_has_users.user_id', $ids)
                ->where(['activity_has_users.type' => 'Submit', 'activity_has_users.status' => 1])
                ->distinct()->pluck('activity_has_users.user_id')->toArray(),
            default => []
        };

        $data = User::orderByField('id', $ids1)
            ->with(['authTags:id,name', 'userTag:id,name,icon,frame'])
            ->select(['id', 'avatar', 'nick_name', 'identity', 'user_tag_id'])
            ->where('status', 1)
            ->paginate($size);

        return JsonResource::success(JsonResource::SUCCESS, ['data' => $data->items(), 'count' => $data->total()]);
    }

    public function trendDetail(Request $request)
    {
        $id       = $request->get('id');
        $size     = $request->get('size', 20);
        $type     = $request->get('type', 1);
        $date     = $request->get('date');
        $nextDay  = date("Y-m-d", strtotime($date . " +1 day"));  //date这1天结束日期
        $user_id  = Auth::id();
        $group_id = GroupHasMember::query()->where(['member_id' => $user_id, 'role' => 1])->value('group_id') ?? 0;
        $ids      = GroupHasMember::query()->where(['group_id' => $group_id, 'role' => 3])->pluck('member_id')->toArray();
        //存在群且当前
        if (!$group_id and in_array($user_id, $ids)) {
            return JsonResource::fail(JsonResource::NO_PERMISSION);
        }
        //试听歌曲
        if ($type == 1) {
            $ids = UserAction::query()
                ->whereIn('event_name', ["listen_clip", "listen_entire"])
                ->where('user_id', $id)
                ->whereBetween('created_at', [$date, $nextDay])
                ->orderBy('created_at', 'desc')
                ->pluck('activity_id')
                ->toArray();
        }
        // 收藏歌曲
        if ($type == 2) {
            $ids = UserAction::query()
                ->where('event_name', 'song_like')
                ->where('user_id', $id)
                ->whereBetween('created_at', [$date, $nextDay])
                ->orderBy('created_at', 'asc')
                ->pluck('activity_id')
                ->toArray();
        }
        // 试唱歌曲
        if ($type == 3) {
            $ids = UserAction::query()
                ->whereIn('event_name', ["submit_piece_online", "submit_sing_offline", "submit_sing_online"])
                ->where('user_id', $id)
                ->whereBetween('created_at', [$date, $nextDay])
                ->orderBy('created_at', 'asc')
                ->pluck('activity_id')
                ->toArray();
        }
        // 合作歌曲
        if ($type == 4) {
            $ids = ActivityUser::query()
                ->join('activitys', 'activity_has_users.activity_id', '=', 'activitys.id')
                ->where('activity_has_users.user_id', $id)
                ->where(['activity_has_users.type' => 'Submit', 'activity_has_users.status' => 1])
                ->whereBetween('activitys.match_at', [$date, $nextDay])
                ->orderBy('activity_has_users.created_at', 'asc')
                ->pluck('activity_has_users.activity_id')
                ->toArray();
        }
        $data = Activity::query()
            ->whereIn('id', $ids)
            ->with(['project:id,name', 'tags:id,name'])
            ->select('id', 'cover', 'status', 'song_name', 'project_id', 'created_at')
            ->orderBy('created_at')
            ->paginate($size);
        return JsonResource::success(JsonResource::SUCCESS, ['data' => $data->items(), 'count' => $data->total()]);
    }

    public function tabledetail(GroupDataService $groupDataService, Request $request)
    {
        $type     = $request->get('type', 1);
        $date     = $request->get('date');
        $nextDay  = date("Y-m-d", strtotime($date . " +1 day"));  //date这1天结束日期
        $user_id  = Auth::id();
        $group_id = GroupHasMember::query()->where(['member_id' => $user_id, 'role' => 1])->value('group_id') ?? 0;
        //存在群且当前
        if (!$group_id) {
            return JsonResource::fail(JsonResource::NO_PERMISSION);
        }
        $ids = GroupHasMember::query()->where(['group_id' => $group_id, 'role' => 3])->pluck('member_id')->toArray();
        //已听
        if ($type == 1) {
            $data = $groupDataService->listenTable($ids, $date, $nextDay);
        }
        //已收藏
        if ($type == 2) {
            $data = $groupDataService->collectionTable($ids, $date, $nextDay);
        }
        //已试唱
        if ($type == 3) {
            $data = $groupDataService->singTable($ids, $date, $nextDay);
        }
        //已合作
        if ($type == 4) {
            $data = $groupDataService->cooperateTable($ids, $date, $nextDay);
        }
        return JsonResource::success(JsonResource::SUCCESS, $data);

    }

    public function projectList(Request $request)
    {
        $id   = $request->get('id');
        $size = $request->get('size', 20);
        $ids  = UserProjectPivot::query()->where('user_id', $id)->pluck('project_id')->toArray();
        $data = Project::query()
            ->whereIn('id', $ids)
            ->where('status', 1)
            ->select(['id', 'intro', 'name', 'cover'])
            ->with(['comfirmTime:project_id,average_day'])
            ->withCount(['totalSong', 'onlineSong'])
            ->orderByDesc('created_at')
            ->paginate($size);
        return JsonResource::success(JsonResource::SUCCESS, ['data' => $data->items(), 'count' => $data->total()]);

    }
}