<?php

namespace App\Services;

use App\Batch;
use App\OracleActAllocationDetails;
use App\Order;
use App\OrderCommodity;
use App\Services\common\BatchUpdateService;
use App\Services\common\DataHandlerService;
use Carbon\Carbon;
use App\Traits\ServiceAppAop;


class OrderCommodityService
{
    use ServiceAppAop;
    protected $modelClass=OrderCommodity::class;

    public function insert($innerParams){
        if(!$innerParams)return false;
        if(count($innerParams)==0)return false;
        try {
            $bool = OrderCommodity::query()->insert($innerParams);
            if ($bool) app('LogService')->log(__METHOD__, __FUNCTION__, '批量添加 OrderCommodities SUCCESS' . ' || ' . count($innerParams) . ' || ' . json_encode($innerParams));
            else app('LogService')->log(__METHOD__, __FUNCTION__, '批量添加 OrderCommodities FAULT' . ' || ' . count($innerParams) . ' || ' . json_encode($innerParams));
            return $bool;
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__, __FUNCTION__, '批量添加 OrderCommodities ERROR'. ' || ' . count($innerParams) . ' || ' . json_encode($innerParams).' || '.json_encode($e->getMessage()).' || '.json_encode($e->getTraceAsString()));
            return false;
        }
    }

    public function correctLocation_fromWMS($orderCommodities){
        $orderCommodities->loadMissing('order.batch');
        $details=OracleActAllocationDetails::query()
            ->where('orderno',data_get($orderCommodities,'*.order.code')??[])
            ->where('waveno',data_get($orderCommodities,'*.order.batch.code')??[])
            ->get(['orderno','location','waveno']);
        foreach($orderCommodities as &$orderCommodity){
            $orderCommodity['location'] ==$details
                ->where('orderno',$orderCommodity['order']['code'])
                ->where('waveno',$orderCommodity['order']['batch']['code'])
                ->first()['location']??'';
        }
        return $orderCommodities;
    }
    public function batchUpdate($updateParams){
        return app(BatchUpdateService::class)->batchUpdate('order_commodities',$updateParams);
    }

    public function syncOrderCommodity(&$orderHeaders)
    {
        /**
         * @var OwnerService $ownerService
         * @var CommodityService $commodityService
         * @var DataHandlerService $dataHandlerService
         */
        $ownerService = app('OwnerService');
        $commodityService = app('CommodityService');
        $dataHandlerService = app('DataHandlerService');
        $orderNos = data_get($orderHeaders,'*.orderno');
        $owner_codes = [];$sku_codes = [];
        $map = [];
        foreach ($orderHeaders as $orderHeader) {
            $actAllocationDetails  = $orderHeader->actAllocationDetails;
            foreach ($actAllocationDetails as $actAllocationDetail) {
                $owner_codes[$actAllocationDetail['customerid']] = $actAllocationDetail['customerid'];
                $sku_codes[$actAllocationDetail['sku']] = $actAllocationDetail['sku'];
                $value = [
                    'owner_code'=> $actAllocationDetail['customerid'],
                    'sku' => $actAllocationDetail['sku']
                ];
                $key = json_encode($value);
                $map[$key] = $value;
            }
        }
        if(count($sku_codes) ==0)return;
        $owners = $ownerService->getOwnerByCodes($owner_codes);
        $owner_id_maps = $dataHandlerService->dataHeader(['id'],$owners);
        $commodities = $commodityService->getCommoditiesByMaps($map);
        unset($owner_codes,$sku_codes);
        $commodity_map = [];
        foreach ($commodities as $commodity) {
            $owner = $dataHandlerService->getKeyValue(['id'=>$commodity->owner_id],$owner_id_maps);
            $key = "_owner_code_{$owner['code']}_sku_{$commodity['sku']}";
            $commodity_map[$key] = $commodity;
        }
        $orders = Order::query()->with('packages.commodities')->whereIn('code',$orderNos)->get();
        if($orders->count()==0)return;
        $orderCommodities = OrderCommodity::query()->with(['order','commodity'])->whereIn('order_id',data_get($orders,'*.id'))->get();
        $order_code_map = $dataHandlerService->dataHeader(['code'],$orders);
        $ActAllocationDetail_maps =  $this->getRegroupActAllocationDetails($orderHeaders);
        $orderCommodity_maps = $this->getRegroupOrderCommodities($orderCommodities,$owner_id_maps);
        unset($orderCommodities,$owner_id_maps,$owners,$orderNos);
        $this->filterHasExist($ActAllocationDetail_maps,$orderCommodity_maps);
        $delete_ids =  $this->getDeleteIds($ActAllocationDetail_maps,$orderCommodity_maps);
        $create_params = $this->getCreateParams($ActAllocationDetail_maps,$orderCommodity_maps);
        unset($orderCommodity_maps,$ActAllocationDetail_maps);

        $inner_params = $this->getInnerParamsByParams($create_params,$order_code_map,$commodity_map);
        unset($create_params,$order_code_map,$orders,$commodity_map);

        if(count($inner_params)>0){
            foreach (array_chunk($inner_params,4000) as $inner_param) {$this->insert($inner_param);}
            unset($inner_params);
        }

        if(count($delete_ids)==0)return;
        OrderCommodity::query()->whereIn('id',$delete_ids)->delete();
        app('LogService')->log(__METHOD__,__FUNCTION__,"delete OrderCommodity ".json_encode($delete_ids));
        unset($delete_ids);
    }

    public function getRegroupActAllocationDetails(&$orderHeaders)
    {
        $map = [];
        if($orderHeaders->count()==0) return $map;
        $orderHeaders->each(function($orderHeader)use(&$map){
            $orderHeader->actAllocationDetails->each(function ($details)use(&$map){
                $key = "order_{$details['orderno']}_owner_code_{$details['customerid']}_sku_{$details['sku']}_location_{$details['location']}_amount_{$details['qty_each']}";
                if(empty($map[$key]))$map[$key]=[];
                $map[$key][] = [
                    'code' => $details['orderno'],
                    'sku' => $details['sku'],
                    'owner_code'=> $details['customerid'],
                    'amount' => $details['qty_each'],
                    'location' => $details['location']
                ];
            });
        });
        return $map;
    }

    public function filterHasExist(&$ActAllocationDetail_maps,&$orderCommodity_maps)
    {
        foreach ($ActAllocationDetail_maps as $key=>$actAllocationDetail_map) {
            $orderCommodity_map = $orderCommodity_maps[$key] ?? null;
            if($orderCommodity_map == null)continue;
            foreach ($actAllocationDetail_map as $index=>$item) {
                if(count($orderCommodity_map)==0)break;
                array_shift($orderCommodity_map);
                unset($actAllocationDetail_map[$index]);
            }
        }
    }

    public function getRegroupOrderCommodities(&$orderCommodities,$owner_id_maps)
    {
        /** @var DataHandlerService  $dataHandlerService */
        $dataHandlerService = app(DataHandlerService::class);
        $map = [];
        if($orderCommodities->count() == 0)return $map;
        $orderCommodities->each(function($orderCommodity)use(&$map,$owner_id_maps,$dataHandlerService){
            $order = $orderCommodity->order;
            $owner  = $dataHandlerService->getKeyValue(['id'=>$order->owner_id ?? ''],$owner_id_maps);
            $sku =  $orderCommodity->commodity->sku ?? '';
            $key = "order_{$order->code}_owner_code_{$owner['code']}_sku_{ $sku}_location_{$orderCommodity->location}_amount_{$orderCommodity->amount}";
            if(empty($map[$key]))$map[$key]=[];
            $map[$key][]  =[
                'id' => $orderCommodity->id,
                'code' => $order->code ?? '',
                'sku' => $sku,
                'owner_code' => $owner->code ?? '',
                'amount' => $orderCommodity->amount,
                'location' => $orderCommodity->location,
            ];
        });
        return $map;
    }

    public function getDeleteIds(&$ActAllocationDetail_maps,&$orderCommodity_maps)
    {
        $ids = [];
        if(count($orderCommodity_maps)==0)return $ids;
        foreach ($orderCommodity_maps as $key=>$orderCommodity_map) {
            $ActAllocationDetail_map = $ActAllocationDetail_maps[$key]  ?? null;
            if($ActAllocationDetail_map==null){
                foreach ($orderCommodity_map as $index=>$orderCommodity) {
                    $ids[] =$orderCommodity['id'];
                    unset($orderCommodity_map[$index]);
                }
                continue;
            }
            if(count($ActAllocationDetail_map) == count($orderCommodity_map))continue;
            if(count($ActAllocationDetail_map) < count($orderCommodity_map)){
                foreach ($orderCommodity_map as $index=>$item) {
                    if(count($ActAllocationDetail_map) == 0)$ids[] =$item['id'];
                    array_shift($ActAllocationDetail_map);
                    unset($orderCommodity_map[$index]);
                }
            }
        }
        return $ids;
    }

    public function getCreateParams(&$ActAllocationDetail_maps,&$orderCommodity_maps)
    {
        $params = [];
        foreach ($ActAllocationDetail_maps as $key=>$actAllocationDetail_map) {
            $orderCommodity_map = $orderCommodity_maps[$key] ?? null;
            if($orderCommodity_map == null){
                foreach ($actAllocationDetail_map as $index=>$actAllocationDetail) {
                    $params[]  = $actAllocationDetail;
                    unset($actAllocationDetail_map[$key]);
                }
                continue;
            }elseif(count($actAllocationDetail_map) == count($orderCommodity_map)){
                continue;
            }elseif(count($actAllocationDetail_map) > count($orderCommodity_map)){
                foreach ($actAllocationDetail_map as $index=>$item) {
                    if(count($orderCommodity_map) == 0)$params[] = $item;
                    array_shift($orderCommodity_map);
                    unset($actAllocationDetail_map[$key]);
                }
            }
        }
        return $params;
    }

    public function getInnerParamsByParams($create_params,$order_code_map,$commodity_map)
    {
        /** @var DataHandlerService  $dataHandlerService */
        $dataHandlerService = app(DataHandlerService::class);
        $inner_params = [];
        $date = (string) Carbon::now();
        foreach ($create_params as $item) {
            $order = $dataHandlerService->getKeyValue(['code'=>$item['code']],$order_code_map);
            if(!$order)continue;
            $key = "_owner_code_{$item['owner_code']}_sku_{$item['sku']}";
            $commodity = $commodity_map[$key] ?? null;
            $inner_params[] = [
                'order_id' => $order['id'] ?? '',
                'commodity_id' => $commodity['id'] ?? '',
                'amount' => $item['amount'],
                'location' => $item['location'],
                'created_at' => $date,
                'updated_at' => $date
            ];
        }
        return $inner_params;
    }

    //更新后续添加进更新逻辑
    public function getUpdateParamsByParamsAndDeleteIds(&$inner_params,&$ids)
    {
        $update_params = [['id','order_id', 'commodity_id', 'amount', 'location', 'created_at', 'updated_at']];
        if(count($inner_params)==0)return $update_params;
        $date = (string)Carbon::now();
        foreach ($inner_params as $key=>$inner_param) {
            if(count($ids)==0)break;
            $inner_param['id'] = array_shift($ids);
            $inner_param['updated_at'] = $date;
            $inner_param['created_at'] = $date;
            $update_params[] = $inner_param;
            unset($inner_params[$key]);
        }
        return $update_params;
    }
}

