<?php

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

use App\City;
use App\Http\Controllers\Controller;
use App\Owner;
use App\Unit;
use App\Waybill;
use App\OraccleBasCustomer;
use App\WMSWaybill;
use App\WMSWaybillOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Ramsey\Uuid\Uuid;
use Zttp\Zttp;

class WaybillController extends Controller
{

    public function new_(Request $request)
    {
        (new Controller())->log(__METHOD__,__FUNCTION__,'WMS requesting:.'.'|'.json_encode($request->all()));
        $errors=$this->validatorForNew($request->all())->errors();
        if(count($errors)>0){
            $this->log(__METHOD__, 'error_' . __FUNCTION__, json_encode($request->getContent()));
            (new Controller())->log(__METHOD__,'error_'.__FUNCTION__,'fields wrong, see Errors report please.'.'|'.json_encode($request->all()).'|'.json_encode($errors));
            return response()->json(['response'=>['return'=>['returnFlag'=>'0','returnCode'=>'0001','returnDesc'=>'消息处理失败:Failure','resultInfo'=>'',
                'errors'=>$errors]]])
                ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }
        $receivedInputtings=$request->input('request');
        foreach ($receivedInputtings as $receiveInputting){
            if(!WMSWaybill::create($receiveInputting)){
                Controller::logS(__METHOD__,'error_'.__FUNCTION__,'运单WMS写入错误'.'|'.json_encode($receiveInputting));
                return response()->json(['response'=>['return'=>['returnFlag'=>'0','returnCode'=>'0001','returnDesc'=>'运单WMS写入错误'.'|'
                    .json_encode($receiveInputting),'resultInfo'=>'']]])
                    ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
            }
            if(isset($receiveInputting['order_list'])&&$receiveInputting['order_list']){
                $warehouseVolume=0;
                $warehouseWeight=0;
                $sign=false;
                foreach ($receiveInputting['order_list'] as $orderInputting){
                    if ($orderInputting['Cubic'])$warehouseVolume += $orderInputting['Cubic'];
                    if ($orderInputting['Cubic']==0)$sign=true;
                    if ($orderInputting['GrossWeight'])$warehouseWeight +=$orderInputting['GrossWeight'];
                    if (!$orderInputting['GrossWeight'] && $orderInputting['NetWeight']) $warehouseWeight +=$orderInputting['NetWeight'];
                    $orderInputting['OrderNo']=$receiveInputting['OrderNo'];
                    if(!WMSWaybillOrder::create($orderInputting)){
                        Controller::logS(__METHOD__,'error_'.__FUNCTION__,'运单订单行WMS写入错误'.'|'.json_encode($orderInputting));
                        return response()->json(['response'=>['return'=>['returnFlag'=>'0','returnCode'=>'0001','returnDesc'=>'运单订单行WMS写入错误'.'|'
                            .json_encode($orderInputting),'resultInfo'=>'']]])
                            ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
                    }
                }
                if ($sign)$warehouseVolume=0;
            }
            $owner=Owner::where('code',$receiveInputting['CustomerID'])->first();
            if (!$owner){$owner=new Owner(['name'=>$receiveInputting['CustomerID'],'code'=>$receiveInputting['CustomerID']]);$owner->save();}
            $city=City::where('name',$receiveInputting['C_City'])->first();
            $zfList=config('merchantsInfo.waybill.ZFList');
            $bswasCustomer=OraccleBasCustomer::where("customerid",$receiveInputting['CustomerID'])->first();
            if ($bswasCustomer){
                $origination=$bswasCustomer->address1;
                $addresses=config("merchantsInfo.address");
                foreach ($addresses as $addressKey=>$addressValue){
                    if (strpos($origination,$addressKey))$origination=$addressValue;
                }
            }
            $recipient_mobile=trim($receiveInputting['C_Tel1'],',');
            $waybill=new Waybill([
                'type'=>isset($zfList[$receiveInputting['CarrierID']])&&$zfList[$receiveInputting['CarrierID']]?"直发车":"专线",
                'waybill_number'=>Uuid::uuid1(),
                'owner_id'=>$owner->id,
                'wms_bill_number'=>$receiveInputting['OrderNo']??'',
                'origination'=>isset($origination)?$origination:"",
                'destination'=>$receiveInputting['C_Address1']??'',
                'recipient'=>$receiveInputting['ConsigneeName']??'',
                'recipient_mobile'=>$recipient_mobile??'',
                'source_bill'=>$receiveInputting['ReservedField01']??'',
                'destination_city_id'=>$city['id'],
            ]);
            $dflist=config('merchantsInfo.waybill.DFList');
            if (isset($dflist[$receiveInputting['CarrierID']]) && $dflist[$receiveInputting['CarrierID']])$waybill->collect_fee=0;
            if (isset($warehouseVolume)&&$warehouseVolume){
                $waybill->warehouse_weight=$warehouseVolume;
                $unit=Unit::where('name','m³')->first();
                if ($unit)$waybill->warehouse_weight_unit_id=$unit->id;
            }
            if (isset($warehouseWeight)){
                $waybill->warehouse_weight_other=$warehouseWeight;
                $unit=Unit::where('name','kg')->first();
                if ($unit)$waybill->warehouse_weight_unit_id_other=$unit->id;
            }
            $waybill->save();
            if ($waybill->type=='直发车'){
                $waybill_number='BSZF'.date ("ymd").str_pad($waybill->id>99999?$waybill->id%99999:$waybill->id,4,"0",STR_PAD_LEFT);
                $waybill->waybill_number=$waybill_number;
                $waybill->update();
            }else{
                $waybill_number='BSZX'.date ("ymd").str_pad($waybill->id>99999?$waybill->id%99999:$waybill->id,4,"0",STR_PAD_LEFT);
                $waybill->waybill_number=$waybill_number;
                $waybill->update();
            }
            //回传FLUX
            $this->accomplishToWMS($waybill);
        }
        return response()->json(['response'=>['return'=>['returnFlag'=>'1','returnCode'=>'0000','returnDesc'=>'正确接收','resultInfo'=>'']]])
            ->setEncodingOptions(JSON_UNESCAPED_UNICODE);


    }

    protected function validatorForNew(array $data)
    {
        return Validator::make($data, [
            'request' => ['required', 'array', 'min:1'],
            'request.*.OrderNo' => ['required', 'string', 'max:191','unique:w_m_s_waybills,OrderNo'],
            'request.*.CustomerID' => ['required', 'string', 'max:191'],
            'request.*.CarrierID' => ['required', 'string', 'max:191'],
            'request.*.ConsigneeName' => ['nullable', 'string', 'max:191'],
            'request.*.C_Tel1' => ['nullable', 'string', 'max:191'],
            'request.*.C_Address1' => ['nullable', 'string', 'max:191'],
            'request.*.C_Province' => ['nullable', 'string', 'max:191'],
            'request.*.C_City' => ['nullable', 'string', 'max:191'],
            'request.*.C_District' => ['nullable', 'string', 'max:191'],
            'request.*.order_list' => ['nullable', 'array', 'min:1'],
            'request.*.order_list.*.SKU_Descr_c' => ['nullable', 'string', 'max:191'],
            'request.*.order_list.*.SKU' => ['nullable', 'string', 'max:191'],
            'request.*.order_list.*.Alternate_sku1' => ['nullable', 'string', 'max:191'],
            'request.*.order_list.*.Qtyordered_each' => ['nullable', 'string', 'max:191'],
            'request.*.order_list.*.Cubic' => ['nullable', 'string', 'max:191'],
            'request.*.order_list.*.GrossWeight' => ['nullable', 'string', 'max:191'],
            'request.*.order_list.*.NetWeight' => ['nullable', 'string', 'max:191'],
        ]);
    }

    public function accomplishToWMS(Waybill $waybill)
    {
        $json="
                {
                    \"request\": [
                        {
                            \"OrderNo\": \"{$waybill['wms_bill_number']}\",
                            \"DELIVERYNO\": \"{$waybill['waybill_number']}\"
                        }
                    ]
                }
                ";
        $sendingJson = json_decode($json,true);
        $url=url(config('api.flux.waybill.new'));
        try{
            $response = Zttp::post($url, $sendingJson);
        }catch (\Exception $exception){
            $this->log(__METHOD__,'Exception_'.__FUNCTION__,'CURL请求异常：'.$exception->getMessage(),null);
            return false;
        }
        $responseJson = $response->json();
        if(!$responseJson||!isset($responseJson['Response'])||!$responseJson['Response']['return']['returnFlag']=='1'){
            Controller::logS(__METHOD__,'error_'.__FUNCTION__,"向WMS提交运单失败！！SO单号：{$waybill['wms_bill_number']}。提交：{$json}，返回：{$response->body()}, URL：{$url}",Auth::user()['id']);
            return false;
        }
        Controller::logS(__METHOD__,''.__FUNCTION__,"向WMS提交运单成功，SO单号：{$waybill['wms_bill_number']}。返回：{$response->body()}",Auth::user()['id']);
        return true;

    }

}
