<?php

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

use App\Http\Controllers\Controller;
use App\Jobs\HandleExceptionWaybill;
use App\Owner;
use App\Services\RegionService;
use App\Unit;
use App\Waybill;
use App\OracleBasCustomer;
use App\WaybillAuditLog;
use App\WMSWaybill;
use App\WMSWaybillOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
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){
            app('LogService')->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::query()->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::query()->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::query()->where('code',$receiveInputting['CustomerID'])->first();
            if (!$owner){$owner=new Owner(['name'=>$receiveInputting['CustomerID'],'code'=>$receiveInputting['CustomerID']]);$owner->save();}
            $zfList=config('merchantsInfo.waybill.ZFList');
            $bswasCustomer=OracleBasCustomer::query()->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']??'',
                'is_to_pay'=>strstr($receiveInputting['CarrierID']??'','DF')===false ? 0 : 1,
                'destination_city_id'=>$receiveInputting['C_City'] ? app(RegionService::class)->getCity($receiveInputting['C_City']) : null,
            ]);
            $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::query()->where('name','m³')->first();
                if ($unit)$waybill->warehouse_weight_unit_id=$unit->id;
            }
            if (isset($warehouseWeight)){
                $waybill->warehouse_weight_other=$warehouseWeight;
                $unit=Unit::query()->where('name','kg')->first();
                if ($unit)$waybill->warehouse_weight_unit_id_other=$unit->id;
            }
            if ($waybill->wms_bill_number){
                $notes = DB::connection("oracle")->selectOne(DB::raw("SELECT notes FROM DOC_ORDER_HEADER WHERE ORDERNO = ?"),[$waybill->wms_bill_number]);
                if ($notes)$waybill->ordering_remark = $notes->notes;
                $order = app("OrderService")->first(["code"=>$waybill->wms_bill_number]);
                if ($order)$waybill->order_id = $order->id;
            }
            $waybill->save();
            WaybillAuditLog::query()->create([
                'waybill_id'=>$waybill->id,
                'audit_stage'=>'创建',
                'user_id'=>Auth::id() ?? 0,
            ]);
            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();
            }
            if (!$waybill->order_id && $waybill->wms_bill_number)dispatch(new HandleExceptionWaybill($waybill))->delay(now()->addMinutes(15));
            //回传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){
            app('LogService')->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;

    }

}
