<?php

namespace Modules\Video\Services;

use Illuminate\Support\Facades\DB;
use Modules\Common\Errors\Errors;
use Modules\Common\Exceptions\CommonBusinessException;

class VideoService
{
    public static function updateVideoChargeInfo($video, $userContext)
    {
        if ($userContext['loginUserRoles']->contains('administrator')) {
            $video->charge_sequence = $video->d_charge_sequence;
            $video->charge_coin = $video->d_charge_coin;
            return;
        }
        if ($userContext['loginUserRoles']->contains('company')) {
            if ($userContext['loginUser']->id == $userContext['operateUser']->id) {
                $video->charge_sequence = $video->d_charge_sequence;
                $video->charge_coin = $video->d_charge_coin;
                return;
            } else {
                $videoUserConfig = self::getVideoUserConfig($userContext['operateUser']->id, $video->id);
                $video->charge_sequence = $videoUserConfig->charge_sequence ?? $video->d_charge_sequence;
                $video->charge_coin = $videoUserConfig->charge_coin ?? $video->d_charge_coin;
                return;
            }
        }
        if ($userContext['loginUserRoles']->contains('optimizer')) {
            $videoUserConfig = self::getVideoUserConfig($userContext['loginUser']->id, $video->id);
            $video->charge_sequence = $videoUserConfig->charge_sequence ?? $video->d_charge_sequence;
            $video->charge_coin = $videoUserConfig->charge_coin ?? $video->d_charge_coin;
            return;
        }
    }

    private static function getVideoUserConfig($uid, $videoId)
    {
        return DB::table('video_user_config')
            ->where(['is_enabled' => 1, 'uid' => $uid, 'video_id' => $videoId])->first();

    }

    /**
     * 通过主键查询短剧信息,没有找到抛出异常
     * @param $videoId
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Query\Builder|object|null
     */
    public static function getVideoByIdOrException($videoId)
    {
        $video = DB::table('videos')
            ->where(['id' => $videoId])
            ->first();
        if (!$video) {
            CommonBusinessException::throwError(Errors::VIDEO_NOT_EXISTS);
        }
        return $video;
    }
}
