<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace Modules\Member\Services;

use Modules\Member\Models\MemberBank;

class BankService {

	public function getDataList($request){
		$map = [];

		$query = MemberBank::query();

		if ($request->filled('title')) {
			$map[] = ['title', 'like', '%' . $request->input('title') . '%'];
		}
		if ($request->filled('name')) {
			$map[] = ['name', 'like', '%' . $request->input('name') . '%'];
		}
		if ($request->filled('is_user')) {
			$map[] = ['member_id', '=', auth('api')->user()['uid']];
		}

		$query = $query->where($map);

		$query->orderBy($request->input('order', 'id'), $request->input('sort', 'desc'));
		if($request->filled('page')){
			$data = [
				'total' => $query->count(),
				'page' => $request->input('page', 1),
				'data' => $query->offset($request->input('offset', 0))->limit($request->input('limit', 10))->get(),
			];
		}else{
			$data = $query->get();
		}
	}

	public function create($request){
		$request->validate([
				'name' => 'required',
				'bank_name' => 'required',
				'bank_card' => 'required',
			],
			[
				'name.required' => '真实姓名不能为空',
				'bank_name.required' => '银行名称不能为空',
				'bank_card.required' => '银行账号不能为空',
			]
		);

		$bank = MemberBank::where('bank_card', $request->input('bank_card'))->where('member_id', auth('api')->user()['uid'])->first();
		if(!$bank){
			$bank = new MemberBank();
		}

		foreach($bank->setFilterFields($request->all()) as $key => $value){
			$bank->$key = $value;
		}
		$bank->member_id = auth('api')->user()['uid'];

		$bank->save();
		return $bank;
	}

	public function update($request, $id){
		$request->validate([
				'name' => 'required',
				'bank_name' => 'required',
				'bank_card' => 'required',
			],
			[
				'name.required' => '真实姓名不能为空',
				'bank_name.required' => '银行名称不能为空',
				'bank_card.required' => '银行账号不能为空',
			]
		);
		$bank = MemberBank::find($id);

		if(!$bank){
			throw new \Exception('银行卡不存在');
		}
		foreach($bank->setFilterFields($request->all()) as $key => $value){
			$bank->$key = $value;
		}

		$bank->save();
		return $bank;
	}

	public function delete($request){
		$bank = MemberBank::find($request->input('id'));

		if(!$bank){
			throw new \Exception('银行卡不存在');
		}

		$bank->delete();
		return $bank;
	}
}