<?php

namespace Modules\Video\Http\Controllers;

use App\Jobs\Video\WechatCheck;
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\Manage\Services\WechatMiniprogramService;

/**
 * 微信提审
 */
class WechatCheckController extends CatchController
{
    use ValidatesRequests;
    /**
     * 添加提审
     * @param Request $request
     */
    public function add(Request $request) {
        $this->validate($request, [
            'video_id'=>'required',
            'producer' => 'required|string|max:256',
            'playwright' => 'required|string|max:256',
            'production_license_img' => 'required|url',
            'authorized_img' => 'required|url',
            'registration_number' => 'required'
        ]);

        $data = $request->all();
        $appid = WechatMiniprogramService::getDuanjuCheckAppid();
        $data['created_at'] = $data['updated_at'] = date('Y-m-d H:i:s');
        $data['appid'] = $appid;
        DB::table('video_wechat_check')
            ->insert($data);

        return 'ok';
    }

    /**
     * 修改
     * @param Request $request
     */
    public function update(Request $request) {
        $this->validate($request, [
            'id'=>'required',
            'producer' => 'required|string|max:256',
            'playwright' => 'required|string|max:256',
            'production_license_img' => 'required|url',
            'authorized_img' => 'required|url',
            'registration_number' => 'required'
        ]);

        $data = $request->only(['producer', 'playwright', 'production_license_img', 'authorized_img', 'registration_number']);
        $data['updated_at'] = date('Y-m-d H:i:s');
        DB::table('video_wechat_check')
            ->where('id', $request->input('id'))
            ->where('is_enabled', 1)
            ->whereIn('status', [0,4])
            ->update($data);
        return 'ok';
    }

    /**
     * 删除
     * @param Request $request
     */
    public function delete(Request $request) {
        $this->validate($request, ['id' => 'required']);
        DB::table('video_wechat_check')
            ->whereIn('status', [0,4])
            ->where([
                'id' => $request->input('id'),
                'is_enabled' => 1,
            ])->update([
                'is_enabled' => 0,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

        return 'ok';
    }
    /**
     * 提审记录列表
     * @param Request $request
     */
    public function list(Request $request) {
        $videoId = $request->input('video_id');
        $producer = $request->input('producer');
        $playwright = $request->input('playwright');
        $status = $request->input('status','0');

        $result =  DB::table('video_wechat_check as check')
            ->join('videos', 'videos.id', 'check.video_id')
            ->whereIn('check.status', explode(',', $status))
            ->where([
                'check.is_enabled' => 1,
            ])->when($videoId, function ($query, $videoId) {
                return $query->where('check.video_id', $videoId);
            })->when($producer, function ($query, $producer){
                return $query->where('check.producer', 'like', '%'. $producer. '%');
            })->when($playwright, function ($query, $playwright){
                return $query->where('check.playwright', 'like', '%'. $playwright. '%');
            })->select('check.id', 'videos.name', 'videos.note', 'videos.total_episode_num',
                'videos.cover_image','check.status','check.producer',
            'check.playwright', 'check.production_license_img', 'check.authorized_img', 'check.apply_at',
            'check.check_at', 'check.check_reason', 'check.registration_number', 'check.video_id')
            ->orderBy('check.id','desc')
            ->paginate($request->input('limit', 20));
        $statusMap = config('video.wechat.dramaCheckStatus');
        foreach ($result as $item) {
            $item->status_str = $statusMap[$item->status] ?? '';
        }

        return $result;
    }

    /**
     * 微信提审
     * @param Request $request
     */
    public function check(Request $request) {
        $this->validate($request, [
            'ids' => 'required|array'
        ]);
        $ids = $request->input('ids');
        $now = date('Y-m-d H:i:s');

        foreach ($ids as $id) {
            $record = DB::table('video_wechat_check as check')
                ->join('videos', 'videos.id', 'check.video_id')
                ->where(['check.is_enabled' => 1, 'check.id' => $id])
                ->select('check.video_id', 'videos.total_episode_num', 'videos.name')
                ->first();
            if(!$record) {
                CommonBusinessException::throwError(Errors::WECHAT_CHECK_RECORD_NOT_EXISTS);
            }

            $medias = DB::table('video_series_wechat_check')
                ->where('video_id', $record->video_id)
                ->where(['sync_status' => 4, 'is_enabled' => 1])
                ->where('media_id', '<>', 0)
                ->get();
            if($medias->count() != $record->total_episode_num) {
                CommonBusinessException::throwError([Errors::SYNC_WECHAT_NOT_OK[0],
                    sprintf('%s,同步到微信:%s集,总集数:%s集', $record->name, $medias->count(), $record->total_episode_num)]);
            }
        }

        DB::table('video_wechat_check')
            ->whereIn('id', $ids)
            ->whereIn('status', [0, 4])
            ->update([
                'status' => 5,
                'updated_at' => $now,
                'apply_at' => $now,
            ]);
        $traceContext = getTraceContext();
        foreach ($ids as  $id) {
            WechatCheck::dispatch([
                'id' => $id,
                'traceInfo' => $traceContext->getTraceInfo()
            ])->onQueue('{duanju_manage}.video.wechatCheck')->onConnection('queue-redis');
        }

        return 'ok';
    }
}
