<?php

namespace App\Imports;

use App\Commodity;
use App\OracleBasSKU;
use App\OracleDOCOrderHeader;
use App\Order;
use App\OrderPackage;
use App\OrderPackageCommodities;
use App\OrderTracking;
use App\Owner;
use App\Services\common\DataHandlerService;
use App\Services\OracleDOCOrderHeaderService;
use App\Services\OrderService;
use App\Services\OrderTrackingService;
use App\Shop;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Concerns\ToCollection;

class OrderTrackingImport implements ToCollection
{

    public $shops = [];
    public $commodities = [];
    public $bas_skus =[];
    public $owner = null;
    public $order = [];
    public $orderPackages = [];
    public $order_is = [];
    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        /**
         * @var OrderTrackingService $service
         * @var OrderService $orderService
         * @var DataHandlerService $dataHandlerService
         * @var Order $order
         * @var OrderPackage $package
         * @var Commodity $commodity
         */
        $owner = Owner::query()->where('name','安桥主品')->first();
        $this->owner = $owner;
        $collection->shift();
        // 1 450 3 400
        $array =  $collection->chunk(450);
        foreach ($array as $item_arr) {
            $inner_params = [];
            foreach ($item_arr as $items) {
                $order = $this->getOrder($items[1], $items);
                $orderPackageCommodities = $this->getOrderPackageCommodities($items);
                $bas_sku = $this->getBasSku((string)$items[6]);
                $gross_weight = round(($bas_sku->grossweight ?? 0) * $orderPackageCommodities->amount, 2);
                $bulk = round(($bas_sku->cube ?? 0) * $orderPackageCommodities->amount, 2);
                $inner_params[] = [
                    'order_package_commodity_id' => $orderPackageCommodities->id,
                    'owner_id' => $owner->id,
                    'web_order_number' => $items[2],
                    'order_client_code' => $order->client_code,
                    'gross_weight' => $gross_weight,
                    'bulk' => $bulk,
                ];
            }
            $this->order = [];
            $this->bas_skus = [];
            $this->shops = [];
            $this->order = [];
            $this->orderPackages = [];
            try {
                OrderTracking::query()->insert($inner_params);
                app('LogService')->log(__METHOD__,__FUNCTION__,'批量创建 OrderTracking'.' || '.json_encode($inner_params));
            } catch (\Exception $e) {
                app('LogService')->log(__METHOD__,'ERROR '.__FUNCTION__,'批量创建 OrderTracking ERROR'.json_encode($e->getMessage()).json_encode($e->getTraceAsString()).' || '.' || '.json_encode($inner_params));
            } finally {
                unset($inner_params,$item_arr);
            }
        }

    }

    public function getOrderPackageCommodities($items){
        $packages = $this->getPackage($items[1],$items);
        $packages = collect($packages);
        if(!$packages||$packages->isEmpty()){
            app('LogService')->log(__METHOD__,__FUNCTION__,'导入空值：'.json_encode($packages));
        };
        $orderPackageCommodities = null;
        if(count($packages)>1){
            $bool = false;
            foreach ($packages as $package) {
                foreach (($package->commodities ?? []) as $commodities) {
                    if (isset($commodities->commodity) && $bool == false) {
                        if ($commodities->commodity->sku == $items[6] && $commodities->amount == $items[8]) {
                            $package->commodities = $package->commodities->filter(function($item)use($commodities){
                                return $item->id != $commodities->id;
                            });
                            return $commodities;
                        }
                    }
                }
            }
        }elseif(count($packages)==1){
            $bool = false;
            foreach ($packages as $package) {
                foreach (($package->commodities ?? []) as $commodities) {
                    if (isset($commodities->commodity) && $bool == false) {
                        if ($commodities->commodity->sku == $items[6] && $commodities->amount == $items[8]) {
                            $package->commodities = $package->commodities->filter(function($item)use($commodities){
                                return $item->id != $commodities->id;
                            });
                            $this->orderPackages[$items[1]] = $packages;
                            return $commodities;
                        }
                    }
                }
            }
        }

        if ($orderPackageCommodities == null) {
            $package = $packages->first();
            if(!$package){
                $order=$this->order[$items[1]];
                $package=$order->package;
            }
            $commodity = $this->getCommodity((string)$items[6], $items);
            $orderPackageCommodities = OrderPackageCommodities::query()->create(['order_package_id' => $package['id'], 'commodity_id' => $commodity->id, 'amount' => $items[8]]);
        }
        return $orderPackageCommodities;
    }


    public function getOrderHeader($soReference1){
        return  $orderHeader = 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.SOReference1',$soReference1)
            ->first();
    }

    public function getShop($name){
        if(!empty($this->shops[$name])){
            return $this->shops[$name];
        }else{
            $shop = Shop::query()->firstOrCreate(['owner_id'=>$this->owner->id,'name'=>$name]);
            $this->shops[$name] = $shop;
            return $shop;
        }
    }
    public function getCommodity(string $sku,&$items){
        if(!empty($this->commodities[(string)$sku])){
            return $this->commodities[(string)$sku];
        }else{
            $bas_sku = $this->getBasSku((string)$sku);
            if($bas_sku == null){
                $commodity = Commodity::query()->firstOrCreate(['sku'=>$sku,'name'=>$items[7],'owner_id'=>$this->owner->id]);
                $this->commodities[(string)$sku] = $commodity;
                return $commodity;
            }
            $commodity = Commodity::query()->firstOrCreate(['sku'=>$bas_sku['sku'],'name'=>$bas_sku['descr_c'],'owner_id'=>$this->owner->id]);
            $this->commodities[(string)$sku] = $commodity;
            return $commodity;
        }
    }

    public function getBasSku($sku){
        if(!empty($this->bas_skus[(string)$sku])){
            return $this->bas_skus[(string)$sku];
        }else{
            $bas_sku = OracleBasSKU::query()->selectRaw('BAS_SKU.sku,BAS_SKU.customerid,BAS_SKU.grossweight,BAS_SKU.cube,BAS_SKU.descr_c')->where('sku',(string)$sku)->where('customerid',$this->owner->code)->first();
            $this->bas_skus[(string)$sku] = $bas_sku;
            return $bas_sku;
        }
    }

    public function getOrder($client_no,&$items){
        /**
         * @var OrderService $orderService
         */
        $orderService = app('OrderService');
        if( !empty($this->order[$client_no])){
            return $this->order[$client_no];
        }

        $order = Order::query()->with('packages.commodities.commodity')->where('client_code',$client_no)->first();
        if($order){
            $this->order[$client_no] = $order;
//            if(!$order)app('LogService')->log(__METHOD__,__FUNCTION__,'get1:'.json_encode($order));
            return $order;
        }else{
            $orderHeader = $this->getOrderHeader($client_no);
            if($orderHeader){
                $orderService->createOrFindOrderInfo($orderHeader);
                $order = Order::query()->with('packages.commodities.commodity')->where('client_code',$client_no)->first();
                if(!$order){
                    $shop = $this->getShop($items[5]);
                    $order = app("OrderService")->createOrder([
                        'code'=>'null'.Str::uuid(),'client_code' => $items[1],'web_order_number' => $items[2],'shop_id'=>$shop->id
                    ]);
                }
                $this->order[$client_no] = $order;
                unset($orderHeader);
//                if(!$order)app('LogService')->log(__METHOD__,__FUNCTION__,'get2:'.json_encode($order));
                return $order;
            }else{
                $shop = $this->getShop($items[5]);
                $order = app("OrderService")->createOrder([
                    'code'=>'null'.Str::uuid(),'client_code' => $items[1],'web_order_number' => $items[2],'shop_id'=>$shop->id
                ]);
//                app('LogService')->log(__METHOD__,__FUNCTION__,'create1:'.json_encode($order));
                $this->order[$client_no] = $order;
//                if(!$order)app('LogService')->log(__METHOD__,__FUNCTION__,'get3:'.json_encode($order));
                return $order;
            }
        }
    }

    public function getPackage($client_code,&$items)
    {
        if(!empty($this->orderPackages[$client_code])){
            return $this->orderPackages[$client_code];
        }else{
            $order = $this->getOrder($client_code,$items);
            if($order && $order->packages->count() > 0 ){
                $this->orderPackages[$client_code] = $order->packages;
                return $order->packages;
            }else{
                $package = OrderPackage::query()->create(['order_id'=>$order->id,'logistic_number'=>'null_'.Str::uuid()]);
                $list = collect();
                $list->push($package);
                $this->orderPackages[$client_code] = $list;
                return $list;
            }
        }
    }
}
