<?php

namespace App\Http\Controllers\Api;

use App\Command\Log;
use App\Models\Carousel;
use App\Models\User;
use App\Models\Income;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class IncomeController extends BaseController
{
    public function getList(Request $request)
    {
        $type = $request->type ?? 0;
        $page = $request->page ?? 1;
        $limit = $request->limit ?? 10;
        $txtArr = ['提现中', '提现成功', '提现失败'];
        if (!in_array($type, [1, 2,])) {
            return $this->JsonResponse('', '参数错误', 201);
        }
        $sql = Income::where(['um_id' => $request->user()->id, 'user_type' => $type, 'deleted_at' => null]);

        $total = $sql->count();
        $data = [
            'total' => $total,
            'total_page' => ceil($total / $limit),
            'list' => []
        ];
        $listData = $sql->offset(($page - 1) * $limit)->limit($limit)->orderBy('created_at', 'DESC')->get();
        if ($listData->toArray()) {
            foreach ($listData as $kk => $vv) {
                $data['list'][] = [
                    'title' => $txtArr[$vv->status],
                    'status' => $vv->status,
                    'created_at' => date("Y-m-d H:i:s", strtotime($vv->created_at)),
                    'amount' => $vv->amount
                ];
            }
        }

        return  $this->JsonResponse($data);
    }

    public function add(Request $request)
    {
        $useObj = $request->user();
        $type = $request->type ?? 0;
        $money = $request->money ? (float)$request->money : 0;

        if (!in_array($type, [1, 2,])) {
            return $this->JsonResponse('', '参数错误', 201);
        }
        if ($money < 1) {
            return $this->JsonResponse('', '提现金额1元起', 500);
        }
        if ($useObj->balance < $money) {
            return $this->JsonResponse('', '余额不足', 500);
        }

        DB::beginTransaction();
        try {
            $comObj = new Income();

            $comObj->user_type = $type;
            $comObj->um_id = $useObj->id;
            $comObj->openid = $useObj->openid;
            $comObj->amount = $money;
            $comObj->status = 0;
            $comObj->save();
            DB::commit();
            return $this->JsonResponse('');
        } catch (\Exception $exception) {
            Log::add('添加提现失败', $exception->getMessage());
            DB::rollBack();
            return $this->JsonResponse('', '添加提现失败', 201);
        }
    }
}