<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserWithdraw;
use Illuminate\Http\Request;

class WithdrawController extends Controller
{
    public function apply()
    {
        $req = request()->post();
        $this->validate(request(), [
            'name|姓名'      => 'required',
            'account|账号'      => 'required',
        ]);

        \DB::beginTransaction();
        try
        {
            $user = auth('api')->user();

            $user = User::where('id',$user['id'])->first()->toArray();
            if($user['overage'] == 0){
                throw new \Exception('暂无可提现金额');
            }
            UserWithdraw::create([
                'user_id' => $user['id'],
                'name' => $req['name'],
                'account' => $req['account'],
                'price' => $user['overage'],
                'desc' => $req['remark'] ?? '',
            ]);


            $user = User::find($user['id']);
            $user->overage = 0;
            $user->save();
            // 提交事务
            \DB::commit();
        }catch (\Exception $e) {
            \DB::rollBack();
            return out(null, 10001, '提现失败!' . $e->getMessage());
        }
        return out();
    }


    // 0-待审核 1-已通过 2-已驳回 -1 全部
    public function lists()
    {
        $req = request()->all();

        $builder = UserWithdraw::orderBy('id','desc');
        if(isset($req['status']) && $req['status'] != -1){
            $builder->where('status', $req['status']);
        }
        $data = $builder->paginate($req['per_page'] ?? 15);
        $total_num = $builder->sum('id');
        $custom = collect([
            'total_num'   => $total_num,
        ]);
        $data = $custom->merge($data);
        return out($data);
    }
}
