<?php

namespace App\Store\Forms;

use App\Command\Log;

use App\Models\StoreIncome;
use App\Models\StoreInfo;

use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Illuminate\Support\Facades\DB;


class IncomeApply extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $store = StoreInfo::where(['store_id'=>Admin::user()->id]);
        if($store->balance < $input['amount']){
            return $this->response()->error('当前余额不足,提现申请失败')->refresh();
        }

        DB::beginTransaction();
        try {
            $model = new StoreIncome();
            $model->store_id = Admin::user()->id;
            $model->amount = $input['amount'];
            $model->invoice = $input['invoice'] ??'';
            $model->save();
            $store->balance -= $input['amount'];
            $store->freeze_balance += $input['amount'];
            $store->save();
            DB::commit();
            Log::add('商城商户提现申请',$model->toArray());
        }catch (\Exception $exception){
            DB::rollBack();
            Log::add('商城商户提现申请失败',$exception);
            return $this->response()->error('提现申请失败')->refresh();
        }

        return $this->response()->success('提现申请成功')->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->currency('amount','金额')->symbol('¥')->required();
        $this->multipleImage('invoice','发票信息')
            ->accept('jpg,jpeg,png')
            ->maxSize(2048)
            ->limit(9)
            ->url('upload/store-invoice')
            ->help('仅支持jpg、jpeg、png格式图片上传')
            ->autoUpload()
            ->saveAsJson();
    }

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