<?php
/**
 * Created by PhpStorm
 * DateTime: 2022/11/5 0:31.
 *
 * @description
 */

namespace App\Http\Controllers\V1\Share;

use App\Http\Controllers\V1\Controller;
use App\Models\ShareConfig;
use App\Models\UserWithdraw;
use Dingo\Api\Http\Request;
use Illuminate\Http\JsonResponse;

class WithdrawController extends Controller
{
    public function lists(Request $request): JsonResponse
    {
        $limit  = $request->input('limit', 10);
        $page   = $request->input('page', 1);
        $status = $request->input('status', -1);
        $offset = ($page - 1) * 10;
        $user   = \user();

        $lists = UserWithdraw::where('user_id', $user->id)
            ->when(-1 != $status, function ($query) use ($status) {
                $query->where('status', $status);
            })
            ->limit($limit)
            ->offset($offset)
            ->get();

        /* @var UserWithdraw $list */
        foreach ($lists as $list) {
            $list->status_name = $list->status;
            $list->type_name   = $list->type;
        }

        return $this->success($lists);
    }

    public function create(Request $request): JsonResponse
    {
        try {
            $config   = ShareConfig::first();
            $price    = $request->input('price');
            $account  = $request->input('account');
            $phoneNum = $request->input('phone_num');
            $bankName = $request->input('bank_name');
            $type     = $request->input('type');
            $name     = $request->input('name');
            $user     = \user();
            if ($price < $config->withdraw_min) {
                return $this->error("提现金额不能小于{$config->withdraw_min}元");
            }
            if ($price > $user->income) {
                return $this->error("提现金额不能小于{$config->withdraw_min}元");
            }
            if (3 == $type && !$bankName) {
                return $this->error('请输入提现银行');
            }
            if ($price > $user->income) {
                return $this->error("提现金额不能大于可提现余额{$user->income}");
            }

            \DB::beginTransaction();

            $withdraw            = new UserWithdraw();
            $withdraw->user_id   = $user->id;
            $withdraw->name      = $name;
            $withdraw->bank_name = $bankName ?: '';
            $withdraw->account   = $account;
            $withdraw->phone_num = $phoneNum;
            $withdraw->price     = $price;
            $withdraw->type      = $type;
            $withdraw->discount  = $price * $config->withdraw_discount / 100;
            $withdraw->save();

            $user->income = $user->income - $price;
            $user->save();

            \DB::commit();

            return $this->success();
        } catch (\Exception $e) {
            \DB::rollBack();

            return $this->error('提交失败', $e->getMessage());
        }
    }
}
