<?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 Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Response;
use Modules\Common\Errors\Errors;
use Modules\Common\Exceptions\CommonBusinessException;
use Modules\Manage\Services\WechatMiniprogramService;
use Modules\Video\Services\WechatCheckSyncService;

class VideoSeriesWechatCheckController extends CatchController
{
    use ValidatesRequests;
    /**
     * 剧集同步到微信
     * @param Request $request
     */
    public function syncWechat(Request $request) {
        $this->validate($request, [
            'series_ids' => 'required|array'
        ]);
        $series_ids = $request->input('series_ids');
        $series = DB::table('video_series')
            ->join('videos', 'video_series.video_id', 'videos.id')
            ->whereIn('video_series.id', $series_ids)
            ->where(['video_series.is_enabled' => 1])
            ->select('video_series.video_id', 'videos.name', 'video_series.series_sequence',
                'video_series.id', 'video_series.video_key')
            ->get();
        if(collect($series_ids)->count() != $series->count()) {
            CommonBusinessException::throwError(Errors::VIDEO_SERIES_NOT_EXISTS);
        }
        $appid = WechatMiniprogramService::getDuanjuCheckAppid();
        $accessToken = WechatMiniprogramService::getDuanjuCheckAccessToken($appid);
        $now = date('Y-m-d H:i:s');
        foreach ($series as $item) {
            $item->video_url = config('common.qiniu.publicVideoLinkDomain') . DIRECTORY_SEPARATOR . $item->video_key;
            $item->media_name = sprintf('%s - 第%s集', $item->name, $item->series_sequence);
            $parsedContent = WechatCheckSyncService::pullupload($item, $accessToken);
            if(false === $parsedContent || (0 != ($parsedContent['errcode'] ?? 0))) {
                CommonBusinessException::throwError(Errors::SYNC_WECHAT_NOT_OK);
            }
            $taskId = $parsedContent['task_id'];
            DB::table('video_series_wechat_check')
                ->where(['series_id' => $item->id, 'is_enabled' => 1])
                ->update(['is_enabled' => 0, 'updated_at' => $now]);
            DB::table('video_series_wechat_check')
                ->insert([
                    'series_id' => $item->id,
                    'sync_task_id' => $taskId, 'appid' => $appid,
                    'created_at' => $now, 'updated_at' => $now,
                    'video_id' => $item->video_id,
                ]);
        }

        return 'ok';
    }

    /**
     * 获取微信方的剧集播放链接
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function medialink(Request $request) {
        $this->validate($request, [
            'series_id' => 'required'
        ]);

        $seriesId = $request->input('series_id');
        $redisKey = WechatCheckSyncService::getWechatMediaLinkRedisKey($seriesId);
        $link = Redis::get($redisKey);
        if($link) {
            return $link;
        }

        $medialinkInfo = WechatCheckSyncService::getMedialinkInfo($seriesId);
        if(false === $medialinkInfo) {
            CommonBusinessException::throwError(Errors::GET_WECHAT_MEDIA_LINK_ERROR);
        }
        $link = $medialinkInfo['mp4_url'];
        Redis::setex($redisKey, 6000, $link);
        return $link;
    }

    /**
     * 获取审核证据
     * todo:fix
     * @param Request $request
     * @throws \Illuminate\Validation\ValidationException
     */
    public function listEvidence(Request $request) {
        $this->validate($request, [
            'series_id' => 'required'
        ]);
        $info = DB::table('video_series_wechat_check')
            ->where([
                'series_id' => $request->input('series_id'),
                'is_enabled' => 1
            ])->orderBy('id', 'desc')
            ->select('evidence_material_id_list', 'appid')->first();
        if($info) {
            $evidence_material_id_lists = \json_decode($info->evidence_material_id_list, true);
            $accessToken = WechatMiniprogramService::getDuanjuCheckAccessToken($info->appid);
        }
        return 'todo:待完善';
    }

    public function test(Request $request) {
        foreach (['1228789.jpg'] as $i) {
            $path = storage_path(uniqid());
            file_put_contents($path, file_put_contents(app_path($i)));
            return response()->file($path);
        }
    }
}
