<?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\User\Http\Controllers\UserTrait;
use Modules\Video\Services\VideoService;

class VideoController extends CatchController
{
    use ValidatesRequests;
    use UserTrait;

    /**
     * 短剧列表
     * @param Request $request
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function list(Request $request) {

        $videoName = $request->input('videoName');
        $updateType = $request->input('updateType');
        $categoryId = $request->input('categoryId');
        $videoId = $request->input('videoId');
        $shelfType = $request->input('shelfType');
        $wechatPass = $request->input('wechatPass');
        if($this->listUserRoles()->intersect(['company', 'optimizer'])->isNotEmpty()) {
            $shelfType = 2;
        }

        $videos = DB::table('videos')
            ->when($videoId, function ($query, $videoId){
                return $query->where('id', $videoId);
            })->when($shelfType, function ($query, $shelfType){
                return $query->where('shelf_type', $shelfType);
            })
            ->when($videoName, function ($query, $videoName){
               return $query->where('name', 'like', '%'. $videoName . '%');
            })->when($updateType, function ($query, $updateType){
                return $query->where('update_type', $updateType);
            })->when($categoryId, function ($query, $categoryId){
                return $query->where('category_id', $categoryId);
            })->when(!is_null($wechatPass), function ($query) use ($wechatPass) {
                return $query->where('wechat_pass', $wechatPass);
            })
            ->orderBy('id', 'desc')
            ->paginate($request->integer('limit', 15));
        $userContext = $this->getUserContext($request->input('operateUserId'));
        $allVideoCategory =  DB::table('video_category')
            ->get()->keyBy('id');
        foreach ($videos as $video) {
            $this->updateVideoInfo($video, $userContext);
            $video->category_str = $this->getCategoryStr($allVideoCategory, $video->category_id);
            $video->shelf_type_str = $video->shelf_type == 1 ? '未上架':'上架';
            $video->update_type_str = $video->update_type == 1 ? '连载中' : '完结';
            $video->cp_share_type_str = ([1 => '分成', 2=>'保底', 3=>'买断'])[$video->cp_share_type] ?? '';
            $video->channel = $allVideoCategory->get($video->category_id)->pid;
            $video->wechat_pass_img = $video->wechat_pass ? config('common.common.logos.1') : '';
        }

        return $videos;
    }

    /**
     * 订阅设置
     * @param Request $request
     * @throws \Illuminate\Validation\ValidationException
     */
    public function setChargeConfig(Request $request) {
        $this->validate($request, [
            'id' => 'required',
            'chargeCoin' => 'required|integer|min:50|max:300',
            'chargeType' => 'required|integer|in:1',
            'chargeSequence' => 'required|integer|min:1|max:30'
        ]);
        $userContext = $this->getUserContext($request->input('operateUserId'));
        if(!(1 == $userContext['loginUser']->id || $userContext['loginUserRoles']->contains('administrator') ||
            $userContext['loginUserRoles']->contains('optimizer'))) {
            CommonBusinessException::throwError(Errors::NO_OPERATE_PERMISSION);
        }
        $now = date('Y-m-d H:i:s');
        if($userContext['loginUserRoles']->contains('administrator') || 1 == $userContext['loginUser']->id) {
            DB::table('videos')
                ->where('id', $request->input('id'))
                ->update([
                    'd_charge_type' => $request->input('chargeType'),
                    'd_charge_sequence' => $request->input('chargeSequence'),
                    'd_charge_coin' => $request->input('chargeCoin'),
                    'updated_at' => $now
                ]);
        } else {
            DB::table('video_user_config')
                ->where([
                    'video_id' => $request->input('id'),
                    'uid' => $userContext['loginUser']->id
                ])->update(['is_enabled' => 0, 'updated_at' => $now]);
            DB::table('video_user_config')
                ->insert([
                    'uid' => $userContext['loginUser']->id,
                    'video_id' => $request->input('id'),
                    'charge_type' => $request->input('chargeType'),
                    'charge_sequence' => $request->input('chargeSequence'),
                    'charge_coin' => $request->input('chargeCoin'),
                    'updated_at' => $now,
                    'created_at' => $now
                ]);
        }

    }

    /**
     * 添加短剧
     * @param Request $request
     * @return int
     * @throws \Illuminate\Validation\ValidationException
     */
    public function add(Request $request) {
        $this->validate($request, [
            'name' => 'required|string|max:128',
            'total_episode_num' => 'required|integer',
            'update_type' => 'required|integer|in:1,2',
            'category_id' => 'required|integer',
            'shelf_type' => 'required|integer|in:1,2',
            'd_charge_sequence' => 'required|integer|min:1',
            'd_charge_coin' => 'required|integer|min:1',
            'cp_name' => 'required|string',
            'cp_share_type' => 'required|integer|in:1,2,3',
            'cover_image' => 'required|string',
            'note' => 'required',
        ]);
        $data = $request->all();
        $now = date('Y-m-d H:i:s');
        $data['created_at'] = $data['updated_at'] = $now;
        if(2 == $request->integer('shelf_type')) {
            $data['shelf_at'] = $now;
        } else {
            $data['shelf_at'] = null;
        }
        DB::table('videos')
            ->insert($data);
        return 1;
    }

    /**
     * 更新短剧信息
     * @param Request $request
     * @return int
     * @throws \Illuminate\Validation\ValidationException
     */
    public function update(Request $request) {
        $this->validate($request, [
            'id' => 'required',
            'name' => 'required|string|max:128',
            'total_episode_num' => 'required|integer',
            'update_type' => 'required|integer|in:1,2',
            'category_id' => 'required|integer',
            'shelf_type' => 'required|integer|in:1,2',
            'd_charge_sequence' => 'required|integer|min:1',
            'd_charge_coin' => 'required|integer|min:1',
            'cp_name' => 'required|string',
            'cp_share_type' => 'required|integer|in:1,2,3',
            'cover_image' => 'required|string',
            'note' => 'required',
        ]);
        $id = $request->input('id');
        $data = $request->except('id', 'shelf_at');
        $data['updated_at'] = date('Y-m-d H:i:s');
        $video = VideoService::getVideoByIdOrException($request->input('id'));
        if(2 == $request->integer('shelf_type') && 1 == $video->shelf_type) {
            $data['shelf_at'] = $data['updated_at'];
        }
        DB::table('videos')
            ->where('id', $id)
            ->update($data);
        return 1;
    }



    private function updateVideoInfo($video, $userContext) {
        VideoService::updateVideoChargeInfo($video, $userContext);
    }



    private function getCategoryStr($allCategory,$categoryId) {
        $category = $allCategory->get($categoryId);
        if(!$category) {
            return '';
        } else {
            $firstLevelStr = $allCategory->get($category->pid)->category_name ?? '';
            $secondLevelStr = $category->category_name;
            return trim(join('/', compact('firstLevelStr','secondLevelStr')), '/');
        }
    }
}
