<?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\Store\Services;

use Modules\Store\Models\Payment;
use Modules\Member\Services\AccountService;
use Modules\Member\Services\ScoreService;
use Illuminate\Support\Str;

class PaymentService {

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

		$query = Payment::with(['store:id,title,logo', 'member:uid,username,nickname,avatar']);

		if($request->filled('order_no')){
			$map[] = ['order_no', 'like', '%'.$request->input('title').'%'];
		}

		if($request->filled('status')){
			$map[] = ['status', '=', $request->input('status')];
		}

		if($request->filled('store_master')){
			$query->whereHas('store', function($query) use ($request){
				$query->where('member_id', '=', $request->input('store_master'));
			});
		}

		$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->limit($request->input('limit', 1000))->get();
		}
		return $data;
	}

	public function create($store_id, $amount, $integral, $remark){
		$payment = new Payment();


		$payment->order_no = str_replace('-', '', Str::orderedUuid());
		$payment->store_id = $store_id;
		$payment->member_id = auth('api')->user()->uid;
		$payment->amount = $amount;
		$payment->integral = $integral;
		$payment->payment_remark = $remark ? $remark : '店铺收款';
		$payment->payment_status = 0;

		//判断积分是否满足
		$member = auth('api')->user();
		if($member['score'] < $integral){
			throw new \Exception("积分不足!", 0);
		}

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

	public function update(){
	}

	public function delete(){
	}

	public function qrcode($request){

	}

	public function getjsPayData($request, $type){
		$payment = Payment::with(['member:uid,username'=> ['social']])->where('id', $request->input('payment_id'))->first();
		if(!$payment){
			throw new \Exception("订单不存在!", 0);
		}
		if(isset($payment['member']['social'])){
			foreach ($payment['member']['social'] as $value) {
				$payment->social = $value['type'] == $type ? $value : [];
			}
		}

		\Modules\Store\Events\PayData::dispatch($payment);
		return $payment;
	}

	public function paySuccess($order_no, $payment_no){
		$payment = Payment::where('order_no', $order_no)->first();

		if($payment && $payment->status == 0){
			$res = app(\Modules\Wechat\Services\PayService::class)->orderQuery($order_no);
			if(isset($res['trade_state']) && $res['trade_state'] == 'SUCCESS'){
				$payment->payment_status = 1;
				$payment->payment_time = date('Y-m-d H:i:s');
				$payment->payment_sn = $payment_no;
				$payment->save();

				// app(ShippingService::class)->pushShipping($order_no, $payment->member_id, '店铺内付款支付');
				\Modules\Store\Events\PaySuccess::dispatch($payment);
			}
		}
	}

	public function userTransfer($request){
		$request->validate([
			'type' => 'required',
			'amount' => 'required',
			'uid' => 'required',
		], [
			'type.required' => '请选择转账类型',
			'amount.required' => '请输入转账金额',
			'uid.required' => '请输入转账用户',
		]);
		$type = $request->input('type', 'amount');
		$amount = $request->input('amount');
		$uid = $request->input('uid');

		if($type == 'score' && auth('api')->user()['score'] < $amount){
			throw new \Exception("积分不足!", 0);
		}

		if($type == 'amount' && auth('api')->user()['money'] < $amount){
			throw new \Exception("金额不足!", 0);
		}

		if($uid == auth('api')->user()['uid']){
			throw new \Exception("不能自己转账自己!", 0);
		}

		if($amount < 1){
			throw new \Exception("额度不能小于1!", 0);
		}

		$member = \Modules\Member\Models\Member::where('uid', $uid)->first();
		if(!$member){
			throw new \Exception("用户不存在!", 0);
		}

		switch ($type) {
			case 'amount':
				app(AccountService::class)->createAccount(
					store_id: 0,
					order_id: 0,
					member_id: auth('api')->user()['uid'],
					type: 'transfer',
					account_type: 'member',
					amount: $amount,
					remark: '用户转账扣除'
				);
				app(AccountService::class)->createAccount(
					store_id: 0,
					order_id: 0,
					member_id: $uid,
					type: 'income',
					account_type: 'member',
					amount: $amount,
					remark: '用户转账'
				);
				break;
			case 'score':
				app(ScoreService::class)->createScore(
					store_id: 0,
					order_id: 0,
					member_id: auth('api')->user()['uid'],
					amount: $amount,
					type: 'transfer',
					account_type: 'member',
					remark: '用户转账扣除'
				);
				app(ScoreService::class)->createScore(
					store_id: 0,
					order_id: 0,
					member_id: $uid,
					amount: $amount,
					type: 'income',
					account_type: 'member',
					remark: '用户转账'
				);
				break;
			default:
				app(ScoreService::class)->createScore(
					store_id: 0,
					order_id: 0,
					member_id: auth('api')->user()['uid'],
					amount: $amount,
					type: 'transfer',
					account_type: 'member',
					remark: '用户转账扣除'
				);
				app(ScoreService::class)->createScore(
					store_id: 0,
					order_id: 0,
					member_id: $uid,
					amount: $amount,
					type: 'income',
					account_type: 'member',
					remark: '用户转账'
				);
				break;
		}
		return true;
	}

	/**
	 * @title 分仓收款
	 *
	 * @param Request $request
	 * @return void
	 */
	public function receiveAccount($request){
		$request->validate([
			'type' => 'required',
			'amount' => 'required',
			'service_id' => 'required',
		], [
			'type.required' => '请选择转账类型',
			'amount.required' => '请输入转账金额',
			'service_id.required' => '请输入分仓ID',
		]);

		$type = $request->input('type', 'amount');
		$amount = $request->input('amount');
		$service_id = $request->input('service_id');

		$service = \Modules\Auth\Models\Admin::where('uid', $service_id)->first();
		if(!$service){
			throw new \Exception("分仓不存在!", 0);
		}

		if($type == 'score' && auth('api')->user()['score'] < $amount){
			throw new \Exception("积分不足!", 0);
		}

		if($type == 'amount' && auth('api')->user()['money'] < $amount){
			throw new \Exception("金额不足!", 0);
		}

		if($amount < 1){
			throw new \Exception("额度不能小于1!", 0);
		}

		switch ($type) {
			case 'amount':
				app(AccountService::class)->createAccount(
					store_id: 0,
					order_id: 0,
					member_id: $service_id,
					type: 'transfer',
					account_type: 'receive',
					amount: $amount,
					remark: '店铺转账扣除'
				);
				app(AccountService::class)->createAccount(
					store_id: 0,
					order_id: 0,
					member_id: auth('api')->user()['uid'],
					type: 'service_income',
					account_type: 'receive',
					amount: $amount,
					remark: '店铺转账'
				);
				break;
			case 'score':
				app(ScoreService::class)->createScore(
					store_id: 0,
					order_id: 0,
					member_id: auth('api')->user()['uid'],
					amount: $amount,
					type: 'transfer',
					account_type: 'receive',
					remark: '店铺转账扣除'
				);
				app(ScoreService::class)->createScore(
					store_id: 0,
					order_id: 0,
					member_id: $service_id,
					amount: $amount,
					type: 'service_income',
					account_type: 'receive',
					remark: '店铺转账'
				);
				break;
			default:
				break;
		}
		return true;
	}
}