<?php

namespace App\Http\Controllers\api\thirdPart\flux;

use App\Http\Controllers\Controller;
use App\OracleDocOrderPackingSummary;
use App\OracleDOCWaveDetails;
use App\OracleDOCWaveHeader;
use App\OracleIdxAsrsReceive;
use App\OrderPackage;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PackageController extends Controller
{

    public function new_(Request $request)
    {
        return response()->json(['response'=>['flag'=>'Y','code'=>'0000','message'=>'正确接收']])
            ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    protected function validatorForNew(array $data)
    {
        return Validator::make($data, [
            'request.TASKID' => ['required', 'string', 'max:191'],
            'request.Orderno' => ['nullable', 'string', 'max:191'],
            'request.palletid' => ['required', 'string', 'max:191'],
            'request.SOReference5' => ['required', 'string', 'max:191'],
            'request.Customer' => ['nullable', 'string', 'max:191'],
            'request.Consigneename' => ['nullable', 'string', 'max:191'],
            'request.CarrierID' => ['nullable', 'string', 'max:191'],
            'request.USERDEFINE1' => ['nullable', 'string', 'max:191'],
            'request.USERDEFINE2' => ['nullable', 'string', 'max:191'],
            'request.USERDEFINE3' => ['nullable', 'string', 'max:191'],
        ],[],[
            'request.TASKID' => 'taskid',
            'request.Orderno' => 'orderno',
            'request.palletid' => 'palletid',
            'request.SOReference5' => 'soreference5',
            'request.Customer' => 'custmoer',
            'request.Consigneename' => 'consigmeename',
            'request.CarrierID' => 'carrierid',
            'request.USERDEFINE1' => 'userdefine1',
            'request.USERDEFINE2' => 'userdefine2',
            'request.USERDEFINE3' => 'userdefine3',
        ]);
    }
//    /**
//     * 完成的包裹称量发送给WMS
//     */
//    public function accomplishToWMS(Package $package)
//    {
//        try{
////            OracleDOCOrderDetail::where('SOREFERENCE5',$package->logistic_number)->update(['grossweight'=>'Y']);
////            return ['result'=>$success];
////            return ['result'=>true];
//            //对WMS接口请求不需要了，直接写其数据库
//            $json=["request"=>['TASKID'=>$package->WMSReflectPackage_name,
//                'SOReference5'=>$package->logistic_number,
//                'Weigh'=>$package->weight,
//                'Addwho'=>'',
//                'Addtime'=>Carbon::now(),
//                'Package'=>$package->paperBox_name,
//                'USERDEFINE1'=>$package->batch_number,
//                'USERDEFINE2'=>$package->batch_rule,
//                'USERDEFINE3'=>'OK',
//            ]];
//            $json=json_encode($json);
//            $url=url(config('api.flux.package.new'));
//            $response = Zttp::post($url, json_decode($json));
//            app('LogService')->log(__METHOD__,'Sign'.__FUNCTION__,json_encode($response->json()),null);
//            $response=$response->json();
//            $noIssues=true;
//            if(!$response||!isset($response['response'])||!$response['response']['flag']=='Y'){
//                $noIssues=false;
//            }
//            if($noIssues&&$response['response']['flag']=='Y'){
//                app('LogService')->log(__METHOD__,'SUCCESS_'.__FUNCTION__,json_encode($json).'| response: '.json_encode($response),null);
//                return ['result'=>'success'];
//            }
//            app('LogService')->log(__METHOD__,'ERROR_'.__FUNCTION__,json_encode($json).'| response: '.json_encode($response),null);
//            return ['result'=>'false'];
//        }catch (\Exception $exception){
//            Controller::logS(__METHOD__,'Exception_'.__FUNCTION__,'请求异常：'.$exception->getMessage(),null);
//            return ['result'=>'false'];
//        }
//    }
    public function accomplishToWMS(OrderPackage $package)
    {
        try{
            $idxAsrsReceive=OracleIdxAsrsReceive::where('userdefine1',$package['logistic_number'])->first();
            if(!$idxAsrsReceive){
                OracleIdxAsrsReceive::create(['grouptaskid'=>$package['logistic_number'],'grouptasksequence'=>1,'userdefine1'=>$package['logistic_number'],'userdefine2'=>$package['weight'],'addwho'=>'WAS','addtime'=>Carbon::now()]);
            }
            $docOrderPackingSummary=OracleDocOrderPackingSummary::where('traceid',$package['logistic_number'])->first();
            if(!$docOrderPackingSummary){
                OracleDocOrderPackingSummary::create(['traceid'=>$package['logistic_number'],'orderno'=>$package['oracleInfo']['orderno'],'grossweight'=>$package['weight'],'addwho'=>'WAS','addtime'=>Carbon::now(),'editwho'=>'WAS','edittime'=>Carbon::now()]);
            }
            app('LogService')->log(__METHOD__,'SUCCESS_'.__FUNCTION__,"称重写入WMS成功：".json_encode($package),null);
            return ['result'=>'success'];
        }catch (\Exception $exception){
            Controller::logS(__METHOD__,'Exception_'.__FUNCTION__,'称重写入WMS请求异常：'.$exception->getMessage(),null);
            return ['result'=>'false'];
        }
    }
    public function markWMSOnBatch($batchNumber,$weight){
        $batchNumber = strtoupper($batchNumber);
        $docWaveHeader=OracleDOCWaveHeader::query()->where('waveno',$batchNumber)->first();
        if(!$docWaveHeader){
            {return ['result'=>false,'message'=>'波次不存在'];}
        }
        if(OracleDOCWaveDetails::unpackedOrders($batchNumber)->isNotEmpty())
            {return ['result'=>false,'message'=>'有未装箱或完成的订单在该波次，不能批量记录重量'];}

        OracleDOCWaveHeader::query()->where('waveno',$batchNumber)->update(['userdefine3'=>'Y']);
        OracleIdxAsrsReceive::saveOrUpdateWeightByBatch($batchNumber,$weight);
        OracleDocOrderPackingSummary::saveOrUpdateWeightByBatch($batchNumber,$weight);

        Controller::logS(__METHOD__,'SUCCESS_'.__FUNCTION__,'标记WMS波次：'.$batchNumber.',userdefine3="Y"',auth()->user()['id']);
        return ['result'=>true];
    }


}
