<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

use App\Traits\ModelLogChanging;

class OracleDocOrderPackingSummary extends Model
{
    use ModelLogChanging;

    protected $connection="oracle";
    protected $primaryKey="traceid";
    protected $table = 'doc_order_packing_summary';
    protected $fillable = ['traceid','orderno','grossweight','addwho','addtime','editwho','edittime'];
    public $timestamps=false;
    public function getIncrementing(){ return false;}

    static public function saveOrUpdateWeightByBatch($batchNumber,$weight){
        $numbersesOfBatch=OracleDOCWaveDetails::select('picktotraceid as logistic_number','act_allocation_details.orderno')->where('doc_wave_details.waveno',$batchNumber)
            ->leftJoin('act_allocation_details','doc_wave_details.orderno','act_allocation_details.orderno')->get();
        $numbersesOfBatch=$numbersesOfBatch->unique('logistic_number');
        $numbersUseful=$numbersesOfBatch->map(function($numbers){return $numbers['logistic_number'];});
        $numbersUseful_toInsert=[];
        $oneIdxAsrsReceive=OracleDocOrderPackingSummary::whereIn('traceid',$numbersUseful)->get();
        if($oneIdxAsrsReceive->count()<$numbersesOfBatch->count()){
            foreach($numbersesOfBatch as $numbers){//跳过idx_asrs_receive已有快递单号
                foreach($oneIdxAsrsReceive as $existingAsrsReceive){
                    if($existingAsrsReceive['userdefine1']==$numbers['logistic_number']){
                        continue 2;
                    }
                }
                $numbersUseful_toInsert[]=$numbers;
            }
            $inserts='';
            $values=[];
            foreach($numbersUseful_toInsert as $numbers){
                $inserts .= " into doc_order_packing_summary (traceid,orderno,grossweight,addwho,addtime,editwho,edittime)values(?,?,?,?,?,?,?) ";
                $values[] = $numbers['logistic_number']??'';
                $values[] = $numbers['orderno']??'';
                $values[] = $weight;
                $values[] = 'WAS';
                $values[] = Carbon::now();
                $values[] = 'WAS';
                $values[] = Carbon::now();
            }
            DB::connection('oracle')->insert("insert all {$inserts} select * from dual",$values);
        }
        OracleDocOrderPackingSummary::whereIn('traceid',$numbersUseful)->update(['grossweight'=>$weight]);
    }
}
