<?php

namespace App\Services;

use App\Commodity;
use App\Http\Controllers\CommodityController;
use App\CommodityBarcode;
use App\OracleBasSKU;
use App\Owner;
use App\Services\common\BatchUpdateService;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;

Class CommodityService
{
    public function firstOrCreate($param,$column = null):Commodity{
        if ($column) return Commodity::query()->firstOrCreate($param,$column);
        return Commodity::query()->firstOrCreate($param);
    }
    public function updateOrCreate($param,$column = null){
        if ($column) return Commodity::query()->updateOrCreate($param,$column);
        return Commodity::query()->updateOrCreate($param);
    }

    public function first(array $params, $with = null){
        $commodity = Commodity::query();
        if ($with)$commodity->with($with);
        foreach ($params as $column => $value){
            if (!is_array($value))$commodity->where($column,$value);
            else $commodity->whereIn($column,$value);
        }
        return $commodity->first();
    }

    public function get(array $params){
        $query = Commodity::query()->with('barcodes');
        if ($params["owner_id"] ?? false){
            $query->where("owner_id", $params["owner_id"]);
        }
        if ($params["sku"] ?? false){
            if (!is_array($params["sku"]))$params["sku"] = [$params["sku"]];
            $query->whereIn('sku', $params["sku"]);
        }
        return $query->get();
    }

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


    public function getOwnerCommodities(array $params){
        $query = Commodity::query();
        foreach ($params as $column => $value){
            if (!is_array($value)) $query->where($column,$value);
            else $query->whereIn($column,$value);
        }
        return $query->get();
    }

    /* 批量更新 */
    public function batchUpdate(array $params){
        return app(BatchUpdateService::class)->batchUpdate('commodities', $params);
    }

    /* 根据货主条形码查找商品 */
    private function ownerBarcodeSeekCommodityQuery(Builder $query, array $ownerParam, $barcode){
        $query->whereHas('owner',function ($builder)use($ownerParam){
            foreach ($ownerParam as $column => $param){
                $builder->where($column, $param);
            }
        });
        $query->whereHas('barcodes',function ($builder)use($barcode){
            if (is_array($barcode))$builder->whereIn('code',$barcode);
            else $builder->where('code',$barcode);
        });
        return $query;
    }
    public function ownerBarcodeSeekCommodityFirst(array $ownerParam, $barcode, $with = null){
        $commodity = Commodity::query();
        if ($with) $commodity->with($with);
        $commodity = $this->ownerBarcodeSeekCommodityQuery($commodity, $ownerParam, $barcode);
        return $commodity->first();
    }
    public function ownerBarcodeSeekCommodityGet(array $ownerParam, $barcode, $isNullSku = false){
        $commodities = Commodity::query()->with('barcodes');
        if ($isNullSku)$commodities->whereNull('sku');
        $commodities = $this->ownerBarcodeSeekCommodityQuery($commodities, $ownerParam, $barcode);
        return $commodities->get();
    }

    /* 通过货主代码与条形码寻找FLUX商品补充至WMS 单条*/
    public function ownerAndBarcodeFirstOrCreate(Owner $owner,$barcode){
        $wmsCommodity = app('OracleBasSkuService')->first(['customerid'=>$owner->code, 'barcode'=>$barcode]);
        if (!$wmsCommodity) return null;

        $commodity = $this->firstOrCreate(['owner_id'=>$owner->id, 'sku'=>$wmsCommodity->sku],[
            "name" => $wmsCommodity->descr_c,
            "sku" => $wmsCommodity->sku,
            "owner_id" => $owner->id,
            "length" => $wmsCommodity->skulength,
            "width" => $wmsCommodity->skuwidth,
            "height" => $wmsCommodity->skuhigh,
            "volumn" => $wmsCommodity->cube,
        ]);
        if ($wmsCommodity->alternate_sku1)app('CommodityBarcodeService')->first([
            'commodity_id' => $commodity->id,
            'code' => $wmsCommodity->alternate_sku1,
        ]);
        if ($wmsCommodity->alternate_sku2)app('CommodityBarcodeService')->first([
            'commodity_id' => $commodity->id,
            'code' => $wmsCommodity->alternate_sku2,
        ]);
        return $commodity;
    }

    public function create(array $params){
        return Commodity::query()->create($params);
    }

    public function getByWmsOrders($orderHeaders){
        if(!$orderHeaders) return null;
        $customerId_sku_map = [];
        foreach ($orderHeaders as $orderHeader) {
            $oracleDOCOrderDetails = $orderHeader->oracleDOCOrderDetails;
            foreach ($oracleDOCOrderDetails as $oracleDOCOrderDetail) {
                $value = [
                    'owner_code' => $oracleDOCOrderDetail->customerid,
                    'sku'=> $oracleDOCOrderDetail->sku
                ];
                if(!in_array($value,$customerId_sku_map)){
                    $customerId_sku_map[] = $value;
                }
            }
        }

        $owner_codes = array_diff(array_unique(data_get($customerId_sku_map,'*.owner_code')),['','*',null]) ;
        if(!$owner_codes) return null;

        $owners = Owner::query()->whereIn('code',$owner_codes)->get();

        $owners_code_map = [];
        $owners_id_map = [];
        foreach ($owners as $owner) {
            $owners_code_map[$owner->code] = $owner;
            $owners_id_map[$owner->id] = $owner;
        }
        $orderHeader_sku = array_diff(array_unique(data_get($customerId_sku_map,'*.sku')),['','*',null]) ;
        $commodities = Commodity::query()
            ->whereIn('owner_id',data_get($owners,'*.id'))
            ->whereIn('sku',$orderHeader_sku)
            ->groupBy('owner_id','sku')  //*!!!!!!!!
            ->get();

        if($commodities->count() < count($customerId_sku_map)){
            $commoditiesInWAS索引_sku = [];
            foreach ($commodities as $commodityInWms) {
                $owner = $owners_id_map[$commodityInWms->owner_id] ?? '';
                if(!$owner)continue;
                $key ='owner_cod='.$owner['code'].' sku='.$commodityInWms->sku;
                $commoditiesInWAS索引_sku[$key]=$commodityInWms;
            }
            $commodities需要新增=[];
            foreach ($customerId_sku_map as $commodityInWms) {
                $key ='owner_cod='.$commodityInWms['owner_code'].' sku='.$commodityInWms['sku'];
                if($commoditiesInWAS索引_sku[$key] ?? false) continue;
                $commodities需要新增[$key] = $commodityInWms;
            }
            $commodity_set = $this->createCommodities($commodities需要新增,$owners_code_map);
            $commodities = $commodities->concat($commodity_set);
        }
        return  $commodities;
    }

    public function createCommodities($params,$owners_code_map)
    {
        if(!$params) return [];
        $bas_sku_arr = OracleBasSKU::query()
            ->selectRaw('customerid,sku,descr_c,skulength,skuwidth,skuhigh,cube')
            ->whereIn('CustomerID',data_get($params,'*.owner_code'))
            ->whereIn('Sku',data_get($params,'*.sku'))
            ->get();
        $insert_params = [];
        $created_at = Carbon::now()->format('Y-m-d H:i:s');
        foreach ($bas_sku_arr as $bas_sku) {
            $owner = $owners_code_map[$bas_sku->customerid] ?? '';
            if(!$owner)continue;
            if($bas_sku->sku==null)continue;
            if($bas_sku->descr_c=='')continue;
            $insert_params[] = [
                'owner_id' => $owner->id,
                'sku' => $bas_sku->sku,
                'name' =>$bas_sku->descr_c,
                'created_at' => $created_at,
                'length' =>$bas_sku->skulength,
                'width' => $bas_sku->skuwidth,
                'height' => $bas_sku->skuhigh,
                'volumn' => $bas_sku->cube
            ];
        }
        if(count($insert_params) > 0){
            try {
                $this->insert($insert_params);
                app('LogService')->log(__METHOD__,__FUNCTION__,'批量添加 commodity ' . count($insert_params) .json_encode($insert_params) );
            } catch (\Exception $e) {
                app('LogService')->log(__METHOD__,__FUNCTION__,'批量添加 commodity error' .json_encode($insert_params) ."||".$e->getMessage().'||'.$e->getTraceAsString());
            }
        }
        return Commodity::query()
            ->whereIn('owner_id',data_get($owners_code_map,'*.id'))
            ->whereIn('sku',data_get($params,'*.sku'))
            ->get();
    }

    public function createTemporaryCommodity(array $params)
    {
        $params["type"] = "临时";
        return Commodity::query()->create($params);
    }



    public function syncBarcodes($barcodesStr,$ownerId,$sku):Commodity
    {
        $barcodes=(function()use($barcodesStr){
            $barcodes=rtrim($barcodesStr,',');
            $barcodes=explode(',',$barcodes);
            foreach ($barcodes as $k=>$barcode){
                if(!trim($barcode)) unset($barcodes[$k]);
            }
            return $barcodes;
        })();
        $commodity=$this->firstOrCreate(['owner_id'=>$ownerId,'sku'=>$sku]);
        $commodityBarcodes=$commodity['barcodes']??new Collection();


        /** @var CommodityBarcodeService $commodityBarcodeService */
        $commodityBarcodeService=app('CommodityBarcodeService');
        $redundantCommodityBarcodes=new Collection();
        foreach($commodityBarcodes as $commodityBarcode){//清除数组中 已经在商品有的条码，清除商品条码中，不在数组中的条码
            $hasMatch=false;
            foreach($barcodes as $key=>$barcode){
                if($barcodes[$key]==$commodityBarcode['code']){
                    $hasMatch=true;
                    unset($barcodes[$key]);
                    break;
                }
            }
            if(!$hasMatch){
                $redundantCommodityBarcodes->push($commodityBarcode);
            }
        }
        if(!empty($redundantCommodityBarcodes)){
            $commodityBarcodeService->destroyCollections($redundantCommodityBarcodes);
        }
        if(!empty($barcodes)){
            $commodityBarcodeService->insertMany_onCommodities([['commodity_id'=>$commodity['id'],'barcodes'=>$barcodes]]);
        }
        return $commodity;
    }
    public function destroyWithOffspring(Commodity $commodity)
    {
        $barcodesIds=$commodity->barcodes->map(function ($barcode){
            return $barcode['id'];
        });
        CommodityBarcode::destroy($barcodesIds);
        $commodity->delete();
    }

    public function syncWMSOrderCode($owner,$skus)
    {
        $basSku = OracleBasSKU::query()->whereIn('SKU',$skus)->where('CustomerID',$owner->code)->get();
        $inner_params = [];
        $created_at = new Carbon();
        $basSku->each(function($bas_sku)use(&$inner_params,$owner,$created_at){
            $inner_params = [
                'owner_id' => $owner->id,
                'sku' => $bas_sku->sku,
                'name' =>$bas_sku->descr_c,
                'created_at' => $created_at,
                'length' =>$bas_sku->skulength,
                'width' => $bas_sku->skuwidth,
                'height' => $bas_sku->skuhigh,
                'volumn' => $bas_sku->cube
            ];
        });
        if(count($inner_params) > 0){
            try {
                $this->insert($inner_params);
                app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($inner_params));
            } catch (\Exception $e) {
                app('LogService')->log(__METHOD__, 'Error '.__FUNCTION__, json_encode($inner_params).' || '.$e->getMessage());
            }
        }
    }
    //获取箱规
    public function getPack($owner_id, $sku)
    {
        $that = $this;
        return app("CacheService")->getOrExecute("pack_{$owner_id}_{$sku}",function ()use($owner_id,$sku,$that){
            $commodity = $that->first([
                "owner_id" => $owner_id,
                "sku" => $sku
            ]);
            if (!$commodity || $commodity->pack === null){
                $owner = app("OwnerService")->find($owner_id);
                $action = new CommodityController();
                $action->syncOwnerCommodities($owner->id,$owner->code,$sku);
            }
            return $that->first([
                "owner_id" => $owner_id,
                "sku" => $sku
            ])->pack;
        });
    }
}
