<?php

namespace App\Admin\Forms;


use App\Command\Log;

use App\Models\Company;
use App\Models\Employee;
use App\Models\Income;
use App\Models\Merchant;
use App\Models\Pay;
use App\Models\User;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Exception;
use Illuminate\Support\Facades\DB;


class CheckIncome extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        DB::beginTransaction();
        $income = Income::find($this->payload['id']);
        if ($income->batch_id) {
            return $this->response()->error('提现已受理,请等待。。。')->refresh();
        }
        try {
            $status = (int)$input['status']; //审核状态 0:审核中 1:通过 2:拒绝
            $income->remark = $input['remark'] ?? '';
            if ($status == 1) {
                $pay_res =  Pay::toBalance($income->openid, $income->amount, '用户提现');
                if (!empty($pay_res)) {
                    $income->partner_trade_no = $pay_res[0];
                    $income->out_batch_no = $pay_res[1];
                    $income->batch_id = $pay_res[2];
                    $income->batch_status = $pay_res[3];
                    //更新余额
                    if ($income->user_type == 1) { //用户
                        $uObj = User::find($income->um_id);
                        if ($uObj->freeze_balance >= $income->amount) {
                            $uObj->freeze_balance -= $income->amount;
                            $uObj->save();
                        } else {
                            throw new Exception('用户余额不足!');
                        }
                    } elseif ($income->user_type == 2) { //商户
                        $mObj = Merchant::find($income->um_id);
                        if ($mObj->freeze_balance >= $income->amount) {
                            $mObj->freeze_balance -= $income->amount;
                            $mObj->save();
                        } else {
                            throw new Exception('商户余额不足!');
                        }
                    }
                }
            } elseif ($status == 2) {
                $income->status = 2;
                //退回余额
                if ($income->user_type == 1) { //用户
                    $uObj = User::find($income->um_id);
                    $uObj->balance += $income->amount;
                    $uObj->freeze_balance -= $income->amount;
                    $uObj->save();
                } elseif ($income->user_type == 2) { //商户
                    $mObj = Merchant::find($income->um_id);
                    $mObj->freeze += $income->amount;
                    $mObj->freeze_balance -= $income->amount;
                    $mObj->save();
                }
            }

            $income->save();

            DB::commit();
            Log::add('提现已受理', $income->toArray());
        } catch (\Exception $exception) {
            DB::rollBack();

            Log::add('用户提现失败', $exception->getMessage());
            return $this->response()->error($exception->getMessage())->refresh();
        }
        return $this->response()->success('用户提现已受理')->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->radio('status', '提现审核')->options([1 => '同意提现', 2 => '拒绝提现'])
            ->when(2, function (Form $form) {
                $form->textarea('remark', '拒绝理由');
            })
            ->required();
        $this->text('remark', '备注');
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        // 获取外部传递参数
        return [];
    }
}