<?php

use App\Services\OrderTrackingService;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddColumnLogisticIdToOrderTrackings extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('order_trackings', function (Blueprint $table) {
            $table->integer('logistic_id')->index()->comment('快递');
        });
        $this->migrationLogistic();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('order_trackings', function (Blueprint $table) {
            $table->dropColumn('logistic_id');
        });
    }

    public function migrationLogistic()
    {
        /** @var OrderTrackingService $service */
        $service = app(OrderTrackingService::class);
        $maxId= \App\OrderTracking::query()->orderByDesc('id')->first();
        $orderTracking_min = \App\OrderTracking::query()->where('logistic_id',0)->orderBy('id')->first();
        if(!$maxId)return;
        $maxId = $maxId->id;
        $minId= $orderTracking_min->id;
        $logistic = \App\Logistic::query()->where('name','新杰物流')->first();
        $logistic_zt = \App\Logistic::query()->where('name','自提')->first();

        for ($i=$minId;$i<= $maxId;$i+=100){
            $orderTrackings = \App\OrderTracking::query()
                ->where('id','>=',$i)
                ->where('id','<=',$i+100)
                ->where('logistic_id','=',0)
                ->where('created_at','!=','0000-00-00 00:00:00')
                ->get();
            if($orderTrackings->count() ==0) continue;
            $update_params = [['id','logistic_id']];
            $orderTrackings->each(function($orderTracking)use($logistic_zt,$logistic,&$update_params){
                $order =$orderTracking->commodities->package->order;
                $logistic_id = $order->logistic_id;
                if($logistic_id!=null){
                    if($order->logistic_id == $logistic_zt->id)$logistic_id = $logistic->id;
                    if($logistic_id==0)dd($order,$logistic_id);
                    $update_params[] = [
                        'id' => $orderTracking->id,
                        'logistic_id' => $logistic_id,
                    ];
                }
            });
            if(count($update_params) > 1){
                $service->batchUpdate($update_params);
            }
        }
    }
}
