<?php

namespace App\Services;

use App\OracleActAllocationDetails;
use App\OracleDOCOrderDetail;
use App\OracleDOCOrderHeader;
use App\Order;
use App\OrderPackage;

class OrderPackageService
{

    public function __construct()
    {
        app()->bind('orderPackageCommoditiesService', OrderPackageCommoditiesService::class);
    }

    public function createdByOrder(Order $order, OracleDOCOrderHeader $orderHeader = null)
    {
        $orderPackageCommoditiesService = app('orderPackageCommoditiesService');
        if (!$orderHeader) {
            $orderHeader = OracleDOCOrderHeader::where('OrderNo', trim($order->code, "'"))->first();
        }
// 获取orderNo 对应的打包详情
        $orderActAllocationDetails = OracleActAllocationDetails::where(['OrderNo' => $order->code])->get();
        if (!$orderActAllocationDetails) {
            return [];
        }
        $orderPackages = [];
        foreach ($orderActAllocationDetails as $detail){
            $logistic_number = $detail->picktotraceid;
            $orderPackage = OrderPackage::where(['logistic_number'=>$logistic_number])->first();
            if(!$orderPackage){
                $orderPackage = OrderPackage::firstOrCreate(['order_id'=>$order['id'],'logistic_number'=>$logistic_number]);
            }
            $orderPackageCommoditiesService->createdOrderPackage($orderPackage,$detail);
        }
       $orderPackages =  OrderPackage::with(['commodities' => function($query){
            return $query->with(['commodity']);
        }])->get();
        return  $orderPackages;
    }

}
