<?php

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

use App\Http\Controllers\Controller;
use App\Jobs\FetchPackageFromOracle;
use App\Logistic;
use App\OracleDOCOrderDetail;
use App\OracleDOCOrderHeader;
use App\OracleDocOrderPackingSummary;
use App\OracleDOCWaveDetails;
use App\OracleDOCWaveHeader;
use App\OracleIdxAsrsReceive;
use App\Owner;
use App\Package;
use App\WMSReflectPackage;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Zttp\Zttp;

class PackageController extends Controller
{

    public function new_(Request $request)
    {
//        $requestInputs=$request->all();
//        $this->log(__METHOD__,'request_'.__FUNCTION__,json_encode($requestInputs),null);
//        $errors=$this->validatorForNew($requestInputs)->errors();
//        if(count($errors)>0){
//            $this->log(__METHOD__,'error2_'.__FUNCTION__,json_encode($requestInputs).'||'.json_encode($errors),null);
//            return ['response'=>['flag'=>'W','message'=>'fields wrong, see Errors report please.',
//                'errors'=>$errors]];
//        }
//        $receiveInputs=$requestInputs['request'];
//        $package=Package::where('logistic_number',$receiveInputs['SOReference5'])->first();
//        if (!$receiveInputs['Customer']) {
//            $this->log(__METHOD__, __FUNCTION__, '富勒没有下发货主！快递单号：'.$receiveInputs['SOReference5'] , null);
//        }
//        $owner=Owner::select('id')->where('code',$receiveInputs['Customer'])->first();
//        if (!$owner&&$receiveInputs['SOReference5']) {
//            Owner::create(['code'=>$receiveInputs['Customer'],'name'=>$receiveInputs['Customer']]);
//            $this->log(__METHOD__, __FUNCTION__, '富勒下发找不到货主，添加. 快递单号：'.$receiveInputs['SOReference5'] , null);
//        }
//        if (!$receiveInputs['CarrierID']) {
//            $this->log(__METHOD__, __FUNCTION__, '富勒没有下发快递公司！快递单号：'.$receiveInputs['SOReference5'] , null);
//        }
//        $logistic=Logistic::select('id')->where('code',$receiveInputs['CarrierID'])->first();
//        if (!$logistic&&$receiveInputs['CarrierID']) {
//            Logistic::create(['code'=>$receiveInputs['CarrierID'],'name'=>$receiveInputs['CarrierID']]);
//            $this->log(__METHOD__, __FUNCTION__, '富勒下发找不到承运商，添加. 快递单号：' .$receiveInputs['SOReference5'] , null);
//        }
//        if ($package) {
//            $package->delivery_number = $receiveInputs['palletid'];
//            if ($owner) {
//                $package->owner_id = $owner->id;
//                $packagePaperBox = new Package();
//                $packagePaperBox->fetchPaperBox($package->length, $package->width, $package->height);
//            } else {
//                $package->status = '记录异常';
//            }
//            $package->recipient = $receiveInputs['Consigneename'];
//            if ($logistic) $package->logistic_id = $logistic->id;
//            $package->batch_number = $receiveInputs['USERDEFINE1'];
//            $package->batch_rule = $receiveInputs['USERDEFINE2'];
//            $package->save();
//            $result = $this->accomplishToWMS($package);
//            if ($result['result'] == 'success') {
//                if ($package->status == "记录异常") $package->status = "已上传异常";
//                else $package->status = "已上传";
//            } else {
//                $package->status = "上传异常";
//            }
//            $package->save();
//            $this->log(__METHOD__, 'fluxPackageApi' . __FUNCTION__, json_encode($request->all()), null);
//            return response()->json(['response' => ['flag' => 'Y', 'code' => '0000', 'message' => '正确接收']])
//                ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
//        }
//        //package不存在
//        $receive = new WMSReflectPackage($receiveInputs);
//        try{
//            $receive->save();
//        }catch (\Exception $exception){
//            Controller::logS(__METHOD__,'Exception_'.__FUNCTION__,'WMS下发请求保存异常：'.$exception->getMessage(),null);
//            return ['response'=>['flag'=>'W','message'=>'already send, order number unique violation.',
//                'errors'=>$exception->getMessage()]];
//        }
//        if (isset($owner->id)&&isset($logistic->id)){
//            $createPackage = new Package([
//                'logistic_number'=>$receiveInputs['SOReference5'],
//                'delivery_number'=>$receiveInputs['palletid'],
//                'recipient'=>$receiveInputs['Consigneename'],
//                'owner_id'=>$owner->id,
//                'logistic_id'=>$logistic->id,
//                'batch_number'=>$receiveInputs['USERDEFINE1'],
//                'batch_rule'=>$receiveInputs['USERDEFINE2'],
//                'status'=>'未测量'
//            ]);
//        }else{
//            $this->log(__METHOD__,'fluxPackageApi(no owner or carrier)'.__FUNCTION__,json_encode($request->all()),null);
//            $createPackage = new Package([
//                'logistic_number'=>$receiveInputs['SOReference5'],
//                'delivery_number'=>$receiveInputs['palletid'],
//                'recipient'=>$receiveInputs['Consigneename'],
//                'batch_number'=>$receiveInputs['USERDEFINE1'],
//                'batch_rule'=>$receiveInputs['USERDEFINE2'],
//                'status'=>'记录异常'
//            ]);
//        }
//        $createPackage->order_code=$receiveInputs['Orderno'];
//        $createPackage->save();
//        //活动波次同步  组合提总
//        if ($receiveInputs['USERDEFINE2']&&strstr($receiveInputs['USERDEFINE2'],'组合')) {
//            $packageBatch = Package::whereRaw('batch_number = ? AND weight IS NOT NULL', [$receiveInputs['USERDEFINE1']])->first();
//            if ($receiveInputs['USERDEFINE1'] && $packageBatch) {
//                $createPackage->measuring_machine_id = $packageBatch->measuring_machine_id;
//                $createPackage->weight = $packageBatch->weight;
//                $createPackage->length = $packageBatch->length;
//                $createPackage->width = $packageBatch->width;
//                $createPackage->height = $packageBatch->height;
//                $createPackage->bulk = $packageBatch->bulk;
//                $createPackage->paper_box_id = $packageBatch->paper_box_id;
//                $createPackage->save();
//                $result = $this->accomplishToWMS($createPackage);
//                if ($result['result'] == 'success') {
//                    if ($createPackage->status == "记录异常") $createPackage->status = "已上传异常";
//                    else $createPackage->status = "已上传";
//                } else {
//                    $createPackage->status = "上传异常";
//                }
//            }
//            if (!$receiveInputs['USERDEFINE1'] || !$packageBatch) {
//                MarkPackageExcepted::dispatch($createPackage)->delay(Carbon::now()->addMinutes(1440));
//            }
//            $createPackage->save();
//            $this->log(__METHOD__, 'success_' . __FUNCTION__, json_encode($request->all()), null);
//            return response()->json(['response' => ['flag' => 'Y', 'code' => '0000', 'message' => '正确接收']])
//                ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
//        }
//        MarkPackageExcepted::dispatch($createPackage)->delay(Carbon::now()->addMinutes(1440));
//        $this->log(__METHOD__,'success_'.__FUNCTION__,json_encode($request->all()),null);
        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));
//            $this->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'){
//                $this->log(__METHOD__,'SUCCESS_'.__FUNCTION__,json_encode($json).'| response: '.json_encode($response),null);
//                return ['result'=>'success'];
//            }
//            $this->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(Package $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()]);
            }
//            $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));
//            $this->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'){
//                $this->log(__METHOD__,'SUCCESS_'.__FUNCTION__,json_encode($json).'| response: '.json_encode($response),null);
//                return ['result'=>'success'];
//            }
                $this->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::where('waveno',$batchNumber)->first();
        if(!$docWaveHeader){
            {return ['result'=>false,'message'=>'波次不存在'];}
        }
        if(OracleDOCWaveDetails::unpackedOrders($batchNumber)->isNotEmpty())
            {return ['result'=>false,'message'=>'有未装箱或完成的订单在该波次，不能批量记录重量'];}

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

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


}
