<?php

namespace App\Jobs;

use App\Events\AuditMediaDeal;
use App\Models\Media\MediaSecure;
use App\Services\Vendor\Miniprogram\Security;
use App\Services\Vendor\Xunfei\Voice2Text;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class XunFeiVoiceJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;


    protected $media;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($media)
    {
        $this->media = $media;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $media = $this->media;

        $taskId = $media->task_id;
        $XunFeiService = new Voice2Text();
        $data = $XunFeiService->getProgress($taskId);
        $data = json_decode($data['data'], true);
        if ($data['status'] !== 9) {
            $this->release(60);
        }

        // 讯飞语音转译
        $data = $XunFeiService->getResult($taskId);
        if ($data['ok'] === 0) {
            $result = json_decode($data['data'], true);
            $media->machine_result = $result;
            $translate = implode('', array_column($result, 'onebest'));
            $media->translate = sprintf('【转译结果】%s', $translate);

            if (!$translate) {
                $media->audit_suggestion = MediaSecure::MACHINE_SUGGESTION_BLOCK;
                $media->result = MediaSecure::MANUAL_SUGGESTION_BLOCK;
                $media->save();
                event(new AuditMediaDeal($media));
                return;
            } else {
                // 文字检测
                $security = new Security();
                $result = $security->msgSecCheck($translate);
                if ($result['errcode']) {
                    $media->audit_suggestion = MediaSecure::MACHINE_SUGGESTION_BLOCK;
                    $media->result = MediaSecure::MANUAL_SUGGESTION_BLOCK;
                    $media->save();
                    event(new AuditMediaDeal($media));
                } else {
                    $media->audit_suggestion = 1;
                    $media->save();
                }
            }
        } else {
            $media->translate = sprintf('【进行中】%s', $data['failed']);
            $media->audit_suggestion = 0;
            $media->save();
        }
    }
}
