<?php

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

use App\Events\WeighedEvent;
use App\Http\Controllers\Controller;
use App\Http\Controllers\LogisticNumberFeatureController;
use App\Jobs\FetchPackageFromOracle;
use App\Jobs\WeightUpdateInstantBill;
use App\MeasuringMachine;
use App\Order;
use App\OrderPackage;
use App\Services\OrderService;
use App\Waybill;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Validator;


class PackageController extends Controller
{
//    public function new_(Request $requestInitial){
//        $request=[];
//        foreach ($requestInitial->all() as $k=>$v){
//            $request[strtolower($k)]=$v;
//        }
//        $reqDate=isset($request['time'])?$request['time']:Carbon::now();
//        $errors=$this->validatorWeight($request)->errors();
//
//        if (count($errors)>0){
//            app('LogService')->log(__METHOD__,'error'.__FUNCTION__,json_encode($request).'||'.json_encode($errors),null);
//            $response=["msg"=>$errors,"code"=>500,"data"=>null];
//            return json_encode($response);
//        }
//
//        $measuringMachine=MeasuringMachine::where('code',$request['id'])->first();
//        if (!$measuringMachine){
//            $measuringMachine=new MeasuringMachine([
//                'name'=>$request['id'],
//                'code'=>$request['id'],
//                'status'=>'在线'
//            ]);
//            $measuringMachine->save();
//            app('LogService')->log(__METHOD__,'weightApi(new measuring machine)'.__FUNCTION__,json_encode($request),null);
//        }else{
//            $measuringMachineStatus=new MeasuringMachine();
//            $measuringMachineStatus->changeStatus($measuringMachine);
//        }
//        MeasuringMachineQueue::dispatch($measuringMachine)->delay(Carbon::now()->addMinutes(30));
//
//        $package=Package::where('logistic_number',$request['barcode'])->first();
//        if (isset($request['length'])&&isset($request['width'])&&isset($request['height'])){
//            $length=$request['length'];
//            $width=$request['width'];
//            $height=$request['height'];
//            $max=($length>=($width>=$height?$width:$height)?$length:($width>=$height?$width:$height));
//            if ($max==$length){
//                $centre=$width>=$height?$width:$height;
//                $min=$width<$height?$width:$height;
//            }elseif ($max==$width){
//                $centre=$length>=$height?$length:$height;
//                $min=$length<$height?$length:$height;
//            }else{
//                $centre=$width>=$length?$width:$length;
//                $min=$width<$length?$width:$length;
//            }
//        }else{
//            $max=0;$centre=0;$min=0;
//        }
//        $apiController=new \App\Http\Controllers\api\thirdPart\flux\PackageController();
//        if ($package){
//            $packageController=new \App\Http\Controllers\PackageController();
//            $package->fetchPaperBox($max,$centre,$min,$package->owner_id);
//            //处理活动波次
//            if ($package->batch_rule&&strstr($package->batch_rule,'组合')){
//                $packageController->syncBatch($package->batch_number,$request['weight'],$max,$centre,$min,$reqDate,$package['paper_box_id']);
//            }else{
//                $package->measuring_machine_id=$measuringMachine->id;
//                $package->weight=$request['weight'];
//                $package->length=$max;
//                $package->width=$centre;
//                $package->height=$min;
//                $package->bulk=$max*$centre*$min;
//                $package->weighed_at=$reqDate;
//                $package->status="未上传";
//                app('LogService')->log(__METHOD__,'Batch_'.__FUNCTION__,json_encode($package),null);
//                $package->save();
//                $result=$apiController->accomplishToWMS($package);
//                if ($result['result']){
//                    if ($package->status=="记录异常")$package->status="已上传异常";
//                    else $package->status="已上传";
//                }else{
//                    $package->status="上传异常";
//                }
//                $package->save();
//            }
//            if ($package->order_code){
//                $waybill=Waybill::where('wms_bill_number',$package->order_code)->where('status','!=','已完结')
//                    ->where('status','!=','无模型')->first();
//                if ($waybill){
//                    $waybill->warehouse_weight_other=$package->weight;
//                    $waybill->warehouse_weight_unit_id_other=1;
//                    $waybill->update();
//                }
//            }
//            event(new WeighedEvent($package));
//            $response=["msg"=>"保存成功",
//                        "code"=>200,
//                        "data"=>true,
//                        "serverMsg"=>null,
//                        "requestor"=>[
//                                "requestor"=>"1",
//                                "eventCode"=>"0",
//                                "reqDate"=>$reqDate,
//                                "resDate"=>Carbon::now()]
//                        ];
//            app('LogService')->log(__METHOD__,'weightApi'.__FUNCTION__,json_encode($request).'|'.json_encode($response),null);
//            return json_encode($response,JSON_UNESCAPED_UNICODE);
//        }
//        if (!$package){
//            $logisticNumber=$request['barcode'];
//            $createPackage=new Package([
//                'logistic_number'=>$logisticNumber,
//                'delivery_number'=>$logisticNumber,
//                'measuring_machine_id'=>$measuringMachine->id,
//                'weight'=>$request['weight'],
//                'length'=>$max,
//                'width'=>$centre,
//                'height'=>$min,
//                'bulk'=>$max*$centre*$min,
//                'weighed_at'=>$reqDate,
//                'status'=>"未下发",
//            ]);
//            $createPackage->fetchAllFromOracle();
//            $createPackage->fetchPaperBox($max, $centre, $min);
//            $result=$apiController->accomplishToWMS($createPackage);
//            if(!$result['result']){
//                app('LogService')->log(__METHOD__,'weightApi'.__FUNCTION__,json_encode($request).'||'.json_encode($createPackage),null);
//                $response=["msg"=>"写入WMS失败!","code"=>500,"data"=>null];
//                return json_encode($response,JSON_UNESCAPED_UNICODE);
//            }
//            if ($createPackage->save()){
//                $measuringMachine->touch();
//                MeasuringMachineQueue::dispatch($measuringMachine)->delay(Carbon::now()->addMinutes(30));
//                MarkPackageExcepted::dispatch($createPackage)->delay(Carbon::now()->addMinutes(1440));
//                event(new WeighedEvent($createPackage));
//                $response=["msg"=>"保存成功",
//                    "code"=>200,
//                    "data"=>true,
//                    "serverMsg"=>null,
//                    "requestor"=>[
//                        "requestor"=>"1",
//                        "eventCode"=>"0",
//                        "reqDate"=>$reqDate,
//                        "resDate"=>Carbon::now()]
//                ];
//                app('LogService')->log(__METHOD__,'weightApi'.__FUNCTION__,json_encode($request).'||'.json_encode($response),null);
//                return json_encode($response,JSON_UNESCAPED_UNICODE);
//            }
//
//            $response=["msg"=>"保存时发生错误（未下发）!","code"=>500,"data"=>null];
//            app('LogService')->log(__METHOD__,'weightApi(ERROR)'.__FUNCTION__,json_encode($request).'||'.json_encode($response),null);
//            return json_encode($response,JSON_UNESCAPED_UNICODE);
//        }
//    }

    public function new_(Request $requestInitial){
        $request=[];
        foreach ($requestInitial->all() as $k=>$v){
            $request[strtolower($k)]=$v;
        }
//        $reqDate=isset($request['time'])?$request['time']:Carbon::now();
        $reqDate=Carbon::now()->format(Carbon::DEFAULT_TO_STRING_FORMAT);
        $errors=$this->validatorWeight($request)->errors();

        if (count($errors)>0){
            app('LogService')->log(__METHOD__,'error'.__FUNCTION__,json_encode($request).'||'.json_encode($errors),null);
            return json_encode(["msg"=>$errors,"code"=>500,"data"=>null]);
        }

        $id = $request['id']??'无ID设备';
        $measuringMachine=MeasuringMachine::query()->firstOrCreate(['code'=> $id]);
        $measuringMachine->turnOn();
        $measuringMachine->turnOffInMinutes(30);

        /** @var OrderPackage $package */
        $package=OrderPackage::query()->where('logistic_number',$request['barcode'])->first();

        $edges=[$request['length']??0,$request['width']??0,$request['height']??0];
        rsort($edges);
        $fluxController=new \App\Http\Controllers\api\thirdPart\flux\PackageController();
        if ($package){
            $package['measuring_machine_id']=$measuringMachine->id;
            $package['weight']=$request['weight'];
            $package['length']=$edges[0];
            $package['width']=$edges[1];
            $package['height']=$edges[2];
            $package['weighed_at']=$reqDate;
            $package->fetchAllFromOracle();
            $package->fetchPaperBox();
            $package['bulk']=$edges[0]*$edges[1]*$edges[2];
            if ($package->isActivityBatch()){//处理活动波次
                app('LogService')->log(__METHOD__,__FUNCTION__,"依波次号同步所有包裹：".json_encode($package),null);
                $package->unifyThisMeasureUnderSameBatch();
                $result=$fluxController->markWMSOnBatch($package['batch_number'], $request['weight']);
                if(!$result['result']){
                    $package->uploaded_to_wms="异常";
                }
            }else{
                app('LogService')->log(__METHOD__,__FUNCTION__,"写入包裹至WMS：".json_encode($package),null);
                try{
                    $result=$fluxController->accomplishToWMS($package);
                    if ($result['result']){
                        $package->uploaded_to_wms="是";
                    }else{
                        $package->uploaded_to_wms="异常";
                    }
                }catch (\Exception $e){
                    $package->uploaded_to_wms="否";
                }
            }
            try{
                $package->save();
                $package->load(['order'=>function($query){
                    $query->with('owner','logistic');
                },'paperBox','measuringMachine']);
                $logisticNumberController = new LogisticNumberFeatureController();
                if (!$package->order){
                    $package->order = new Order();
                    $logistic=$logisticNumberController->getLogisticByFeatures($package->logistic_number);
                    $package->order->logistic = $logistic;
                }else{
                    if(!$package->order->logistic){
                        $logistic=$logisticNumberController->getLogisticByFeatures($package->logistic_number);
                        $package->order->logistic_id = $logistic['id'];
                        $package->order->save();
                    }
                }
            }catch (\Exception $e){
                $response=["msg"=>"称重下发修改时发生错误!".json_encode($e),"code"=>500,"data"=>null];
                app('LogService')->log(__METHOD__,'weightApi(ERROR)'.__FUNCTION__,json_encode($request).'||'.json_encode($response).'||'.json_encode($e),null);
                return json_encode($response,JSON_UNESCAPED_UNICODE);
            }
        }
        if (!$package){
            $logisticNumber=$request['barcode'];
            /** @var $orderService OrderService */
            $orderService = app('OrderService');
            $order = $orderService->logisticNumberFirstOrCreateOrder($logisticNumber);
            if (!$order) {
                $response=["msg"=>"保存时发生错误（未在WMS找到该单）!","code"=>500,"data"=>null];
                return json_encode($response,JSON_UNESCAPED_UNICODE);
            }
            $package=new OrderPackage([
                'order_id' => $order->id,
                'logistic_number'=>$logisticNumber,
                'measuring_machine_id'=>$measuringMachine->id,
                'weight'=>$request['weight'],
                'length'=>$edges[0],
                'width'=>$edges[1],
                'height'=>$edges[2],
                'bulk'=>$edges[0]*$edges[1]*$edges[2],
                'weighed_at'=>$reqDate,
                'status'=>"无",
            ]);
            $package->fetchAllFromOracle();
            $package->fetchPaperBox();
            try{
                $package->save();
                $package->load(['order'=>function($query){
                    $query->with('owner','logistic');
                },'paperBox','measuringMachine']);
                $logisticNumberController = new LogisticNumberFeatureController();
                if (!$package->order){
                    $package->order = new Order();
                    $logistic=$logisticNumberController->getLogisticByFeatures($package->logistic_number);
                    $package->order->logistic = $logistic;
                }else{
                    if(!$package->order->logistic){
                        $logistic=$logisticNumberController->getLogisticByFeatures($package->logistic_number);
                        $package->order->logistic_id = $logistic['id'];
                        $package->order->save();
                    }
                }
            }catch (\Exception $e){
                $response=["msg"=>$e->getMessage(),"code"=>500,"data"=>$e->getTraceAsString()];
                app('LogService')->log(__METHOD__,'weightApi(ERROR)'.__FUNCTION__,json_encode($request).'||'.json_encode($response).'||'.$e->getTraceAsString(),null);
                return json_encode($response,JSON_UNESCAPED_UNICODE);
            }
            $result=$fluxController->accomplishToWMS($package);
            if(!$package['batch_number'])
                FetchPackageFromOracle::dispatch($package)->delay(Carbon::now()->addMinutes(1440));
            if(!$result['result']){
                app('LogService')->log(__METHOD__,'weightApi'.__FUNCTION__,json_encode($request).'||'.json_encode($package),null);
                $response=["msg"=>"写入WMS失败!","code"=>500,"data"=>null];
                return json_encode($response,JSON_UNESCAPED_UNICODE);
            }
        }
        if(!empty($package->order))
            Waybill::setWeightByOrderCode($package->order->code,$package->weight);
        if ($package){
            event(new WeighedEvent($package));
            dispatch(new WeightUpdateInstantBill($package));
        }
        $response=["msg"=>"保存成功",
            "code"=>200,
            "data"=>true,
            "serverMsg"=>null,
            "requestor"=>[
                "requestor"=>"1",
                "eventCode"=>"0",
                "reqDate"=>$reqDate,
                "resDate"=>Carbon::now()]
        ];
        app('LogService')->log(__METHOD__,__FUNCTION__,"下发写入包裹成功：".json_encode($request).'|'.json_encode($response),null);
        return json_encode($response,JSON_UNESCAPED_UNICODE);
    }

    public function validatorWeight(array $request){
        $validator=Validator::make($request,[
            'id'=>['nullable','max:30'],
            'barcode'=>['required','max:191'],
            'weight'=>['required','numeric','min:0'],
            'length'=>['nullable','numeric','min:0'],
            'width'=>['nullable','numeric','min:0'],
            'height'=>['nullable','numeric','min:0'],
        ],[
            'required'=>':attribute 为必填项',
            'max'=>':attribute 字符过多或数值过大',
            'min'=>':attribute 不得为负',
            'numeric'=>':attribute 应为数字',
        ],[]);
        return $validator;
    }

}
