<?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\Storage;
use Illuminate\Support\Facades\Config;
use EasyWeChat\MiniApp\Application;

class WechatService {
	public function getSingleQrcode($request){
		$config = config('wechat.miniapp');

		$doctor_id = $request->input('doctor_id');
		$refresh = $request->input('refresh', 0);
		$pic_name = md5('doctor_' . $doctor_id);
		$path = "qrcode/{$pic_name}.png";
		if (Storage::disk('public')->exists($path) && !$refresh) {
			return Storage::disk('public')->url($path);
		}

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

		$response = $client->postJson('/wxa/getwxacodeunlimit', [
			'scene' => $doctor_id,
			'page' => 'pages/health/patient/form',
			'width' => 430,
			'check_path' => false,
			// 'env_version' => $config['env_version'],
		]);

		if ($response->isFailed()) {
			throw new \Exception($response->getContent(), $response->getStatusCode());
		}else{
			Storage::disk('public')->put($path, $response->toStream());
			return Storage::disk('public')->url($path);
		}
	}

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

		$app = new Application($config);
		$refresh = $request->input('refresh', 0);
		$pic_name = md5('invite_code_' . $request->input('uid', ''));
		$path = "qrcode/{$pic_name}.png";
		if (Storage::disk('public')->exists($path) && !$refresh) {
			return Storage::disk('public')->url($path);
		}

		$client = $app->getClient();

		$response = $client->postJson('/wxa/getwxacodeunlimit', [
			'scene' => 'invite_uid=' . $request->input('uid', ''),
			'page' => 'pages/ucenter/login/index',
			'width' => 430,
			'check_path' => false,
			// 'env_version' => $config['env_version'],
		]);

		if ($response->isFailed()) {
			throw new \Exception($response->getContent(), $response->getStatusCode());
		}else{
			Storage::disk('public')->put($path, $response->toStream());
			return Storage::disk('public')->url($path);
		}
	}
}
