<?php

namespace Modules\Video\Http\Controllers;

use Catch\Base\CatchController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Common\Errors\Errors;
use Modules\Common\Exceptions\CommonBusinessException;
use Modules\Common\Services\Qiniu\QiniuTokenService;
use Modules\User\Http\Controllers\UserTrait;
use Modules\Video\Services\VideoService;

class EpisodeController extends CatchController
{
    use UserTrait;
    use ValidatesRequests;

    public function list(Request $request) {
        $this->validate($request, [
            'video_id' => 'required'
        ]);

        $video = VideoService::getVideoByIdOrException($request->input('video_id'));

        VideoService::updateVideoChargeInfo($video, $this->getUserContext($request->input('operateUserId')));

        $videoSeries = DB::table('video_series')
            ->where([
                'video_id' => $request->integer('video_id'),
                'is_enabled' => 1
            ])->select('series_name', 'series_sequence', 'video_key', 'duration', 'id', 'video_id')
            ->orderBy('series_sequence', 'asc')
            ->paginate($request->integer('limit', 15));
        /**
         * 增加微信审核状态
         */
        $wechatCheckStatus = null;
        if($request->input('need_wechat_status', 0)) {
            $serieIds = $videoSeries->pluck('id');
            $wechatCheckStatus = DB::table('video_series_wechat_check')
                ->whereIn('series_id', $serieIds)
                ->where('is_enabled', 1)
                ->select('series_id', 'check_status')
                ->get()->keyBy('series_id');
        }
        $wechatCheckStatusMap = config('video.wechat.checkStatus');
        foreach ($videoSeries as $series) {
            $series->series_name = sprintf('第%s集', $series->series_sequence);
            $series->is_charge = $series->series_sequence >= $video->charge_sequence;
            $series->duration_str = gmdate('H:i:s', $series->duration);
            $series->public_video_url = config('common.qiniu.publicVideoLinkDomain') . DIRECTORY_SEPARATOR . $series->video_key;
            $series->download_video_url = QiniuTokenService::getPrivateSourceDownloadUrl(config('common.qiniu.sourceVideoLinkDomain') . DIRECTORY_SEPARATOR .
                $series->video_key.'?attname='.urlencode($series->series_name).'.mp4');
            $wechat_check_status = $wechatCheckStatus[$series->id]->check_status ?? 0;
            $series->wechat_check_status = $wechat_check_status;
            $series->wechat_check_status_str = $wechatCheckStatusMap[$wechat_check_status] ?? '';

        }

        return $videoSeries;
    }

    public function downloadList(Request $request) {
        return $this->list($request);
    }

    /**
     * 添加短剧剧集, 允许覆盖已经存在的播放地址
     * @param Request $request
     * @return int
     * @throws \Illuminate\Validation\ValidationException
     */
    public function add(Request $request) {
        $this->validate($request, [
            'video_id' => 'required',
            'videos' => 'required|array|min:1',
            'videos.*.name' => 'required',
            'videos.*.duration' => 'required|integer|min:1',
            'videos.*.key' => 'required',
        ]);
        VideoService::getVideoByIdOrException($request->input('video_id'));
        $videos = $request->input('videos');
        $data = [];
        $now = date('Y-m-d H:i:s');
        foreach ($videos as $item) {
            $sequence = intval(explode('_', $item['name'])[0]);
            if($sequence <=0 ) {
                CommonBusinessException::throwError(Errors::SERIES_NAME_NOT_OK);
            }
            $data[$sequence] = [
                'video_id' => $request->input('video_id'),
                'video_key' => $item['key'],
                'series_name' => $item['name'],
                'series_sequence' => $sequence,
                'duration' => $item['duration'],
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }

        $allSequence = DB::table('video_series')->where(['video_id' => $request->input('video_id')])
            ->select('series_sequence')->get()->pluck('series_sequence');

        foreach ($data as $key=>$item) {
            if($allSequence->contains($key)) {
                DB::table('video_series')->where([
                    'video_id' => $item['video_id'],
                    'series_sequence' => $item['series_sequence']
                ])->update([
                    'video_key' => $item['video_key'], 'series_name' => $item['series_name'],
                    'duration' => $item['duration'], 'updated_at' => $item['updated_at'],
                ]);
            } else {
                DB::table('video_series')->insert($item);
            }
        }

        DB::table('videos')
            ->where(['id' => $request->input('video_id')])
            ->update(['updated_episode_num' => DB::table('video_series')
                ->where(['video_id' => $request->input('video_id')])->count(),'updated_at' => $now]);
        return 1;
    }
}
