<?php

namespace App\Services;

use App\Commodity;
use App\OracleActAllocationDetails;
use App\OracleBasSKU;
use App\OracleDOCOrderDetail;
use App\OracleDOCOrderHeader;
use App\OrderPackageCommodities;
use App\OrderTracking;
use App\Owner;
use App\Services\common\BatchUpdateService;
use App\Services\common\DataHandlerService;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use App\Traits\ServiceAppAop;


class OrderPackageCommoditiesService
{
    use ServiceAppAop;
    protected $modelClass=OrderPackageCommodities::class;

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

    public function create(array $params){
        if(!$params){return [];}
        try {
            $this->insert($params);
            app('LogService')->log(__METHOD__,__FUNCTION__,'批量创建 OrderPackageCommodities'.count($params).json_encode($params));
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__,__FUNCTION__,'批量创建 OrderPackageCommodities error'.json_encode($params)."||".$e->getMessage().'||'.$e->getTraceAsString());
        } finally {
            $order_package_ids = array_unique(data_get($params,'*.order_package_id'));
            unset($params);
            return OrderPackageCommodities::query()
                ->with('commodity')
                ->whereIn('order_package_id',$order_package_ids)
                ->get();
        }
    }

    public function getByWmsOrder($orderHeaders){
        $order_no =  data_get($orderHeaders,'*.orderno');
        return OrderPackageCommodities::query()
            ->with('package.order','commodity')
            ->whereIn('order_package_id',function($query) use ($order_no){
                $query->from('order_packages')->select('id')->whereIn('order_id',function($query)use($order_no){
                    $query->from('orders')->select('id')->whereIn('code',$order_no);
                });
            })->get();
    }

    public function batchUpdateItself($column, array $params)
    {
        return app(BatchUpdateService::class)->batchUpdateItself('order_package_commodities', $column, $params);
    }

    public function getByOrderNos($orderNos)
    {
        return OrderPackageCommodities::query()->with('package.order','commodity')
            ->whereIn('order_package_id',function($query) use ($orderNos){
                $query->from('order_packages')->select('id')->whereIn('order_id',function($query)use($orderNos){
                    $query->from('orders')->select('id')->whereIn('code',$orderNos);
                });
            })->get();
    }

    /**
     * @param Collection $orders
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getByOrders($orders)
    {
        return $this->getByOrderNos(data_get($orders,'*.code'));
    }

    /**
     * @param OracleDOCOrderHeader $orderHeader
     * @return array|Collection|\Tightenco\Collect\Support\Collection
     */
    public function 返回创建数组($orderHeader)
    {
        if($orderHeader->sostatus == 90){return [];}
        $actAllocationDetails = $orderHeader->actAllocationDetails->collect();
        $innerParams = collect();
        $actAllocationDetails->each(function($detail)use(&$innerParams){
            $sku =  $detail->sku;
            $amount =  $detail->qty_each;
            $logistic_number = $detail->picktotraceid;
            $params = [
                'ownerCode' => $detail->customerid,
                'orderNo' => $detail->orderno,
                'sku' => $sku,
                'amount' => $amount,
                'logistic_number' => $logistic_number,
            ];

            $innerParam = $innerParams->where('logistic_number',$logistic_number)->where('sku',$sku)->first();
            if($innerParam ?? false){
                $bool = false;
                $innerParams = $innerParams->map(function($param)use($innerParam,$amount,&$bool){
                    if($innerParam['logistic_number'] == $param['logistic_number'] &&
                        $innerParam['sku'] == $param['sku'] && !$bool){
                        $param['amount'] += $amount;
                        $bool = !$bool;
                    }
                    return $param;
                });
            }else{
                $innerParams->push($params);
            }
        });
        return $innerParams;
    }

    public function 返回创建数组_WMS订单($orderHeaders)
    {
        $innerParams = [];
        foreach ($orderHeaders as $orderHeader) {
            $innerParam = $this->返回创建数组($orderHeader);
            foreach ($innerParam as $param) {
                $innerParams[] = $param;
            }
        }
        return $innerParams;
    }
    /**
     * @param array $innerParams
     * @return array
     */
    public function 生成OrderPackageCommodities_基于创建数组($innerParams)
    {
        if(!$innerParams){return [];}
        if(is_array($innerParams) && count($innerParams) == 0){return [];}
        $commodity_map = $this->返回Commodity数组_根据数组中sku($innerParams);
        $orderPackages_map = app(OrderPackageService::class)->返回OrderPackage数组_根据数组中的快递单号($innerParams);
        $createParams = [];
        $dataTime = Carbon::now()->format('Y-m-d H:i:s');
        foreach ($innerParams as $innerParam) {
            $key = ' ownerCode='.($innerParam['ownerCode'] ?? '').' sku='.($innerParam['sku'] ?? '');
            $commodity = $commodity_map[$key] ?? null;
            $orderPackage = $orderPackages_map[$innerParam['logistic_number']] ?? '';
            $createParams[] = [
                'order_package_id' => $orderPackage->id ?? '',
                'commodity_id' => $commodity->id ?? null,
                'amount' => $innerParam['amount'],
                'created_at' => $dataTime,
                'updated_at' => $dataTime,
            ];
        }
        return $createParams;
    }

    /**
     * @param $orderHeaders
     */
    public function 更新OPC_根据WMS订单($orderHeaders)
    {
        if(!$orderHeaders){return ;}
        if(count($orderHeaders) == 0){return ;}
        app(CommodityService::class)->getByWmsOrders($orderHeaders);
        $orderPackageCommodities = $this->getByWmsOrder($orderHeaders);
        $OPCCollects = $this->将orderPackageCommodity抽象成数组($orderPackageCommodities);
        $creatParams = $this->返回创建数组_WMS订单($orderHeaders);
        $orderNos = $this->数据重组($OPCCollects,$creatParams);
        $updateParams= collect();$deleteIds = [];$insertParams =[];
        foreach ($orderNos as $orderNo) {
            $OPCCollect = $OPCCollects[$orderNo] ?? null;
            $creatParam = $creatParams[$orderNo];
            $retain[] = $this->删选可以保留的OrderPackageCommodities($OPCCollect,$creatParam);

            $collect = $this->删选需要修改的OrderPackageCommodities($OPCCollect,$creatParam);

            $ids = $this->删选出删除的OrderPackageCommodities($OPCCollect,$creatParam);

            $insertParam = $this->删选出需要添加的OrderPackageCommodities($OPCCollect,$creatParam);

            $deleteIds = array_merge($deleteIds,$ids);

            foreach ($collect as $item) {
                $updateParams->push($item);
            }
            foreach ($insertParam as $item) {
                $insertParams[]= $item;
            }

        }
        $this->根据更新数组进行更新($updateParams);
        $this->删除OPC以及对应的追踪件($deleteIds);
        $creatParams = $this->生成OrderPackageCommodities_基于创建数组($insertParams);
        $this->create($creatParams);
    }

    /**
     * @param Collection $orderPackageCommodities
     * @return Collection|\Tightenco\Collect\Support\Collection
     */
    public function 将orderPackageCommodity抽象成数组($orderPackageCommodities)
    {
        /** @var DataHandlerService $dataHandlerService */
        $dataHandlerService = app(DataHandlerService::class);
        $collect = collect();
        $ownerIds = array_unique(data_get($orderPackageCommodities,'*.commodity.owner_id'));
        $owners = Owner::query()->whereIn('id',$ownerIds)->get();
        $owner_id_map = $dataHandlerService->dataHeader(['id'],$owners);
        foreach ($orderPackageCommodities as $orderPackageCommodity) {
            $owner = $dataHandlerService->getKeyValue(['id'=>$orderPackageCommodity->commodity->owner_id ?? ''],$owner_id_map);
            $params = [
                'id' => $orderPackageCommodity->id,
                'ownerCode' => $owner->code,
                'orderNo' => $orderPackageCommodity->package->order->code,
                'sku' => $orderPackageCommodity->commodity->sku,
                'amount' => $orderPackageCommodity->amount,
                'logistic_number' => $orderPackageCommodity->package->logistic_number,
            ];
            $collect->push($params);
        }
        return $collect;
    }

    public function 数据重组(&$OPCCollects,&$params)
    {
        $collect_map = [];$params_map = [];$order_no_map = [];

        foreach ($OPCCollects as $item) {
            $orderNo = $item['orderNo'];
            if(!isset($collect_map[$orderNo])){$collect_map[$orderNo] = collect();}
            $collect_map[$orderNo]->push($item);
        }

        foreach ($params as $param) {
            $orderNo =  $param['orderNo'];
            if(!isset($params_map[$orderNo])){$params_map[$orderNo] = collect();}
            $order_no_map[] = $orderNo;
            $params_map[$orderNo]->push($param);
        }
        $order_no_map = array_unique($order_no_map);
        $OPCCollects = $collect_map;
        $params = $params_map;
        return $order_no_map;
    }

    public function 删选可以保留的OrderPackageCommodities(&$OPCCollect,&$params)
    {
        $retain = collect();
        if($OPCCollect == null){return $retain;}
        $map = [];
        foreach ($params as $param) {
            $key = ' logistic_number='.$param['logistic_number'].' sku='.$param['sku'].' amount='.$param['amount'];
            if(! isset($map[$key])){
                $map[$key] = [];
            }
            $map[$key][] = $param;
        }

        foreach ($OPCCollect as $item) {
            $key = ' logistic_number='.$item['logistic_number'].' sku='.$item['sku'].' amount='.$item['amount'];
            if(isset($map[$key]) && count($map[$key]) > 0){
                $value = $map[$key][0];
                array_shift($map[$key]);
                $params->filter(function($param)use($value){
                    return count(array_diff_assoc($param,$value)) != 0 ;
                });
                $retain->push($value);
            }
        }

        return $retain;
    }

    public function 删选出需要添加的OrderPackageCommodities(&$OPCCollect,&$params)
    {
        $innerParam = [];
        $OPCmap = [];
        if($OPCCollect == null){return $params;}
        foreach ($OPCCollect as $item) {
            $key = ' logistic_number='.$item['logistic_number'].' sku='.$item['sku'].' amount='.$item['amount'];
            if(!isset($OPCmap[$key])){
                $OPCmap[$key][] = [];
            }
            $OPCmap[$key][] = $item;
        }
        $paramsMap = [];
        foreach ($params as $param) {
            $key = ' logistic_number='.$param['logistic_number'].' sku='.$param['sku'].' amount='.$param['amount'];
            if(!isset($OPCmap[$key])){
                $paramsMap[$key][] = [];
            }
            $paramsMap[$key][] = $param;
        }
        $paramsCopy = $params->collect();
        foreach ($paramsCopy as $param) {
            $key = ' logistic_number='.$param['logistic_number'].' sku='.$param['sku'].' amount='.$param['amount'];
            if(!(isset($OPCmap[$key]) && count($OPCmap[$key]) == 0)){
                $innerParam[] = $param;
                $OPCCollect->filter(function($item)use($param){
                    return !($item['logistic_number'] == $param['logistic_number'] &&$item['sku'] == $param['sku'] &&$item['amount'] == $param['amount'])  ;
                });
            }
        }
        return $innerParam;
    }

    public function 删选需要修改的OrderPackageCommodities(&$OPCCollect,&$params)
    {
        $update = collect();
        $map = [];
        if($OPCCollect == null){return $update;}
        foreach ($OPCCollect as $item) {
            $key = ' logistic_number='.$item['logistic_number'].' sku='.$item['sku'];
            if(!isset($map[$key])){$map[$key] = [];}
            $map[$key][] = $item;
        }
        $paramsCopy = $params->collect();
        foreach ($paramsCopy as $param) {
            $key = ' logistic_number='.$param['logistic_number'].' sku='.$param['sku'];
            if(!isset($map[$key])){continue;}
            $item = array_shift($map[$key]);
            $params = $params->filter(function($value)use($item){
                return !($value['logistic_number'] == $item['logistic_number'] && $value['sku'] == $item['sku'])  ;
            });
            $OPCCollect  = $OPCCollect->filter(function($opc)use($item){
                return !($opc['logistic_number'] == $item['logistic_number'] && $opc['sku'] == $item['sku'] && $opc['amount'] == $item['amount'] && $item['id'] == $opc['id']);
            });
            if($item['amount']!= $param['amount']){
                $param['id'] = $item['id'];
                $update->push($param);
            }
        }

        return $update;
    }

    public function 删选出删除的OrderPackageCommodities(&$OPCCollect,&$params)
    {
        $deleteIds = [];
        $map = [];
        if($OPCCollect == null){return $deleteIds;}
        foreach ($params as $item) {
            $key = ' logistic_number='.$item['logistic_number'].' sku='.$item['sku'].' amount='.$item['amount'];
            if(!isset($map[$key])){
                $map[$key] = [];
            }
            $map[$key][] = $item;
        }
        foreach ($OPCCollect as $opc) {
            $key = ' logistic_number='.$opc['logistic_number'].' sku='.$opc['sku'].' amount='.$opc['amount'];
            if(!isset($map[$key]) || count($map[$key])==0){
                $deleteIds[] = $opc['id'];
            }
        }

        return $deleteIds;
    }

    public function 删除OPC以及对应的追踪件($ids)
    {
        if(!$ids){return;}
        $OPCs = OrderPackageCommodities::query()->whereIn('id', $ids)->get();
        if($OPCs->count() == 0){return;}
        try {
            OrderPackageCommodities::query()->whereIn('id', $ids)->delete();
            app('LogService')->log(__METHOD__, __FUNCTION__, '删除OrderPackageCommodities ' . count($ids) . json_encode($OPCs));
            $orderTracking = OrderTracking::query()->whereIn('order_package_commodity_id',$ids)->get();
            app(OrderTrackingService::class)->deleteOrderTracings($orderTracking);
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__, __FUNCTION__, '删除OrderPackageCommodities ' . count($ids) . json_encode($OPCs).$e->getMessage().$e->getTraceAsString());
        }
    }

    public function 根据更新数组进行更新($updateParams)
    {
        if(!isset($updateParams)){return;}
        if(is_array($updateParams) && count($updateParams)==0){return;}
        $commodity_map = $this->返回Commodity数组_根据数组中sku($updateParams);
        $orderPackages_map = app(OrderPackageService::class)->返回OrderPackage数组_根据数组中的快递单号($updateParams);
        $dataTime = Carbon::now()->format('Y-m-d H:i:s');
        $update_params = [['id','commodity_id','order_package_id','amount','updated_at']];
        foreach ($updateParams as $updateParam) {
            $commodity_key = ' ownerCode='.($updateParam['ownerCode'] ?? '').' sku='.($updateParam['sku'] ?? '');
            $commodity = $commodity_map[$commodity_key] ?? '';
            $orderPackage = $orderPackages_map[$updateParam['logistic_number']] ?? '';
            $update_params[] = [
                'id' => $updateParam['id'],
                'commodity_id' => $commodity->id ?? '',
                'order_package_id' => $orderPackage->id ?? '',
                'amount' => $updateParam['amount'],
                'updated_at' => $dataTime
            ];
        }
        $this->batchUpdate($update_params);
    }

    private function 返回Commodity数组_根据数组中sku($params)
    {
        $skus = array_unique(data_get($params,'*.sku'));
        $commodities = Commodity::query()->with('owner')->whereIn('sku',$skus)->get();
        $commodity_map = [];
        foreach ($commodities as $commodity) {
            $key = ' ownerCode='.($commodity->owner->code ?? '').' sku='.$commodity->sku;
            $commodity_map[$key] = $commodity;
        }
        return $commodity_map;
    }

    public function syncOrderPackageCommodities($orderHeaders)
    {
        $this->syncOrderPackageCommoditiesByOrderHeaders($orderHeaders);
    }

    public function syncOrderPackageCommoditiesByOrderHeaders(&$orderHeaders)
    {
        /**
         * @var DataHandlerService $dataHandService
         * @var CommodityService $commodityService
         * @var OrderPackageService $orderPackageService
         * @var OwnerService $ownerService
         */
        $dataHandService = app('DataHandlerService');
        $commodityService = app('CommodityService');
        $orderPackageService  = app( 'OrderPackageService');
        $ownerService  = app( 'OwnerService');
        if(!$orderHeaders)return ;

        $owner_codes = [];$sku_codes = [];$map = [];
        foreach ($orderHeaders as $orderHeader) {
            $Order_Details = $orderHeader->oracleDOCOrderDetails;
            $Order_Details->each(function($item)use(&$owner_codes,&$sku_codes,&$map){
                $owner_codes[$item['customerid']] = $item['customerid'];
                $sku_codes[$item['sku']] = $item['sku'];
                $value = [
                    'owner_code'=> $item['customerid'],
                    'sku' => $item['sku']
                ];
                $key = json_encode($value);
                $map[$key] = $value;
            });
        }
        if(count($owner_codes) ==0 || count($sku_codes) == 0)return ;
        $owners = $ownerService->getOwnerByCodes($owner_codes);
        $commodities = $commodityService->getCommoditiesByMaps($map);   // 预先处理     3s
        $orderPackages = $orderPackageService->getByWmsOrders($orderHeaders);
        $orderCommodities = $this->getByWmsOrder($orderHeaders);
        $owner_id_map=[];
        foreach ($owners as $owner) {
            $owner_id_map[$owner['id']] = $owner;
        }

        $package_map = $dataHandService->dataHeader(['logistic_number'],$orderPackages);

        $orderCommodities = $this->regroupOrderCommodities($orderCommodities);

        $orderAllocationDetails = $this->regroupWmsOrderAllocationDetails($orderHeaders);
        $del_orderCommodities  =[];

        $update_params =$this->filterUpdateParams($orderAllocationDetails,$orderCommodities,$del_orderCommodities);                  // 修改

        $inner_params = $this->filterInnerParams($orderAllocationDetails,$orderCommodities);                                            // 创建

        $delete_params = $this->filterDeleteParams($orderAllocationDetails,$orderCommodities);                                           // 删除
        unset($orderAllocationDetails,$orderCommodities);
        if(count($inner_params)>0)
            $this->createOrderCommodities($inner_params,$package_map,$commodities,$owner_id_map);  // 创建 3s
        unset($inner_params,$package_map,$commodities,$owner_id_map);
        if(count($update_params)>0)
            $this->updateOrderCommodities($update_params);              // 更新
        unset($update_params);
        if(count($delete_params)>0)
            $this->deleteOrderCommodities($delete_params);              // 删除
        unset($delete_params);
        if(count($del_orderCommodities)>0)
            $this->deleteOrderCommodities($del_orderCommodities);       // 删除
        unset($del_orderCommodities);
    }

    public function regroupOrderCommodities(&$orderCommodities):array
    {
        $params = [];
        $orderCommodities->each(function($orderCommodity)use(&$params){
            $order_no = $orderCommodity->package->order->code ?? '';
            $logistic_number = $orderCommodity->package->logistic_number ?? '';
            $sku = $orderCommodity->commodity->sku ?? '';
            $key = ' orderno='.$order_no.' logsitic_number='.$logistic_number.' sku='.$sku.' ';
            $params[$key][] = [
                'id' =>$orderCommodity->id,
                'orderno'=>$order_no,
                'logistic_number'=>$logistic_number,
                'sku' => $sku,
                'amount' => $orderCommodity->amount,
                'order_package_id'=>$orderCommodity->package->id ?? '',
                'commodity_id'=>$orderCommodity->commodity->id ?? '',
            ];
        });
        return $params;
    }

    public function regroupWmsOrderAllocationDetails(&$orderHeaders):array
    {
        /**
         * @var OracleDOCOrderHeader $orderHeader
         */
        $params =[];
        foreach ($orderHeaders as $orderHeader) {
            $order_no = $orderHeader->orderno;
            $actAllocationDetails = $orderHeader->actAllocationDetails ?? [];
            if($orderHeader['sostatus'] == '90'){
                $logistic_number = $orderHeader['soreference5'];
                if($logistic_number == '' ) $logistic_number= $orderHeader['orderno'];
                $oracleDOCOrderDetails = $orderHeader->oracleDOCOrderDetails ?? [];
                $oracleDOCOrderDetails->each(function($item)use(&$params,$order_no,$logistic_number){
                    $sku = $item->sku;
                    $key = ' orderno='.$order_no.' logsitic_number='.$logistic_number.' sku='.$sku.' ';
                    if(isset($params[$key])){
                        $params[$key]['amount']+= $item->qty_each;
                    }else{
                        $params[$key] = [
                            'orderno'=>$item->orderno,
                            'logistic_number'=>$logistic_number,
                            'sku' => $sku,
                            'amount' => $item->qtyordered,
                            'owner_code' => $item->customerid
                        ];
                    }
                });
            }else{
                $actAllocationDetails->each(function($item)use(&$params,$order_no){
                    $logistic_number = $item->picktotraceid;
                    $sku = $item->sku;
                    $key = ' orderno='.$order_no.' logsitic_number='.$logistic_number.' sku='.$sku.' ';
                    if(isset($params[$key])){
                        $params[$key]['amount']+= $item->qty_each;
                    }else{
                        $params[$key] = [
                            'orderno'=>$item->orderno,
                            'logistic_number'=>$item->picktotraceid,
                            'sku' => $sku,
                            'amount' => $item->qty_each,
                            'owner_code' => $item->customerid
                        ];
                    }
                });
            }
        }
        return $params;
    }

    public function filterUpdateParams(&$orderAllocationDetails,&$orderCommodities,&$del_orderCommodities):array
    {
        $update_params = [];
        foreach ($orderCommodities as $key=>$orderCommodity) {
            if(isset($orderAllocationDetails[$key])){
                if(count($orderCommodity) == 1  && $orderAllocationDetails[$key]['amount'] != $orderCommodity[0]['amount']){
                    $update_params[$key] = $orderCommodity[0];
                    $update_params[$key]['amount'] = $orderAllocationDetails[$key]['amount'];
                }elseif(count($orderCommodity)>1){
                    $update_params[$key] = array_shift($orderCommodity);
                    $update_params[$key][0]['amount'] = $orderAllocationDetails[$key]['amount'];
                    collect($orderCommodity)->each(function($item)use(&$del_orderCommodities){
                        $del_orderCommodities[] = $item;
                    });
                }
                unset($orderCommodities[$key],$orderAllocationDetails[$key]);
            }
        }
        return $update_params;
    }

    public function filterInnerParams(&$orderAllocationDetails,&$orderCommodities):array
    {
        $inner_params = [];
        foreach ($orderAllocationDetails as $key=>$orderAllocationDetail) {
            if(!($orderCommodities[$key] ?? false)){
                $inner_params[] = $orderAllocationDetail;
                unset($orderCommodities[$key],$orderAllocationDetail);
            }
        }
        return $inner_params;
    }

    public function filterDeleteParams(&$orderAllocationDetails,&$orderCommodities):array
    {
        $del_params = [];
        foreach ($orderCommodities as $key => $orderCommodity) {
            if(!isset($orderAllocationDetails[$key])){
                collect($orderCommodity)->each(function ($item)use(&$del_params){
                    $del_params[] = $item;
                });
                unset($orderCommodities[$key]);
            }
        }
        return $del_params;
    }

    public function createOrderCommodities(&$inner_params,&$package_map,&$commodities,&$owner_id_map)
    {
        /** @var DataHandlerService $dataHandlerService */
        $dataHandlerService  = app('DataHandlerService');
        $commodity_map = (function()use(&$commodities,&$owner_id_map){
            $map = [];
            foreach ($commodities as $commodity) {
                $owner = $owner_id_map[$commodity['owner_id']] ;
                $key = ' owner='.$owner->code.' sku='.$commodity->sku;
                $map[$key] = $commodity;
            }
            return $map;
        })();
        $create_params =[];
        $date = Carbon::now();
        foreach ($inner_params as $inner_param) {
            if($inner_param['logistic_number'] === '*' || $inner_param['logistic_number'] === ' ')continue;
            $package = $dataHandlerService->getKeyValue(['logistic_number'=>$inner_param['logistic_number']],$package_map);
            if(!$package)continue;
            $commodity = $commodity_map[' owner='.$inner_param['owner_code'].' sku='.$inner_param['sku']] ?? null;
            $create_params[] = [
                'order_package_id'=>$package->id,
                'commodity_id'=>$commodity->id ?? null,
                'amount' => $inner_param['amount'],
                'created_at' => $date,
                'updated_at' => $date
            ];
        }
        if(count($create_params)>0){
            $inner_array = array_chunk($create_params,5000);
            foreach ($inner_array as $item) {
                try {
                    $bool = $this->insert($item);
                    LogService::log(__METHOD__, __FUNCTION__, '批量添加 orderCommodity ' . ($bool > 0 ? 'SUCCESS' : 'FAULT') . " || " . count($item) . ' || ' . json_encode($create_params));
                } catch (\Exception $e) {
                    LogService::log(__METHOD__,__FUNCTION__.'error','批量添加 orderCommodity ERROR'." || ".count($item).' || '.json_encode($item). ' || '.json_encode($e->getMessage()). ' || '.json_encode($e->getTraceAsString()));
                }
            }
        }
        unset($create_params,$commodity_map);
    }

    public function updateOrderCommodities(&$orderCommodities)
    {
        if(!$orderCommodities)return ;
        $updated_at = Carbon::now();
        $update_params = [['id','order_package_id','commodity_id','amount','updated_at']];
        foreach ($orderCommodities as $orderCommodity) {
            $update_params[] = [
                'id' => $orderCommodity['id'] ?? '',
                'order_package_id'=>$orderCommodity['order_package_id'] ?? '',
                'commodity_id'=>$orderCommodity['commodity_id'] ?? '',
                'amount' => $orderCommodity['amount'],
                'updated_at' => $updated_at
            ];
        }
        if(count($update_params)>1)
            $this->batchUpdate($update_params);

        unset($update_params);
    }

    public function deleteOrderCommodities(&$orderCommodities){
        /** @var OrderTrackingService $orderTrackingService */
        $orderTrackingService = app('OrderTrackingService');
        if(!$orderCommodities)return;
        if(count($orderCommodities)==0)return;
        try {
            $ids = data_get($orderCommodities, '*.id');
            if(count($ids) >0){
                $bool = OrderPackageCommodities::query()->whereIn('id', $ids)->delete();
                $orderTrackings = OrderTracking::query()->whereIn('order_package_commodity_id',$ids)->get();
                $orderTrackingService->deleteOrderTracings($orderTrackings);
                LogService::log(__METHOD__, __FUNCTION__, '批量删除 OrderCommodity '  . ($bool > 0 ? 'SUCCESS' : 'FAULT') .'||' .count($orderCommodities)  . ' || ' . json_encode($orderCommodities));
            }
        } catch (\Exception $e) {
            LogService::log(__METHOD__, __FUNCTION__.' error', '批量删除 OrderCommodity Error' . ' || ' . json_encode($e->getMessage()) . ' || ' . json_encode($e->getTraceAsString()));
        }
        unset($orderCommodities);
    }
}
