<?php

namespace App;

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

use App\Traits\ModelLogChanging;

class OracleIdxAsrsReceive extends Model
{
    use ModelLogChanging;

    protected $connection="oracle";
    protected $primaryKey="GROUPTASKID";
    protected $table = 'idx_asrs_receive';
    protected $fillable = ['grouptaskid','grouptasksequence','userdefine1','userdefine2','addwho','addtime'];
    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');
        $logisticNumbers=$numbersesOfBatch->map(function($numbers){return $numbers['logistic_number'];});
        $logisticNumbers_toInsert=[];
        $idxAsrsReceives=OracleIdxAsrsReceive::whereIn('userdefine1',$logisticNumbers)->get();
        if($idxAsrsReceives->count()<$numbersesOfBatch->count()){
            foreach($numbersesOfBatch as $numbers){//跳过idx_asrs_receive已有快递单号
                foreach($idxAsrsReceives as $existingAsrsReceive){
                    if($existingAsrsReceive['userdefine1']==$numbers['logistic_number']){
                        continue 2;
                    }
                }
                $logisticNumbers_toInsert[]=$numbers['logistic_number'];
            }
            $inserts='';
            $values=[];
            foreach($logisticNumbers_toInsert as $logisticNumber){
                $inserts .= " into idx_asrs_receive (grouptaskid,grouptasksequence,userdefine1,userdefine2,addwho,addtime)values(?,?,?,?,?,?) ";
                $values[] = $logisticNumber??'';
                $values[] = 1;
                $values[] = $logisticNumber??'';
                $values[] = $weight;
                $values[] = 'WAS';
                $values[] = Carbon::now();
            }
            DB::connection('oracle')->insert("insert all {$inserts} select * from dual",$values);
        }
        OracleIdxAsrsReceive::whereIn('userdefine1',$logisticNumbers)->update(['userdefine2'=>$weight]);
    }
}
