<?php

namespace App\Listeners;

use App\Events\InformWMSReceivedEvent;
use App\Events\WmsReceiveNewEvent;
use App\Http\Controllers\Controller;
use App\Http\Controllers\RejectedBillItemController;
use App\Jobs\ProcessReceiveCombinedJob;
use App\Owner;
use App\RejectedBill;
use App\RejectedBillItem;
use App\WMSReflectReceive;
use App\WMSReflectReceiveSku;
use Carbon\Carbon;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;

class WmsReceiveNewListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  WmsReceiveNewEvent  $event
     * @return void
     */
    public function handle(WmsReceiveNewEvent $event)
    {
        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"进入退单处理事件，由下发或队列启动，退单号：{$event->logisticNumberReturn}",null);
        $logisticNumberReturn=$event->logisticNumberReturn;
        $wmsReceives=WMSReflectReceive::where('ASNREFERENCE3',$logisticNumberReturn)->where('is_uploaded',0)->orderBy('id','desc')->get();
        $downloadedSkuItems=[];
        $wmsReceives->each(function (WMSReflectReceive $receive)use(&$downloadedSkuItems){
            $receive->skus()->each(function(WMSReflectReceiveSku $item)use(&$downloadedSkuItems){
                $downloadedSkuItems[]=$item;
            });
        });
        $wmsReceive=$event->wmsReceive;
        switch ($wmsReceive['CUSTOMERID']){
            case 'JIANSHANG':
                $this->handleJianshang($logisticNumberReturn,$downloadedSkuItems,$wmsReceives);
                break;
        }
    }

    private function handleJianshang($logisticNumberReturn, $downloadedSkuItems, $wmsReceives){
        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"进入笕尚退单处理事件，退单号：{$logisticNumberReturn}",null);
        $bills=RejectedBill::where('logistic_number_return',$logisticNumberReturn)->
            whereIn('is_loaded',[0,2])->get();
        if($bills->isEmpty()){//没有本地货单
            Controller::logS(__METHOD__,__FUNCTION__,"退单搁置，没有本地对应退单，退单号：{$logisticNumberReturn}",null);
            return;
        }


        //找得到本地单，（未入库的）
        $actualGotItems=(function()use($bills){
            $items=[];
            $bills->each(function (RejectedBill $bill)use(&$items){
                $bill->items()->each(function (RejectedBillItem $item)use(&$items){
                    $items[]=$item;
                });
            });
            return new Collection($items);
        })();
        $isItemsReceivedOverDownloaded=WMSReflectReceiveSku::isItemsOverDownloadedSkus($actualGotItems,$downloadedSkuItems);
        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"退单事件中，同名退单数：（"
            .$bills->count()."）}，同名退单：（".json_encode($bills)."）}，实收件：（".json_encode($actualGotItems)."）}，下载件：（"
            .json_encode($downloadedSkuItems)."）}，退单号：{$logisticNumberReturn}",null);

        if(!$isItemsReceivedOverDownloaded){//实收小于等于下发(下发大于等于实收)，入库
            if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"退单事件中，入库触发（实收小于等于下发），退单号：{$logisticNumberReturn}",null);
            foreach ($bills as $bill){
                if($bill['is_loaded']!==1){
                    $bill->setIsLoaded_toWaitConfirm();
//                    event(new InformWMSReceivedEvent($bill)); //暂时关闭下发途迳的入库，不管是录入后才下发，延时处理发现待推单，该入的都改为人工确定
                }
            }
            if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"退单事件中，入库完成并结束事件，退单号：{$logisticNumberReturn}",null);
            return;
        }


        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"实收大于下发（不入库）,退单号：{$logisticNumberReturn}",null);
        //（下发小于实收）
        //该单号在6小时前录入的(不是当前最新录入)，直接不入库，将实收推给客户（笕尚），并且退单号下所有WMS本地单作废
        $lastReceive=$wmsReceives->first();
        if($lastReceive&&$lastReceive['created_at'])
            if(Carbon::now()->greaterThan(Carbon::make($lastReceive['created_at'])->addHours(6))){
                if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"退单事件中，下发小于实收。6小时前WMS下发的该退单，将不入库的单推给笕尚,未来不再处理该单！退单号：{$logisticNumberReturn}",null);
                (new RejectedBillItemController())->sendRejectedToThirdPart2($actualGotItems,$bills->first());
                return;
            }

        //不入库，推入任务，13小时后重新执行本事件
        if($wmsReceives->isNotEmpty()){
            Controller::logS(__METHOD__,  __FUNCTION__,  '推入任务，13小时后执行本事件，退单号:'.$logisticNumberReturn);
            ProcessReceiveCombinedJob::dispatch($logisticNumberReturn)->delay(now()->addHours(13));
            return;
        }
        Controller::logS(__METHOD__,'error_'.__FUNCTION__,"退单事件已走完，但下载的WMS退单不存在! 退单号：{$logisticNumberReturn}",null);
    }
}
