IndexController.php 9.44 KB
<?php

namespace App\Http\Container\AdminSection\Controllers\Dashboard;

use App\Enums\ActivityWorkModeEnum;
use App\Enums\ActivityWorkTypeEnum;
use App\Models\UserAction;
use App\Models\Views\ActivityWork;
use App\Support\Controller;
use Arr;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Hikoon\LaravelApi\Facades\Response;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Vtiful\Kernel\Excel;
use Vtiful\Kernel\Format;

class IndexController extends Controller
{
    /**
     * @param \Illuminate\Http\Request $request
     * @return \Hikoon\LaravelApi\Facades\Response|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function submitWork(Request $request): Response|BinaryFileResponse
    {
        $pageSize = $request->get('pageSize', 20);
        $filter   = $request->except('page', 'pageSize');

        $build = ActivityWork::filter($filter)
            ->select([
                'id', 'activity_id', 'activity_name', 'activity_type', 'activity_title', 'activity_status', 'project_id',
                'user_id', 'user_nick_name', 'user_real_name', 'user_identity', 'business_id',
                'price_id', 'mode', 'sing_type', 'demo_url', 'submit_at', 'status'
            ])
            ->with([
                'business' => fn($query) => $query->select(['id', 'nick_name', 'real_name', 'identity'])->where('identity', 3),
                'project:id,name',
                'tags:id,name',
                'price:id,value,is_deduct,is_talk,is_accept_address,address_id',
            ])
            ->where('type', ActivityWorkTypeEnum::SUBMIT);


        if ($request->get('fetchType') === 'excel') {
            $fileName   = Str::random(32) . '.xlsx';
            $excel      = new Excel(['path' => storage_path('excels')]);
            $fileObject = $excel->constMemory($fileName, NULL, false);
            $format     = new Format($fileObject->getHandle());
            $headStyle  = $format->align(Format::FORMAT_ALIGN_CENTER, Format::FORMAT_ALIGN_VERTICAL_CENTER)->background(0XF2F2F2)->bold()->toResource();


            $row = $fileObject
                ->header(['名称', '推荐语', '歌曲风格', '厂牌', '用户艺名', '用户真名', '身份', '经纪人艺名', '经纪人真名', '试唱方式', '唱酬', '分成', '价格是否可谈', '录音地点', '是否接受其他录音地点', '提交时间', '试唱音频', '试唱结果'])
                ->setRow('A1', 22, $headStyle)
                ->setColumn('A:J', 16)
                ->setColumn('K:U', 14);

            $build->chunk(1000, static function (Collection $collection) use ($fileObject) {
                $fileObject->data($collection->map(static function (ActivityWork $work) {
                    $price        = $work->getAttribute('price');
                    $userIdentity = data_get($work, 'user_identity', 0);

                    return [
                        data_get($work, 'activity_name', ''),
//                        ActivitySongTypeEnum::tryFrom(data_get($work, 'activity_type', 1))?->label(),
                        data_get($work, 'activity_title', ''),
                        $work->getRelation('tags')->implode('name', '、'),
                        data_get($work, 'project.name', ''),
                        data_get($work, 'user_nick_name', ''),
                        data_get($work, 'user_real_name', ''),
                        match ($userIdentity) {
                            0 => '未认证',
                            1 => '音乐人',
                            2, 3 => "经纪人",
                            default => ''
                        },
                        data_get($work, 'business.nick_name', ''),
                        data_get($work, 'business.real_name', ''),
                        $work->getAttribute('mode') === ActivityWorkModeEnum::OFFLINE ? $work->getAttribute('mode')?->label() : $work->getAttribute('sing_type')?->label(),
                        data_get($price, 'value.is_reward', 0) === 1 ? data_get($price, 'value.amounts') : '无',
                        data_get($price, 'value.is_dividend', 0) === 1 ? $price->getDividendFormat() : '无',
                        data_get($price, 'is_talk', 0) === 1 ? '是' : '否',
                        $price ? $price->getAddressFormat() : '',
                        data_get($price, 'is_accept_address', 0) === 1 ? '是' : '否',
                        data_get($work, 'submit_at', ''),
                        data_get($work, 'demo_url', ''),
                        $work->getFormatStatus()
                    ];
                })->toArray());
            });
            return response()->download($row->output(), $fileName)->deleteFileAfterSend();
        }

        return $this->successWithData($build->paginate($pageSize));
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return \Hikoon\LaravelApi\Facades\Response|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function overview(Request $request): Response|BinaryFileResponse
    {
        $request->validate([
            'createBetween'   => 'required|array|size:2',
            'createBetween.*' => 'date'
        ], [
            'createBetween.required' => '请选择查询区间',
            'createBetween.array'    => '查询参数异常',
            'createBetween.size'     => '查询参数异常',
            'createBetween.*.date'   => '查询参数异常'
        ]);
        $searchTime = $request->offsetGet('createBetween');

        $startTime = Carbon::parse(Arr::first($searchTime))->startOfDay();
        $endTime   = Carbon::parse(Arr::last($searchTime))->startOfDay();

        $calendar = CarbonPeriod::create($startTime, '1 day', $endTime);

        $listerUserCount = UserAction::query()
            ->selectRaw("DATE_FORMAT(created_at,'%Y-%m-%d') as days,count(distinct user_id) as num")
            ->whereIn('event_name', ['listen_clip', 'listen_entire'])
            ->whereBetween('created_at', [$calendar->first()?->startOfDay()->toDateTimeString(), $calendar->last()?->endOfDay()->toDateTimeString()])
            ->groupByRaw('days')->pluck('num', 'days');

        $listerCount = UserAction::query()
            ->selectRaw("DATE_FORMAT(created_at,'%Y-%m-%d') as days,count(*) as num")
            ->whereIn('event_name', ['listen_clip', 'listen_entire'])
            ->whereBetween('created_at', [$calendar->first()?->startOfDay()->toDateTimeString(), $calendar->last()?->endOfDay()->toDateTimeString()])
            ->groupByRaw('days')->pluck('num', 'days');

        $likeCount = UserAction::query()
            ->selectRaw("DATE_FORMAT(created_at,'%Y-%m-%d') as days,count(*) as num")
            ->whereIn('event_name', ['bottom_like', 'song_like', 'sing_like'])
            ->whereBetween('created_at', [$calendar->first()?->startOfDay()->toDateTimeString(), $calendar->last()?->endOfDay()->toDateTimeString()])
            ->groupByRaw('days')->pluck('num', 'days');

        $submitCount = UserAction::query()
            ->selectRaw("DATE_FORMAT(created_at,'%Y-%m-%d') as days,count(*) as num")
            ->whereIn('event_name', ['submit_piece_online', 'submit_sing_offline', 'submit_sing_online'])
            ->whereBetween('created_at', [$calendar->first()?->startOfDay()->toDateTimeString(), $calendar->last()?->endOfDay()->toDateTimeString()])
            ->groupByRaw('days')->pluck('num', 'days');

        $time = collect();
        $calendar->forEach(fn(Carbon $item) => $time->put($item->toDateString(), 0));

        $result = [
            'time'              => $time->keys()->toArray(),
            'listen_user_count' => $time->merge($listerUserCount)->values()->toArray(),
            'listen_count'      => $time->merge($listerCount)->values()->toArray(),
            'like_count'        => $time->merge($likeCount)->values()->toArray(),
            'submit_count'      => $time->merge($submitCount)->values()->toArray(),
        ];

        if ($request->get('fetchType') === 'excel') {
            $fileName   = Str::random(32) . '.xlsx';
            $excel      = new Excel(['path' => storage_path('excels')]);
            $fileObject = $excel->constMemory($fileName, NULL, false);
            $format     = new Format($fileObject->getHandle());

            $headStyle = $format->align(Format::FORMAT_ALIGN_CENTER, Format::FORMAT_ALIGN_VERTICAL_CENTER)->background(0XF2F2F2)->bold()->toResource();


            $row = $fileObject
                ->header(['日期', '试听用户', '试听次数', '收藏次数', '提交作品数'])
                ->setRow('A1', 22, $headStyle)
                ->setColumn('A:E', 24);

            $fileObject->data([
                [
                    sprintf('%s~%s', Arr::first($result['time']), Arr::last($result['time'])),
                    $listerUserCount->sum(),
                    $listerCount->sum(),
                    $likeCount->sum(),
                    $submitCount->sum(),
                ],
                ...Arr::map($result['time'], static fn($val, $key) => [
                    $val,
                    Arr::get($result['listen_user_count'], $key, 0),
                    Arr::get($result['listen_count'], $key, 0),
                    Arr::get($result['like_count'], $key, 0),
                    Arr::get($result['submit_count'], $key, 0),
                ])
            ]);


            return response()->download($row->output(), $fileName)->deleteFileAfterSend();
        }


        return $this->successWithData($result);
    }
}