<?php

namespace app\controller\v2;

use app\extra\basic\Base;
use app\extra\service\blue\UserBankService;
use app\middleware\WxMiddleware;
use app\model\blue\BlueBankCompany;
use app\model\blue\BlueUserBank;
use app\validate\blue\BankValidate;
use DI\Attribute\Inject;
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/bank"),Middleware(WxMiddleware::class)]
class Bank extends Base
{


    protected array $noNeedLogin = ["getBankList"];

    #[Inject]
    protected BankValidate $validate;

    #[Inject]
    protected BlueUserBank $model;

    #[Inject]
    protected UserBankService $service;


    /**
     * 获取银行列表
     * @param Request $request
     * @return Response
     */
    #[Route(path: "list",methods: "get")]
    public function getBankList(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "name.require"  => trans("empty.require")
            ]);
            if (!is_array($param)) return error($param);
            $data = (new BlueBankCompany)->where("name","like","%{$param['name']}%")->select()->toArray();
            return successTrans("success.data",$data);
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

    /**
     * 绑定银行卡
     * @param Request $request
     * @return Response
     */
    #[Route(path: "bind",methods: "post")]
    public function bindUserBank(Request $request): Response
    {
        try {
            $param = $request->post();
            $param['openid'] = $request->user['openid'];
            if (!$this->validate->scene('add')->check($param)) return error($this->validate->getError());
            $bank = (new BlueBankCompany)->where("bank_code",$param['bank_code'])->findOrEmpty();
            if ($bank->isEmpty()) return error("开户行不存在");
            $param['bank_name'] = $bank['name'];
            $state = $this->model->setAutoData($param);
            if (!$state) return errorTrans("error.data");
            return successTrans("success.data");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


    /**
     * 绑定银行卡列表
     * @param Request $request
     * @return Response
     */
    #[Route(path: "bind/list",methods: "get")]
    public function bindUserList(Request $request): Response
    {
        try {
            $param = $request->all();
            if (empty($param['size'])) return errorTrans("empty.require");
            $param['pageSize'] = $param['size'];
            $param['openid'] = $request->user['openid'];
            $list = $this->service->getList($param);
            return successTrans("success.data",pageFormat($list));
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

}