UserActivityController.php 9.98 KB
<?php

namespace App\Http\Container\AppSection\Controllers;

use App\Enums\ActivityAuditStatusEnum;
use App\Enums\ActivityWorkTypeEnum;
use App\Helpers\JsonResource;
use App\Models\Activity;
use App\Models\Pivots\ActivityTagPivot;
use App\Models\Pivots\UserActivityCollectionPivot;
use App\Models\Project;
use App\Models\User;
use Carbon\Carbon;
use Hikoon\LaravelApi\Support\ApiController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;


/**
 * 用户唱片
 */
class UserActivityController extends ApiController
{

    /**
     * 已经完成
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function taCollection(Request $request): JsonResponse
    {
        $size     = $request->get('size', 0);
        $songType = $request->get('song_type', 1);
        $size     = $size < 0 ? 10 : $size;
        $userId   = Auth::id();
        // 获取关联的歌手id
        $singerIdsQuery = User::query()->where('business_id', '=', $userId)
            ->where('deleted_at', '=', NULL)->select(['id']);
        // 获取歌手收藏的活动id
        $activityList = UserActivityCollectionPivot::query()->whereIn('user_id', $singerIdsQuery)
            ->where('deleted_at', '=', NULL)->orderBy('created_at', 'desc')
            ->select(['activity_id', 'user_id'])->get()->toArray();

        $all_activity_ids = [];
        $userIds          = [];
        foreach ($activityList as $value) {
            $all_activity_ids[] = $value['activity_id'];
            $userIds[]          = $value['user_id'];
        }

        $orderByRaw = implode(',', $all_activity_ids);
        $data       = Activity::query()->whereIn('id', $all_activity_ids)
            ->where('status', '=', 1)
            ->where('song_type', '=', $songType)
            ->where('deleted_at', '=', NULL)
            ->withCount('attend_union_user_count as attend_count')
            ->orderByRaw(DB::raw("FIELD(id,$orderByRaw)"))
            ->paginate($size);

        $list       = $data->items();
        $projectIds = [];

        $activity_ids = [];

        foreach ($list as $v) {
            $projectIds[]   = $v['project_id'];
            $activity_ids[] = $v['id'];
        }


        $tagList = ActivityTagPivot::query()->leftJoin('system_tags', 'activity_has_tags.tag_id', '=', 'system_tags.id')
            ->whereIn('activity_has_tags.activity_id', $activity_ids)
            ->where('activity_has_tags.deleted_at', '=', NULL)
            ->where('system_tags.deleted_at', '=', NULL)
            ->select(['activity_has_tags.id', 'system_tags.name', 'activity_has_tags.activity_id'])->get()->toArray();

        $projectList = Project::query()->leftJoin('users', 'users.id', '=', 'projects.master_id')->whereIn('projects.id', $projectIds)
            ->where('projects.status', '=', 1)
            ->where('projects.deleted_at', '=', NULL)->select(['projects.*', 'users.nick_name', 'users.real_name', 'users.avatar'])->get()->toArray();
        foreach ($projectList as $k => $v) {
            $projectList[$k]['master'] = [
                'id'        => $v['master_id'],
                'nick_name' => $v['nick_name'],
                'real_name' => $v['real_name'],
                'avatar'    => $v['avatar']
            ];
            unset($projectList[$k]['nick_name']);
            unset($projectList[$k]['real_name']);
            unset($projectList[$k]['avatar']);
        }

        $collectionList = UserActivityCollectionPivot::query()
            ->leftJoin('users', 'users.id', '=', 'user_activity_collections.user_id')
            ->leftJoin('user_messages', function ($join) use ($userId) {
                $join->on('user_messages.activity_id', '=', 'user_activity_collections.activity_id')
                    ->on('user_messages.sender_id', '=', 'user_activity_collections.user_id')
                    ->where('user_messages.type', '=', 2)
                    ->where('user_messages.is_read', '=', 0)
                    ->where('user_messages.is_bind', '=', 1)
                    ->where('user_messages.receiver_id', '=', $userId)
                    ->where('user_messages.deleted_at', '=', NULL);
            })
            ->whereIn('user_activity_collections.activity_id', $activity_ids)
            ->whereIn('user_activity_collections.user_id', $userIds)
            ->select(['user_activity_collections.id', 'user_activity_collections.user_id', 'user_activity_collections.activity_id', 'user_activity_collections.created_at', 'users.nick_name', 'users.intro', 'users.real_name', 'users.avatar', 'users.province', 'users.city', 'users.company', 'users.rate', 'user_messages.id as is_new'])
            ->orderByDesc('user_activity_collections.created_at')
            ->get()->toArray();

        foreach ($list as $k => $v) {
            // 遍历tagList 数据
            $activeId            = $v['id'];
            $tag                 = array_filter(array_map(function ($value) use ($activeId) {
                if ($value['activity_id'] == $activeId) {
                    return ['id' => $value['id'], 'name' => $value['name']];
                }
            }, $tagList));
            $list[$k]['tags']    = array_values($tag);
            $project             = array_filter(array_map(function ($item) use ($v) {
                if ($item['id'] == $v['project_id']) {
                    return $item;
                }
            }, $projectList));
            $list[$k]['project'] = array_values($project);
            $collection          = array_filter(array_map(function ($item) use ($activeId) {
                if ($item['activity_id'] == $activeId) {
                    return [
                        'id'          => $item['id'],
                        'user_id'     => $item['user_id'],
                        'activity_id' => $item['activity_id'],
                        'created_at'  => Carbon::parse($item['created_at'])->format('Y-m-d H:i:s'),
                        'user'        => [
                            'id'        => $item['user_id'],
                            'nick_name' => $item['nick_name'],
                            'intro'     => $item['intro'],
                            'real_name' => $item['real_name'],
                            'avatar'    => $item['avatar'],
                            'province'  => $item['province'],
                            'city'      => $item['city'],
                            'company'   => $item['company'],
                            'rate'      => $item['rate'],
                        ],
                        'is_new'      => $item['is_new'] > 0,
                    ];
                }
            }, $collectionList));

            $list[$k]['collection'] = array_values($collection);
        }

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


    /**
     * 听过
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userListen(Request $request)
    {
        $pageSize     = $request->integer('size', 10);
        $song_type    = $request->get('song_type', '1');
        $user_id      = Auth::id();
        $activity_ids = DB::table('user_view_activitys')
            ->where('user_id', $user_id)
            ->whereNull('deleted_at')
            ->orderByDesc('updated_at')
            ->pluck('activity_id')
            ->toArray();
        $data         = Activity::query()
            ->with('user:id,nick_name,avatar')
            ->whereIn('id', $activity_ids)
            ->whereIn('status', [1, 2, 3, 5])
            ->where('song_type', $song_type)
            ->with(['tags:id,name', 'project.master:id,nick_name,real_name,avatar'])
            ->withExists('is_unlike')
            ->select(['id', 'cover', 'song_name', 'status', 'is_official', 'created_at', 'sub_title', 'guide', 'lyric', 'clip_lyric', 'user_id', 'project_id'])
            ->orderByRaw(DB::raw("FIELD(id, " . implode(',', $activity_ids) . ")"))
            ->paginate($pageSize);

        $view_activity_ids = array_column($data->items(), 'id');
        $data->each(function (Activity $activity) use ($view_activity_ids) {
            $activity->setAttribute('is_unlike', $activity->is_unlike_exists === 1);
        });
        $listen_at_list = DB::table('user_view_activitys')
            ->whereIn('activity_id', $view_activity_ids)
            ->where('user_id', $user_id)
            ->whereNull('deleted_at')
            ->pluck('updated_at', 'activity_id')
            ->toArray();
        $result         = json_decode(json_encode($data->items()), true);
        foreach ($result as &$v) {
            $v['listen_at'] = !empty($listen_at_list[$v['id']]) ? $listen_at_list[$v['id']] : '';
            unset($v['user_id'], $v['project_id']);
        }

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


    /**
     * @param \Illuminate\Http\Request $request
     * @param int                      $id
     * @return \Illuminate\Http\JsonResponse
     * @author Jun
     */
    public function submitActivity(Request $request, int $id): JsonResponse
    {
        $size = $request->get('size', 0);


        $activities = Activity::query()
            ->with(['tags:id,name', 'project:id,name,cover'])
            ->join('activity_has_users', 'activity_has_users.activity_id', 'activitys.id')
            ->selectRaw('activitys.id,activitys.song_name,activitys.cover,activitys.project_id,activitys.status,activity_has_users.submit_at,activity_has_users.demo_url as submit_url,activity_has_users.status as submit_status')
            ->where('activity_has_users.type', ActivityWorkTypeEnum::SUBMIT)
            ->where('activitys.audit_status', ActivityAuditStatusEnum::SUCCESS)
            ->where('activity_has_users.user_id', $id)
            ->orderByDesc('activity_has_users.submit_at')
            ->paginate($size);

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