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

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use EasyWeChat\Pay\Application;
use Modules\Member\Models\Member;
use Modules\Member\Models\MemberAccount;
use Modules\Order\Services\OrderService;
use Modules\Store\Services\PaymentService;
use Modules\Order\Services\RefundService;

class NotifyService {

	public function orderNotify($request){
		$config = Config::get('wechat.miniapp');

		$app = new Application($config);

		$server = $app->getServer();
		// 处理支付结果事件
		$server->handlePaid(function ($message) {
			app(OrderService::class)->paySuccess($message['out_trade_no']);
		});

		return $server->serve();
	}

	public function paymentNotify($request){
		$config = Config::get('wechat.miniapp');

		$app = new Application($config);

		$server = $app->getServer();
		// 处理支付结果事件
		$server->handlePaid(function ($message) {
			app(PaymentService::class)->paySuccess($message['out_trade_no'], $message['transaction_id']);
		});

		return $server->serve();
	}

	public function refundNotify($request){
		$config = Config::get('wechat.miniapp');

		$app = new Application($config);
		$server = $app->getServer();
		// 处理退款结果事件
		$server->handleRefunded(function ($message) {
			app(RefundService::class)->refundSuccess($message);
		});

		return $server->serve();
	}

	public function transferNotify($request){
		$config = Config::get('wechat.miniapp');

		$app = new Application($config);
		$server = $app->getServer();

		//Log::info("转账到零钱异步返回通知：");
		// 处理退款结果事件
		//DB::connection()->enableQueryLog();
		$data= MemberAccount::where(['status'=>1,'detail_status'=>null])->whereNotNull("out_batch_no")->select()->get();
		//print_r(DB::getQueryLog());

		foreach ($data as $key=>$val){
			$result = TransferService::transferQuery($val['out_batch_no'],$val['request_no']);
			if(isset($result['code']) && !empty($result['code'])){
				MemberAccount::where(['id'=>$val['id']])->update(['status'=>-2,'reason'=>$result['message'],'detail_status'=>$result['fail_reason']]);
				//提现失败金额退回
				/*$user = Member::find($val['member_id']);
				$user->money = bcadd($user->money, $val['amount'], 2);
				$user->save();*/
			}else{
				MemberAccount::where(['id'=>$val['id']])->update(['detail_status'=>'SUCCESS']);
			}
		}



		return $server->serve();
	}
}