<?php

namespace App\Admin\Actions\Form;

use App\Models\User;
use App\Models\UserWithdraw;
use Carbon\Carbon;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class WithdrawReview extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $status = $input['status'];

        try {
            $withdraw = UserWithdraw::find($input['id']);
            if ($status > 0) {
                $withdraw->status = $status;
                // 审核通过或者拒绝
                if (1 == $status || 3 == $status) {
                    $withdraw->review_at = Carbon::now()->toDateTimeString();
                }
                if (2 == $status) {
                    $withdraw->withdraw_at = Carbon::now()->toDateTimeString();
                }
                $withdraw->save();
            }

            // 驳回返还收益
            if (3 == $withdraw->status) {
                $user         = User::find($withdraw->user_id);
                $user->income = $user->income + $withdraw->price;
                $user->save();
            }
        } catch (\Exception $exception) {
            return $this->response()->error($exception->getMessage());
        }

        return $this->response()->success('success')->refresh();
    }

    public function form()
    {
        $id = isset($this->payload['id']) ? $this->payload['id'] : 0;
        $this->hidden('id')->value($id);
        $this->radio('status', '审核结果')
            ->options(config('global.withdraw_status'))->default(1);
        $this->disableResetButton();
    }
}
