<?php

namespace app\controller\v2;

use app\extra\basic\Base;
use app\middleware\WxMiddleware;
use app\model\blue\BlueExpert;
use app\model\blue\BlueWithdrawLog;
use LinFly\Annotation\Route\Controller;
use LinFly\Annotation\Route\Middleware;
use LinFly\Annotation\Route\Route;
use support\Request;
use support\Response;

/**
 * 提现
 */
#[Controller(prefix: "/wx_v2/withdraw"),Middleware(WxMiddleware::class)]
class Withdraw extends Base
{

    /**
     * 获取可提现金额
     * @param Request $request
     * @return Response
     */
    #[Route(path: "balance",methods: "get")]
    public function getBalance(Request $request): Response
    {
        try {
            $balance = (new BlueExpert)->where("openid",$request->user['openid'])->value("balance");
            if ($balance > 0) $balance = format_money($balance/100);
            return successTrans("success.data",compact("balance"));
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


    /**
     * 申请提现
     * @param Request $request
     * @return Response
     */
    #[Route(path: "submit",methods: "post")]
    public function submitData(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "money.require" => trans("empty.require"),
                "bank.require"  => trans("empty.require")
            ],$request->method());
            if(!is_array($param)) return error($param);
            $balance = (new BlueExpert)->where("openid",$request->user['openid'])->findOrEmpty();
            if ($balance->isEmpty()) return error("非法操作");
            if ($param['money'] * 100 > $balance['balance']) return error("余额不足");
            $bankData = is_string($param['bank']) ? json_decode($param['bank'],true):$param['bank'];
            if (!isset($bankData['bank_code'])) return error("银行卡数据错误");
            $state = (new BlueWithdrawLog)->insertGetId([
                "openid"    => $request->user['openid'],
                "bank_id"   => $bankData['bank_code'],
                "money"     => $param['money'] * 100
            ]);
            if (!$state) return errorTrans("error.data");
            $balance->balance = $balance['balance'] - ($param['money'] * 100);
            $balance->save();
            return successTrans("success.data");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


}