<?php

namespace App\Admin\Actions\backstage\Refund;

use App\Models\Order;
use App\Models\RefundApplication;
use App\Models\User;
use App\Models\UserBalanceLog;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;

class RefundCompleteAction extends RowAction
{
    public $name = '退款完成';

    public function handle(Model $model)
    {
        $money = Order::where('id',$this->row->order_id)->value('payment_amount');
        Order::where('id',$this->row->order_id)->update(['payment_status'=> 4]);
        RefundApplication::where('id',$this->row->id)->update([ 'end_time'=>date('Y-m-d H:i:s',time()),
                                                                'financial_auditor'=>\Admin::user()->id,
                                                                'status'=>2,
                                                                'refund_amount'=> $money]);
        $user_id = Order::where('id',$this->row->order_id)->value('user_id');
        $balance = User::where('id',$user_id)->value('balance');
        $new_balance = $balance+$money;
        User::where('id',$user_id)->update(['balance'=>$new_balance]);
        $balance_log = [
            'user_id' => $user_id,
            'admin_user_id' => \Admin::user()->id,
            'type' => 4,
            'relation_id' => $this->row->order_id,
            'before_balance' => $balance,
            'change_balance' => '+'.$money,
            'after_balance' => $new_balance,
            'remark'=>'订单退款'
        ];
        UserBalanceLog::create($balance_log);
        return $this->response()->success('退款成功')->refresh();
    }

}