<?php

namespace App;

use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Model;
use App\Traits\ModelTimeFormat;

use App\Traits\ModelLogChanging;

class WMSReflectReceiveSku extends Model
{
    use ModelLogChanging;

    use ModelTimeFormat;
    protected $fillable=['ASNLINENO','SKU','ALTERNATE_SKU1','SKUDESCRC','EXPECTEDQTY_EACH',
        'LOTATT05','USERDEFINE4','USERDEFINE5','USERDEFINE6'];
    function receives(){
        return $this->belongsTo('App\WMSReflectReceive','wms_receive_id');
    }

    static function isItemsOverDownloadedSkus($actualGotItems, $downloadedItems){
        //将同条形码的商品合并为一个元素计数
        $combine=function($targetItems){
            $combinedItems=[];
            foreach ($targetItems as $item){
                $isActualCounted=false;
                foreach ($combinedItems as $key=>$combined){
                    if(($combined['barcode_goods']??$combined['ALTERNATE_SKU1'])
                            ==($item['barcode_goods']??$item['ALTERNATE_SKU1'])){
                        $combinedItems[$key]['amount'] += $item['amount'];
                        $combinedItems[$key]['EXPECTEDQTY_EACH'] += $item['EXPECTEDQTY_EACH'];
                        $isActualCounted=true;
                    }
                }
                if(!$isActualCounted)
                    $combinedItems[] = $item;
            }
            return $combinedItems;
        };
        $combinedActualItems=$combine($actualGotItems);
        $combinedDownloadedItems=$combine($downloadedItems);;
        //比较实收有没有超出下发，有则true
        foreach ($combinedActualItems as $item){
            $isInDownloaded=false;
            foreach ($combinedDownloadedItems as $sku){
                if($item&&$item['is_loaded']=='已入库'){
                    $isInDownloaded=true;
                    break;
                }
                if($item['barcode_goods']==$sku['ALTERNATE_SKU1']){
                    if($item['amount']<=$sku['EXPECTEDQTY_EACH']){
                        $isInDownloaded=true;
                        break;
                    }
                }
            }
            if(!$isInDownloaded){
                return true;
            }
        }
        return false;
    }
}
