<?php

namespace App\Http\Controllers;

use App\MeasuringMachine;
use App\OrderPackage;
use Illuminate\Http\Request;
require_once '../app/library/baidu-api-speech/AipSpeech.php';
class MeasureMonitorController extends Controller
{

    /**
     * Display a listing of the resource.
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $measuringMachines=MeasuringMachine::query()->select('id','name','code','status')->get();
        $laravelEchoPrefix = config('database.redis.options.prefix');
        return view('package.measureMonitor.index',compact('laravelEchoPrefix','measuringMachines'));
    }

    public function data(Request $request){
        $measuring_machine_id=$request->input('id');
        if ($measuring_machine_id){
            $package=OrderPackage::with(['order'=>function($query){
                $query->with('owner','logistic');
            },'paperBox','measuringMachine'])->where('measuring_machine_id',$measuring_machine_id)->orderByDesc('weighed_at')->first();
            if (!$package){
                $measuringMachine=MeasuringMachine::query()->where('id',$measuring_machine_id)->first();
                $package=new OrderPackage();
                if ($measuringMachine)$package->measuringMachine=$measuringMachine;
            }
            return $package;
        }
        return '';
    }


    public function speech(Request $request){
        $logistic=$request->input('logistic');
        if (!$logistic)$logistic='空';
        if (file_exists("storage/".$logistic.'.mp3')){
            return "/storage/".$logistic.'.mp3';
        }
        $client=new \AipSpeech(config('api.baidu.speech.APP_ID'),config('api.baidu.speech.API_KEY'),config('api.baidu.speech.SECRET_KEY'));
        $client->setConnectionTimeoutInMillis('180000');
        $client->setSocketTimeoutInMillis('180000');

        $result = $client->synthesis($logistic, 'zh', 1, array(
            'vol' => 15,
        ));
        // 识别正确返回语音二进制 错误则返回json 参照下面错误码
        if(!is_array($result)){
            file_put_contents('storage/'.$logistic.'.mp3', $result);
        }
        return "/storage/".$logistic.'.mp3';
    }
}
