MusicianSongService.php 11 KB
<?php

namespace App\Services;


use App\Helper\CosHelper;
use App\Helper\Response;
use App\Models\Legal\Contract;
use App\Models\Legal\Song;
use App\Models\Legal\SongsIp;
use App\Models\Legal\SongsIpExts;
use App\Models\Legal\SongStakeholder;
use App\Models\Legal\StakeholderSongCollate;
use App\Models\Musician\AppUserVerified;
use Carbon\Carbon;

/**
 * Class MusicianSongService
 * @package App\Services
 */
class MusicianSongService extends Service
{
    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function songRights()
    {
        $song_ids  =  array_filter(array_unique(SongStakeholder::query()->identify()->pluck('song_id')->toArray()));
        if (empty($song_ids)) return Response::success();

        $res    =   Song::query()->with(['contractDetail'])->whereIn('id', $song_ids)->select(['id', 'custom_id'])->get()->toArray();
        $data   =   [];

        foreach ($res as $item) {
            if (in_array($item['custom_id'], $this->request->custom_ids) && !empty($item['contract_detail'])) {

                $role = [];

                if ($clause_res = array_column($item['contract_detail'], 'clause')) {
                    foreach ($clause_res as $clause_res_item) {
                        if($clause = json_decode($clause_res_item)) {
                            foreach ($clause as $clause_item) {
                                if (in_array($clause_item->stakeholder_id, $this->request->get('stakeholder_ids'))) {
                                    $role = array_merge($role, Contract::transformRole($clause_item->right_type));
                                }
                            }
                        }
                    }
                }

                $data[$item['custom_id']] = $role;
            }
        }

        return Response::success($data);
    }

    /**
     * 授权发行歌曲指数统计
     * @return \Illuminate\Http\JsonResponse
     */
    public function releaseSongCnt()
    {
        $cnt = [
            'favCnt'            =>  0.00,   //收藏指数 - 月
            'playCnt'           =>  0.00,   //播放指数 - 月
            'downloadCnt'       =>  0.00,   //下载指数 - 月
            'favCnt_week'       =>  0.00,   //收藏指数 - 周
            'playCnt_week'      =>  0.00,   //播放指数 - 周
            'downloadCnt_week'  =>  0.00,   //下载指数 - 周
            'favCnt_years'      =>  0.00,   //收藏指数 - 年
            'playCnt_years'     =>  0.00,   //播放指数 - 年
            'downloadCnt_years' =>  0.00    //下载指数 - 年
        ];

        $song_ids  =  array_filter(array_unique(SongStakeholder::query()->identify()->pluck('song_id')->toArray()));
        if (empty($song_ids)) return Response::success($cnt);

        $res = SongsIp::query()->with('songsIpExt:song_ip_id,favCnt,playCnt,downloadCnt,favCnt_week,playCnt_week,downloadCnt_week,favCnt_years,playCnt_years,downloadCnt_years')
                ->join('songs as s', 'songs_ip.song_id', '=', 's.id')
                ->where('auth_channel', 1)->whereIn('s.id', $song_ids)->select(['s.id as sid', 'songs_ip.id as id', 'songs_ip.song_id'])->get();

        foreach ($res as $item) {
            if (empty($item->songsIpExt)) continue;

            $cnt['favCnt']              = bcadd($cnt['favCnt'],             $item->songsIpExt->favCnt,        2);
            $cnt['playCnt']             = bcadd($cnt['playCnt'],            $item->songsIpExt->playCnt,       2);
            $cnt['downloadCnt']         = bcadd($cnt['downloadCnt'],        $item->songsIpExt->downloadCnt,   2);
            $cnt['favCnt_week']         = bcadd($cnt['favCnt_week'],        $item->songsIpExt->favCnt_week,   2);
            $cnt['playCnt_week']        = bcadd($cnt['playCnt_week'],       $item->songsIpExt->playCnt_week,  2);
            $cnt['downloadCnt_week']    = bcadd($cnt['downloadCnt_week'],   $item->songsIpExt->downloadCnt_week, 2);
            $cnt['favCnt_years']        = bcadd($cnt['favCnt_years'],       $item->songsIpExt->favCnt_years,  2);
            $cnt['playCnt_years']       = bcadd($cnt['playCnt_years'],      $item->songsIpExt->playCnt_years, 2);
            $cnt['downloadCnt_years']   = bcadd($cnt['downloadCnt_years'],  $item->songsIpExt->downloadCnt_years, 2);
        }

        return Response::success($cnt);
    }


    /**
     * 授权发行歌曲
     * @return \Illuminate\Http\JsonResponse
     */
    public function releaseSong()
    {
        $song_ids  =  array_filter(array_unique(SongStakeholder::query()->identify()->pluck('song_id')->toArray()));

        if (empty($song_ids)) return Response::success();

        $song_table     =   Song::table();
        $songip_table   =   SongsIp::table();

        $res =  Song::query()->join($songip_table, "{$song_table}.id", '=', "{$songip_table}.song_id")
                    ->with(['contractDetail', 'coverResource'])->whereIn("{$songip_table}.song_id", $song_ids)->whereNull("{$songip_table}.deleted_at")
                    ->select(["{$song_table}.id", "{$songip_table}.id as sp_id", 'online_time', 'publish_song'])
                    ->groupBy(["song_id"])->paginate($this->pageSize);

        $sp_exts = [];
        if ($sp_ids = array_column($res->items(), 'sp_id')) {
            $sp_exts = SongsIpExts::query()->whereIn('song_ip_id', $sp_ids)->get()->keyBy('song_ip_id');
        }

        foreach ($res as &$item) {

            list($name, $singer) = explode('|', $item->publish_song);

            $item->setAttribute('name', $name);
            $item->setAttribute('singer', $singer);
            $item->setAttribute('cover', empty($item->coverResource) ? '' : env('COS_URL').$item->coverResource->url);
            $item->setAttribute('ext', $sp_exts[$item->sp_id] ?? null);
            $item->setAttribute('online_time', $item->online_time);

            $tmp = $item->toArray();
            if (empty($tmp['contract_detail'])) {
                $item->setAttribute('role', []);
                unset($item->contractDetail, $item->publish_song, $item->coverResource);
                continue;
            }

            $role = [];
            if ($clause_res = array_column($tmp['contract_detail'], 'clause')) {
                foreach ($clause_res as $clause) {
                    if ($clause = json_decode($clause)){
                        foreach ($clause as $clause_item) {
                            if (in_array($clause_item->stakeholder_id, $this->request->get('stakeholder_ids'))) {
                                $role = array_merge($role, Contract::transformRole($clause_item->right_type));
                            }
                        }
                    }
                }
            }
            $item->setAttribute('role', array_values(array_unique($role)));
            unset($item->contractDetail, $item->publish_song, $item->coverResource);
        }

        return Response::success($res);
    }

    /**
     * 授权发行歌曲详情
     * @param $song_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function songDetail($song_id)
    {
        //1. 发行记录
        $res = SongsIp::query()->where('song_id', $song_id)->groupBy(['auth_channel'])
                                    ->select(['song', 'auth_channel', 'online_time'])
                                    ->orderBy('online_time')->get();

        $release = [];
        foreach ($res as $item) {
            if (!isset($release[$item->online_time])) {
                $release[$item->online_time] = ['online_time'=>$item->online_time];
            }
            $release[$item->online_time]['auth_channel'][] = $item->auth_channel;
        }

        //2. 计算发行天数
        $release_day = '';
        if ($item = $res->first()) {
            $release_day = Carbon::now()->diffInDays($item->online_time);
        }

        //3. 权益人and歌曲累计收益
        $income = StakeholderSongCollate::query()->identify()->where('song_id', $song_id)
                                                ->sum('real_share_amount');

        return Response::success([
            'release' => array_values($release),
            'release_day' => $release_day,
            'income'  => $income,
        ]);

    }

    /**
     * 权益人歌曲权益
     * @param $song_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function right($song_id)
    {
        $client = new CosHelper();

        $res = SongStakeholder::query()->where('song_id', $song_id)->identify()
                                ->with(['contract:id,cooperation_type,date_starting,date_ending,district_id,is_exclusive', 'contract.stakeholderContract', 'contract.filesNew:id,key,link_id'])
                                ->get()->toArray();

        $contracts = [];

        foreach ($res as $k=>$item) {

            if (empty($item['contract'])) continue;

            $files = [];

            if (!empty($item['contract']['files_new'])) {
                $files = array_column($item['contract']['files_new'], 'key');
            }

            foreach ($files as &$file) {
                $file = $client->getPreviewUrl($file);
            }

            $right = $role = $rights = [];
            if (!empty($item['contract']['stakeholder_contract'])) {
                foreach ($item['contract']['stakeholder_contract'] as $stakeholder_contract) {
                    if (in_array($stakeholder_contract['stakeholder_id'], $this->request->get('stakeholder_ids'))) {
                        $right[] = $stakeholder_contract;
                        $role = array_merge($role, Contract::transformRole($stakeholder_contract['right_type']));

                        //新数据
                        $rights[] = [
                            'role'  =>  Contract::transformRole($stakeholder_contract['right_type']),
                            'right' =>  Contract::getModel($item['contract']['cooperation_type'], [$stakeholder_contract]),
                        ];
                    }
                }
            }

            $contracts[$k] = [
                'contract_id'       =>  $item['contract_id'],
                'files'             =>  $files,
                'cooperation_type'  =>  Contract::getCooperation($item['contract']['cooperation_type']),
                'right'             =>  Contract::getModel($item['contract']['cooperation_type'], $right),
                'role'              =>  array_unique($role),
                'date_starting'     =>  date('Y/m/d', strtotime($item['contract']['date_starting'])),
                'date_ending'       =>  is_null($item['contract']['date_ending']) ? '永久' : date('Y/m/d', strtotime($item['contract']['date_ending'])),
                'limit'             =>  is_null($item['contract']['date_ending']) ? '永久' : data_diff($item['contract']['date_starting'], $item['contract']['date_ending']),
                'district'          =>  Contract::getDistrict($item['contract']['district_id']),
                'exclusive'         =>  Contract::isExclusive($item['contract']['is_exclusive']),
                'rights'            =>  $rights,
            ];
        }

        return Response::success(array_values($contracts));
    }
}