<?php

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

class ChangeOrderIssue extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('order_issues',function (Blueprint $table) {
            $table->string('logistic_number_return')->nullable()->index()->after('order_id');
        });

        $orderIssues = \App\OrderIssue::query()->withTrashed()->get();
        if($orderIssues->count()>0){
            foreach ($orderIssues as $orderIssue) {
                $rejectedBill = $orderIssue->hasOne(RejectedBill::class, 'id', 'rejected_bill_id')->first();
                if($rejectedBill ?? false){
                    $orderIssue->update(['logistic_number_return'=>$rejectedBill->logistic_number_return ?? null]);
                }
            }
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
//        Schema::table('order_issues',function (Blueprint $table) {
//            $table->integer('rejected_bill_id')->index()->nullable()->comment('退回单')->after('order_id');
//        });

        $orderIssues = \App\OrderIssue::query()->withTrashed()->get();
        if($orderIssues->count()>0){
            foreach ($orderIssues as $orderIssue) {
                $rejectedBill =  $orderIssue->hasOne(RejectedBill::class, 'logistic_number_return', 'logistic_number_return')->first();
                if($rejectedBill ?? false){
                    $orderIssue->update(['rejected_bill_id'=>$rejectedBill->id ?? null]);
                }
            }
        }

//        Schema::table('order_issues',function (Blueprint $table) {
//            $table->dropColumn('logistic_number_return');
//        });
    }
}
