<?php

namespace App\Services;

use App\Commodity;
use App\OracleActAllocationDetails;
use App\OracleBasSKU;
use App\OracleDOCOrderDetail;
use App\Order;
use App\OrderPackage;
use App\OrderPackageCommodities;
use App\Owner;

class OrderPackageCommoditiesService
{
    public function createdOrderPackage(OrderPackage $orderPackage)
    {
        $detail = OracleActAllocationDetails::where('picktotraceid',$orderPackage->logistic_number)->first();
        $owner = Owner::where(['code' => $detail->customerid])->first();      // 货主
        $sku = $detail->sku;
        $owner_id = $owner->id;
        $commodity = Commodity::where(['sku' => $sku, 'owner_id' => $owner_id])->first();
        if ($commodity == null) {
            $basSku = OracleBasSKU::where(['sku' => $sku, 'customerid' => $detail->customerid])->first();
            $commodity = Commodity::create(['sku' => $sku, 'owner_id' => $owner_id, 'name' => $basSku->descr_c]);
        }
        $arr = [
            'order_package_id' => $orderPackage->id,      // 包裹id
            'commodity_id' => $commodity->id,             // 商品id
            'amount' => $detail->qty,                     // 商品数量
        ];
        $OrderPackageCommodities = OrderPackageCommodities::create($arr);
        $OrderPackageCommodities->commodity = $commodity;
        return $OrderPackageCommodities;
    }

    public function getOrderPackageCommoditiesByOrderId($orderId){
        $order =  Order::where('id',$orderId)->first();
        if(!$order){
            return null;
        }
        $orderPackageIds = OrderPackage::select('id')->where('order_id',$order['id'])->get();
        if(!$orderPackageIds){
            return null;
        }
        return  OrderPackageCommodities::with('commodity')->whereIn('order_package_id',$orderPackageIds)->get();
    }
}
