<?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\Str;
use EasyWeChat\Pay\Application;
use Modules\Wechat\Models\MemberSocial;
use Modules\Order\Models\Order;

class PayService {

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

		$app = new Application($config);

		$utils = $app->getUtils();

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

		$description = "";
		switch ($type) {
			case 'order':
				$data = app('Modules\Order\Services\OrderService')->getjsPayData($request, $from);
				$description = "订单支付";
				$data->amount = $data->amount-$data->integral;
				break;
			case 'payment':
				$data = app('Modules\Store\Services\PaymentService')->getjsPayData($request, $from);
				$description = "店铺收款";
				break;
			default:
				$data = app('Modules\Order\Services\OrderService')->getjsPayData($request, $from);
				$description = "订单支付";
				break;
		}
		$payData = [
			'mchid' => $config['mch_id'],
			'appid' => $config['app_id'],
			'out_trade_no' => $data->order_no,
			'description' => $description,
			'notify_url' => request()->root() .'/api/wechat/notify/'.$type,
			'amount' => [
				'total' => intval($data->amount * 100),
				'currency' => 'CNY',
			],
			'payer' => [
				'openid' => $data->social->openid,
			]
		];

		$response = $app->getClient()->postJson("v3/pay/transactions/jsapi", $payData);

		if($response->isFailed()){
			throw new \Exception($response->getContent(), $response->getStatusCode());
		}

		$prepayId = $response->toArray()['prepay_id'];
		switch ($type) {
			case 'order':
				Order::where('id', $data->id)->update(['pay_no' => $prepayId, 'pay_type' => $from]);
				break;
			case 'payment':
				\Modules\Store\Models\Payment::where('id', $data->id)->update(['payment_sn' => $prepayId, 'payment_type' => $from]);
				break;
			default:
				Order::where('id', $data->id)->update(['pay_no' => $prepayId, 'pay_type' => $from]);
				break;
		}

		if ($from == 'miniapp') {
			return $utils->buildMiniAppConfig($prepayId, $config['app_id'], 'RSA');
		}else if ($from == 'h5') {
			return $utils->buildBridgeConfig($prepayId, $config['app_id'], 'RSA');
		}else if ($from == 'mp') {
			return $utils->buildSdkConfig($prepayId, $config['app_id'], 'RSA');
		}else if ($from == 'app') {
			return $utils->buildAppConfig($prepayId, $config['app_id'], 'RSA');
		}else{
			return $utils->buildMiniAppConfig($prepayId, $config['app_id'], 'RSA');
		}
	}

	public function refund($order, $refund, $detail){
		$config = Config::get('wechat.miniapp');

		$app = new Application($config);
		$api = $app->getClient();

		$refund->out_refund_no = str_replace('-', '', Str::orderedUuid());
		$refund->save();

		$response = $api->postJson("/v3/refund/domestic/refunds", [
			'out_trade_no' => $order->order_no,
			'out_refund_no' => $refund->refund_no,
			'reason' => $refund->reason,
			'notify_url' => request()->root() .'/api/wechat/notify/refund',
			'amount' => [
				'refund' => intval($refund->amount * 100),
				'total' => intval($order->amount * 100),
				'currency' => 'CNY',
			]
		]);
		// if($response->isFailed()){
		// 	throw new \Exception($response->getContent(), $response->getStatusCode());
		// }
	}

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

		$app = new Application($config);
		$api = $app->getClient();

		$response = $api->get("v3/pay/transactions/out-trade-no/{$order_no}", [
			'query' => [
				'mchid' => $config['mch_id'],
			]
		]);

		return $response->toArray();
	}
}