<?php

namespace App\Admin\Actions\backstage\Refund;

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

class RefundPartCompleteAction extends RowAction
{
    public $name = '部分退款完成';

    public function handle(Model $model,Request $request)
    {
        $num = request('num');
        $num = $num*100;
        $total =  Order::where('id',$this->row->order_id)->value('payment_amount');
        if ($num>$total)
        {
            return $this->response()->error('部分退款金额不得大于订单金额')->refresh();
        }
        if ($num<0)
        {
            return $this->response()->error('部分退款金额不得小于0')->refresh();
        }
        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'=> $num
        ]);
        $user_id = Order::where('id',$this->row->order_id)->value('user_id');
        $balance = User::where('id',$user_id)->value('balance');
        $new_balance = $balance+$num;
        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' => '+'.$num,
            'after_balance' => $new_balance,
            'remark'=>'订单部分退款'
        ];
        UserBalanceLog::create($balance_log);
        return $this->response()->success('退款成功')->refresh();
    }
    public function form(){
        $total =  Order::where('id',$this->row->order_id)->value('payment_amount');
        $this->text('total','当前订单金额')->value($total/100)->disable();
        $this->text('num','部分退款金额')->help('部分退款金额应小于订单金额');
    }
}