<?php

namespace App\Services;

use App\OracleActAllocationDetails;
use App\OracleDOCOrderDetail;
use App\OracleDOCOrderHeader;
use App\Order;
use App\OrderPackage;
use App\OrderPackageCommodities;
use App\OrderTracking;
use App\Services\common\BatchUpdateService;
use App\Services\common\DataHandlerService;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class OrderPackageService
{
    public function batchUpdate(array $params){
        return app(BatchUpdateService::class)->batchUpdate('order_packages',$params);
    }

    public function insert(array $params)
    {
        return OrderPackage::query()->insert($params);
    }

    public function createdByOrder($order)
    {
        /** @var OrderPackageCommoditiesService $orderPackageCommoditiesService */
        $orderPackageCommoditiesService = app('OrderPackageCommoditiesService');
        $oracleActAllocationDetails = OracleActAllocationDetails::query()->where('OrderNo', $order['code'])->get();
        $orderHeader = OracleDOCOrderHeader::query()->where('OrderNo', $order['code'])->first();
        $oracleDOCOrderDetail = OracleDOCOrderDetail::query()->where('OrderNo', $order['code'])->get();
        $logistic_number = null;
        if ($oracleActAllocationDetails->count() == 0) {  // 通过oracle Order Detail
            $logistic_number = $orderHeader['soreference5'];
            if ($oracleDOCOrderDetail->count() == 0) {
                return null;
            }
            if ($logistic_number == null || $logistic_number == '*') {
                return null;
            }
            try {
                $orderPackage = OrderPackage::query()->firstOrCreate(['order_id' => $order['id'], 'logistic_number' => $logistic_number]);
                $orderPackageCommoditiesService->basedOnOracleDetailsStore($orderHeader['orderno'], $orderPackage);
                app('LogService')->log(__METHOD__, __FUNCTION__, '创建订单包裹orderPackage' . json_encode($orderPackage));
            } catch (\Exception $e) {
                app('LogService')->log(__METHOD__, __FUNCTION__, '创建订单包裹orderPackage失败' . $e->getMessage() . $e->getTraceAsString());
            }
        } else if ($oracleActAllocationDetails->count() > 0) {
            $count = $oracleActAllocationDetails->where('OrderNo', $order['code'])->whereNull('picktotraceid')->count();
            if ($count > 0) {   // 快递单号为空
                if (($orderHeader['soreference5'] ?? false) && $orderHeader['soreference5'] == '*') {
                    return null;
                }
                $logistic_number = $orderHeader['soreference5'];

                try {
                    $orderPackage = OrderPackage::query()->firstOrCreate(['order_id' => $order['id'], 'logistic_number' => $logistic_number]);
                    $orderPackageCommoditiesService->basedOnOracleDetailsStore($order, $orderPackage);
                    app('LogService')->log(__METHOD__, __FUNCTION__, '创建订单包裹orderPackage' . json_encode($orderPackage));
                } catch (\Exception $e) {
                    app('LogService')->log(__METHOD__, __FUNCTION__, '创建订单包裹orderPackage失败' . $e->getMessage() . $e->getTraceAsString());
                }
            } else {
                $ActAllocationDetails = $oracleActAllocationDetails->where('orderno', $order['code']);
                $picktotraceids = data_get($ActAllocationDetails,'*.picktotraceid');
                $picktotraceids = array_unique($picktotraceids);
                foreach ($picktotraceids as $picktotraceid) {
                    $logistic_number = $picktotraceid;
                    if ($logistic_number == null || $logistic_number == '*') {
                        $logistic_number = $orderHeader['soreference5'];
                        if ($logistic_number == null || $logistic_number == '*') {
                            return null;
                        }
                        $orderPackage = OrderPackage::query()->where(['order_id' => $order['id'], 'logistic_number' => $logistic_number])->first();
                        if ($orderPackage) {
                            $orderPackageCommoditiesService->basedOnActAllocationDetailsStoreByOrderNo($order['code'], $orderPackage);
                            continue;
                        }
                        try {
                            $orderPackage = OrderPackage::query()->create(['order_id' => $order['id'], 'logistic_number' => $logistic_number]);
                            $orderPackageCommoditiesService->basedOnActAllocationDetailsStoreByOrderNo($order['code'], $orderPackage);
                            app('LogService')->log(__METHOD__, __FUNCTION__, '创建订单orderPackage' . json_encode($orderPackage));
                        } catch (\Exception $e) {
                            app('LogService')->log(__METHOD__, __FUNCTION__, '创建订单orderPackage失败' . json_encode($e->getMessage()) . json_encode($e->getTraceAsString()));
                        }
                        continue;
                    }
                    $orderPackage = OrderPackage::query()->where('order_id', $order['id'])->where('logistic_number', $logistic_number)->first();
                    if ($orderPackage) {
                        $orderPackageCommoditiesService->basedOnActAllocationDetailsStore($orderPackage);
                        continue;
                    }
                    try {
                        $orderPackage = OrderPackage::query()->create(['order_id' => $order['id'], 'logistic_number' => $logistic_number]);
                        $orderPackageCommoditiesService->basedOnActAllocationDetailsStore($orderPackage);
                        app('LogService')->log(__METHOD__, __FUNCTION__, '创建订单' . json_encode($orderPackage));
                    } catch (\Exception $e) {
                        app('LogService')->log(__METHOD__, __FUNCTION__, '创建订单orderPackage失败' . json_encode($e->getMessage()) . json_encode($e->getTraceAsString()));
                    }
                }
            }
        }
        unset($oracleActAllocationDetails,$oracleDOCOrderDetail);
    }
    // 需删除
//    public function updateOrderPackageInfo(Order $order)
//    {
//        $orderHeader = OracleDOCOrderHeader::where('orderNo', $order['code'])->first();
//        if ($orderHeader['oracleBASCode_codename_c'] == $order['wam_status']) {
//            return;
//        }
//        $orderPackages = OrderPackage::where('order_id', $order['id'])->get();
//        $orderPackageCommodities = OrderPackageCommodities::with('commodity')->whereIn('order_package_id', data_get($orderPackages, '*.id'))->get();
//        $actAllocationDetails = OracleActAllocationDetails::where('orderNo', $order['client_code'])->get();
//        if (count($orderPackageCommodities) < count($actAllocationDetails)) {
//            $actAllocationDetails = $actAllocationDetails->reject(function ($value, $key) use (&$orderPackageCommodities) {
//                $bool = false;
//                $count = 0;
//                $orderPackageCommodities->reject(function ($value1, $key1) use ($value, &$bool, $count) {
//                    if ($count > 0) {
//                        return false;
//                    }
//                    if ($value1->commodity['sku'] == $value['sku'] && $value1['amount'] == intval($value['qty'])) {
//                        $bool = true;
//                        $count++;
//                        return true;
//                    } else {
//                        return false;
//                    }
//                });
//                return $bool;
//            });
//        }
//        $orderPackageCommoditiesService = app('OrderPackageCommoditiesService');
//        $orderPackageCommoditiesService->basedOnActAllocationDetail($order, $orderHeader, $actAllocationDetails);
//        $order['wam_status'] = $orderHeader['oracleBASCode_codename_c'];
//        $order->save();
//    }
    /**
     * @param string $logistic_number
     * @param array $values
     * @return OrderPackage $package
     */
    public function firstOrCreate($logistic_number, array $values){
        /** @var $package OrderPackage  */
        $package = OrderPackage::query()->where('logistic_number',$logistic_number)->first();
        if ($package)return $package;

        /** @var OrderService */
        $order = app('OrderService')->logisticNumberFirstOrCreateOrder($logistic_number);
        if ($order) $values["order_id"] = $order->id;

        $values["logistic_number"] = $logistic_number;
        /** @var OrderPackage $package */
        $package = OrderPackage::query()->create($values);
        return $package;
    }


    public function createExceptionPaginate($paginate)
    {
        return OrderPackage::query()->select('id', 'status', 'logistic_number', 'measuring_machine_id', 'weighed_at', 'weight', 'length', 'width', 'height', 'bulk', 'paper_box_id')
            ->where('status', '上传异常')->orWhere('status', '测量异常')->orderBy('created_at', 'DESC')
            ->paginate($paginate);
    }

    public function issueExceptionPaginate($paginate)
    {
        return OrderPackage::query()->select('id', 'logistic_number', 'created_at', 'batch_number', 'batch_rule')
            ->where('status', '下发异常')->orWhere('status', '记录异常')
            ->orWhere('status', '已上传异常')->orderBy('created_at', 'DESC')
            ->paginate($paginate);
    }

    public function createByWmsOrder($orderHeaders)
    {
        /**
         * @var OrderService $orderService
         * @var DataHandlerService $dataHandlerService
         * @var OrderPackageCommoditiesService $orderPackageCommodityService
         */
        $orderService = app(OrderService::class);
        $dataHandlerService = app(DataHandlerService::class);
        $orderPackageCommodityService = app(OrderPackageCommoditiesService::class);

        if(!$orderHeaders ){return ;}
        $orders = $orderService->getByWmsOrders($orderHeaders);
        if(!$orders){return ;}
        $order_packages = OrderPackage::query()->whereIn('order_id',data_get($orders,'*.id'))->get();

        $order_packages_logistic_number_map=$dataHandlerService->dataHeader(['order_id','logistic_number'],$order_packages);
        $order_headers_orderNo_map =  $dataHandlerService->dataHeader(['orderno'],$orderHeaders);

        $insert_params = [];
        foreach ($orders as $order) {
            $orderHeader =  $dataHandlerService->getKeyValue(['orderno'=>$order->code],$order_headers_orderNo_map);
            if(!$orderHeader){ continue;}
            if(!$orderHeader->sostatus == 90){ continue;}
            $params = $this->getParamsByOrderHeader($orderHeader,$order,$order_packages_logistic_number_map);
            if(!$params){continue;}
            foreach ($params as $param) {
                $key = ['order_id'=>$param['order_id'],'logistic_number'=>$param['logistic_number']];
                $orderPackage = $dataHandlerService->getKeyValue($key,$order_packages_logistic_number_map);
                if(isset($orderPackage)){
                    continue;
                }else{
                    $insert_params[] = $param;
                }
            }
        }
        if(count($insert_params)>0){
            $order_packages = $this->create($insert_params);
        }
        unset($orders_code_map,$order_packages_logistic_number_ma,$insert_params,$order_packages,$order_package_commodities);
        $orderPackageCommodityService->createByWmsOrder($orderHeaders);
        unset($orderHeaders);
    }

    public function getParamsByOrderHeader($orderHeader,$order,$order_packages_logistic_number_map)
    {
        /** @var DataHandlerService $dataHandlerService */
        $dataHandlerService = app(DataHandlerService::class);
        $actAllocationDetails = $orderHeader->actAllocationDetails;
        $logistic_numbers = array_diff(array_unique(data_get($actAllocationDetails,'*.picktotraceid')),['','*',null]);
        $params = [];
        $created_at = Carbon::now()->format('Y-m-d H:i:s');
        $updated_at = Carbon::now()->format('Y-m-d H:i:s');
        foreach ($logistic_numbers as $logistic_number) {
//            if($logistic_number == $orderHeader->orderno)continue;
            $key  = ['order_id'=>$order->id,'logistic_number'=>$logistic_number];
            $orderPackage = $dataHandlerService->getKeyValue($key,$order_packages_logistic_number_map);
            if(isset($orderPackage)){ continue;}
            $params[] = [
                'order_id' => $order->id, 'logistic_number' => $logistic_number,'created_at' => $created_at,'updated_at' => $updated_at
            ];
        }
        return $params;
    }

//    public function getUpdateParamsByOrderHeader($orderHeader,$order,$orderPackages)
//    {
//        $updated_at = Carbon::now()->format('Y-m-d H:i:s');
//        /** @var DataHandlerService $dataHandlerService */
//        $dataHandlerService = app(DataHandlerService::class);
//        $wms_logistic_number =  app(OracleDOCOrderHeaderService::class)->getLogisticNumbers($orderHeader);
//        $order_packages  = $orderPackages->where('order_id',$order->id)->get();
//        $was__logistic_number = data_get($order_packages,'*.logistic_number');
//        $arr1=  array_diff($was__logistic_number,$wms_logistic_number);
//        $arr2=  array_diff($wms_logistic_number,$was__logistic_number);
//        if(count($arr2) > 0 && count($arr1) == 0){
//            return [
//                'id'=>$order_packages->first()->id,
//                'logistic_number' => $arr1[0],
//                'updated_at'=> $updated_at,
//            ];
//        }
//        return null;
//    }

    public function updateOrderPackageByWmsOrder($orderHeaders){
        /** @var OrderPackageCommoditiesService $orderPackageCommoditiesService */
        $orderPackageCommoditiesService =  app(OrderPackageCommoditiesService::class);
        /** @var DataHandlerService $dataHandlerService */
        $dataHandlerService = app(DataHandlerService::class);
        if(!$orderHeaders){return;}

        $orders = Order::query()->with('packages')->whereIn('code',data_get($orderHeaders,'*.orderno'))->get();
        $orders_code_map =  $dataHandlerService->dataHeader(['code'],$orders);

        $orderPackages =$this->getByWmsOrders($orderHeaders);
        $order_packages_logistic_number_map = $dataHandlerService->dataHeader(['order_id','logistic_number'],$orderPackages);

        $insertParams = [];
        foreach ($orderHeaders as $orderHeader) {
            $order = $dataHandlerService->getKeyValue(['code'=>$orderHeader->orderno ?? ''],$orders_code_map);
            if(!$order){continue;}
            $order_packages = $order->packages ?? null;
            if(!$order_packages){continue;}
            $params =$this->getParamsByOrderHeader($orderHeader,$order,$order_packages_logistic_number_map);
            if(count($params) > 0){
                foreach ($params as $param) {
                    $key  = ['order_id'=>$param['order_id'],'logistic_number'=>$param['logistic_number']];
                    $order_package = $dataHandlerService->getKeyValue($key,$order_packages_logistic_number_map);
                    if($order_package){continue;}
                    $insertParams[] = $param;
                }
            }
        }
        if(count($insertParams)>0){
            $this->create($insertParams);
        }
        $orderPackageCommoditiesService->updateByWmsOrder($orderHeaders);
        $this->删除多余的订单包裹_根据WMS订单($orderHeaders);
    }

    public function getByWmsOrders($orderHeaders){
        $order_nos = data_get($orderHeaders,'*.orderno');
        return OrderPackage::query()->with('order')
            ->whereHas('order',function($query) use ($order_nos){
                $query->whereIn('code',$order_nos);
            })->get();
    }

    public function create(array $params)
    {
        if(count($params) == 0)return null;
        try {
            $this->insert($params);
            app('LogService')->log(__METHOD__,__FUNCTION__,'批量生成 orderPackage' . count($params) . json_encode($params));
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__,__FUNCTION__,'批量生成 orderPackage error ' . json_encode($params) . $e->getMessage() . $e->getTraceAsString());
        } finally {
            $logistic_numbers = data_get($params,'*.logistic_number');
            unset($params);
            return OrderPackage::query()->whereIn('logistic_number',$logistic_numbers)->get();
        }
    }

    /**
     * @param OracleDOCOrderHeader $orderHeaders
     */
    public function 删除多余的订单包裹_根据WMS订单($orderHeaders)
    {
        if(!isset($orderHeaders)){return;}
        if(is_array($orderHeaders) && count($orderHeaders) == 0){return;}
        $orderPackages = $this->getByWmsOrders($orderHeaders);
        $Was_logistic_number = data_get($orderPackages,'*.logistic_number');
        $Wms_logistic_number = array_unique(data_get($orderHeaders,'*.actAllocationDetails.*.picktotraceid'));
        $delete_logistic_number = array_diff($Was_logistic_number,$Wms_logistic_number);
        if(count($delete_logistic_number) == 0){return;}
        $delete_orderPackages = OrderPackage::query()->wherein('logistic_number',$delete_logistic_number)->get();
        $delete_ids = app(OrderPackageCommoditiesService::class)->删除包裹商品信息_根据快递单号($delete_logistic_number);
        try {
            OrderPackage::query()->whereIn('logistic_number', $delete_logistic_number)->delete();
            app('LogService')->log(__METHOD__,__FUNCTION__,'删除多余OrderPackage '.$delete_orderPackages->count().json_encode($delete_orderPackages),null);
            $orderTracking = OrderTracking::query()->whereIn('order_package_commodity_id', $delete_ids)->get();
            app(OrderTrackingService::class)->deleteOrderTracings($orderTracking);
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__,__FUNCTION__,'删除多余OrderPackage error'.$delete_orderPackages->count().json_encode($delete_orderPackages).$e->getMessage().$e->getTraceAsString(),null);
        }
    }

    /**
     * @param array  $orderNos
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getByOrderNos($orderNos)
    {
        return OrderPackage::query()->with('order')
            ->whereHas('order',function($query)use($orderNos){
                $query->whereIn('code',$orderNos);
            })->get();
    }

    public function 返回OrderPackage数组_根据数组中的快递单号($params)
    {
        $map = [];
        $orderPackages = OrderPackage::query()->whereIn('logistic_number',data_get($params,'*.logistic_number'))->get();
        if($orderPackages->count() == 0){return $map;}
        foreach ($orderPackages as $orderPackage) {
            $map[$orderPackage->logistic_number] = $orderPackage;
        }
        return  $map;
    }

    /**
     * @param string $orderClientNo
     * @param string $logisticNumber
     * @return array|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object
     */
    public function update($orderClientNo,$logisticNumber)
    {
        $order = Order::query()->with('packages.commodities.commodity')->where('client_code',$orderClientNo)->first();
        if(!$order){
            $order = Order::query()->create(['client_code'=>$orderClientNo]);
        }
        $orderPackage = OrderPackage::query()->where('logistic_number',$logisticNumber)->first();
        if($orderPackage){return  compact('orderPackage','order');}
        $orderPackage = OrderPackage::query()->create(['order_id'=>$order->id,'logistic_number'=>$logisticNumber]);
        return  compact('orderPackage','order');
    }

    // TODO
    public function syncOrderPackage(&$orderHeaders)
    {
        /**
         * @var OrderPackageCommoditiesService $OrderPackageCommoditiesService
         */
        $OrderPackageCommoditiesService = app('OrderPackageCommoditiesService');
        $this->syncPackageByOrderHeaders($orderHeaders);
        $OrderPackageCommoditiesService->syncOrderPackageCommodities($orderHeaders);
    }
    // TODO
    public function syncPackageByOrderHeaders(&$orderHeaders)
    {
        /**
         * @var OrderService $orderService
         * @var OrderPackageCommoditiesService $orderPackageCommodityService
         * @var OrderTrackingService $orderTrackingService
         */
        $orderService = app('OrderService');
        $orderPackageCommodityService= app('OrderPackageCommoditiesService');
        $orderTrackingService = app('OrderTrackingService');
        if(!$orderHeaders)return;
        $orders = $orderService->getByWmsOrders($orderHeaders);
        $packages = $this->getByOrderNos(data_get($orderHeaders,'*.orderno'));          // 已有
        $this->createOrderPackage($orderHeaders,$orders,$packages);                     // 创建package

        $del_ids = $this->deleteUnnecessaryPackage($orderHeaders,$packages);     // 删除package
        $orderPackageCommodityService->deleteUnnecessaryOrderCommodities($del_ids);     // 删除 orderCommodity

        $orderTracking = OrderTracking::query()->whereHas('commodities.package',function($query)use($del_ids){
            $query->whereIn('id',$del_ids);
        })->get();
        $orderTrackingService->deleteOrderTracings($orderTracking);                     // 删除追踪件
    }
    // TODO
    public function createOrderPackage($orderHeaders,$orders,$packages)
    {
        if(!$orderHeaders)return;
        /**
         * @var DataHandlerService $dataHandlerService
         */
        $dataHandlerService = app(DataHandlerService::class);
        $orderHeaders_map = $dataHandlerService->dataHeader(['orderno'],$orderHeaders);
        $packages_maps = $dataHandlerService->dataHeader(['logistic_number'],$packages);
        $inner_params = [];
        foreach ($orders as $order){
            $orderHeader = $dataHandlerService->getKeyValue(['orderno'=>$order->code],$orderHeaders_map);
            if(!$orderHeader)continue;
            if($orderHeader->sotatus == 90)continue;
            $params = $this->getInnerParams($orderHeader,$order,$packages_maps);
            $inner_params = array_merge($inner_params,$params);
        }
        if(count($inner_params)>0){
            try {
                $inner_array = array_chunk($inner_params,1000);
                foreach ($inner_array as $params) {
                    $bool = $this->insert($params);
                    $bool ? LogService::log(__METHOD__, __FUNCTION__, '批量添加 OrderPackage ' . count($inner_params) . ' || ' . json_encode($inner_params)) : null;
                }
            } catch (\Exception $e) {
                LogService::log(__METHOD__, __FUNCTION__, '批量添加 OrderPackage error ' . count($inner_params) . ' || ' .json_encode($e->getMessage()). json_encode($inner_params).json_encode($e->getTraceAsString()));
            }
        }
    }
    // TODO
    public function getInnerParams($orderHeader,$order,$packages_maps)
    {
        /**
        * @var DataHandlerService $dataHandlerService
        */
        $dataHandlerService = app('DataHandlerService');
        $logistic_numbers = array_diff(array_unique(data_get($orderHeader->actAllocationDetails,'*.picktotraceid')),['','*']);
        $inner_params = [];
        $date = Carbon::now()->format('Y-m-d H:i:s');
        foreach ($logistic_numbers as $logistic_number){
            $package = $dataHandlerService->getKeyValue(['logistic_number'=>$logistic_number],$packages_maps);
            if(isset($package))continue;
            $inner_params[] = [
                'order_id' => $order->id,
                'logistic_number' => $logistic_number,
                'created_at' => $date,
                'updated_at' => $date,
                'status' =>'无'
            ];
        }
        return $inner_params;
    }
    // TODO
    public function deleteUnnecessaryPackage($orderHeaders,$packages)
    {
        /**
         * @var DataHandlerService $dataHandlerService
         */
        $dataHandlerService = app(DataHandlerService::class);
        $logistic_numbers = data_get($orderHeaders,'*.actAllocationDetails.*.picktotraceid');     // 获取picktotraceid (运单的快递单号)
        $logistic_numbers = array_unique($logistic_numbers);
        $logistic_numbers = array_diff($logistic_numbers,['',' ','*']);

        $packages_maps = $dataHandlerService->dataHeader(['logistic_number'],$packages);
        $exits_number = data_get($packages,'*.logistic_number');
        $packages = collect();
        $diff_number = array_diff($exits_number,$logistic_numbers);
        foreach ($diff_number as $number) {
            $package = $dataHandlerService->getKeyValue(['logistic_number'=>$number],$packages_maps);
            if($package ?? false)$packages->push($package->id);
        }
        if($packages->isEmpty())return $packages;
        try {
            $bool = OrderPackage::query()->whereIn('id', $packages)->delete();
            $bool ? LogService::log(__METHOD__,__FUNCTION__,'删除多余包裹 ids:'.json_encode($packages)) : null;
            return $bool ? $packages : collect();
        } catch (\Exception $e) {
            LogService::log(__METHOD__,__FUNCTION__,'删除多余包裹 ids:'.json_encode($packages).$e->getMessage());
            return collect();
        }
    }
    // TODO
    public function createPackagesFromBatchCode($batchCode,$weight)
    {
        /**
         * @var OrderService $orderService
         */
        $now = Carbon::now();
        $orderService = app('OrderService');
        $orderHeaders = OracleDOCOrderHeader::query()->selectRaw(implode(',',OracleDOCOrderHeaderService::$columns))
            ->with(['oracleBASCustomer'=>function($query){
                $query->selectRaw('BAS_CUSTOMER.CustomerID,BAS_CUSTOMER.Customer_Type,BAS_CUSTOMER.Descr_C,BAS_CUSTOMER.Active_Flag');
            },'oracleDOCOrderDetails'=>function($query){
                $query->selectRaw('doc_order_details.orderNo,doc_order_details.CustomerId,doc_order_details.sku,doc_order_details.QtyOrdered');
            }, 'actAllocationDetails'=>function($query){
                $query->selectRaw('ACT_Allocation_Details.AllocationDetailsID,ACT_Allocation_Details.OrderNo,ACT_Allocation_Details.Qty_Each,ACT_Allocation_Details.PickToTraceID,ACT_Allocation_Details.CustomerID,ACT_Allocation_Details.Sku');
            },'oracleBASCode'=>function($query){
                $query->selectRaw('BAS_Codes.CodeID,BAS_Codes.CodeName_C,BAS_Codes.Code');
            }])
            ->where('Doc_Order_Header.WaveNo',$batchCode)
            ->get();
        $orderService->syncOrderByWMSOrderHeaders($orderHeaders);
        $this->syncPackageByOrderHeaders($orderHeaders);
        $orders = Order::query()->with('packages')->whereIn('code',data_get($orderHeaders,'*.orderno'))->get();
        $update_params = [[
            'id','weight','weighed_at','status','batch_number'
        ]];
        foreach ($orderHeaders as $orderHeader) {
            $order = $orders->where('code',$orderHeader->orderno)->first();
            if(!$order){
                app('LogService')->log(__METHOD__,"此包裹在WMS未找到order",json_encode($orderHeader),Auth::user()['id']);
                continue;
            }
            $order->packages->each(function($package)use(&$update_params,$weight,$batchCode,$now){
                $update_params[] = [
                    'id' => $package->id,
                    'weight' =>$weight,
                    'weighed_at'=>$now,
                    'status' =>"已上传",
                    'batch_number' => $batchCode
                ];
            });
        }
        if(count($update_params)==1)return;
        DB::transaction(function ()use($update_params){
                $this->batchUpdate($update_params);
        });
        app('LogService')->log(__METHOD__,"批量录入包裹成功",json_encode($update_params),Auth::user()['id']);
    }
}
