<?php

namespace App\Http\Controllers\WeChatApplet;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;
use App\Services\WeChatApplet\User\LoginUserService;

class WeChatAuthController extends Controller
{
	// 微信授权
    public function weixinAuth(Request $request)
    {
		// 记录日志
		$log_record['request'] = $request->all();
		$log_record['time'] = date('Y-m-d H:i:s');
		$log_record['function'] = 'weixinAuth';
		logFileRecord($log_record, 'wash/WeChatAuth', 2);

        $appid = config('apisystem.car_owner_appid');
        $appsecret = config('apisystem.car_owner_appsecret');
        // $js_code = "091xu9000devCM1u9f00097ZiS2xu90c";
        $js_code = $request['js_code'];//小程序传值
		// 登录凭证校验。
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$js_code."&grant_type=authorization_code";
        // $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx3d5338c9dbe01eaf&secret=23d512f5ebc9c1f3cf1b6f23a91ce77d&js_code=001xBp000RcdCM1VFD3003BHlZ0xBp0S&grant_type=authorization_code';
        $result = file_get_contents($url);
		$code2Session = json_decode($result, true);//小程序登录返回的数据

		if(!empty($code2Session['openid'])){
			$login_user_service = new LoginUserService();
			$return_data = $login_user_service->weixinAuth($code2Session,$request);
			// 记录日志
			$log_record['return_data'] = $return_data;
			$log_record['time'] = date('Y-m-d H:i:s');
			$log_record['function'] = 'weixinAuth1';
			logFileRecord($log_record, 'wash/new/WeChatAuth', 2);
			// 查询用户id
			// $weus_id = DB::table('weixin_user')
			// 	->where("weus_openid", $code2Session['openid'])
			// 	->value('weus_id');
			// if ($weus_id) {
			// 	$weus_data['weus_session_key'] = $code2Session['session_key'];
			// 	$weus_data['weus_update_time'] = date('Y-m-d H:i:s');
			// 	$weus_res = DB::table('weixin_user')
			// 		->where("weus_id", $weus_id)
			// 		->update($weus_data);
			// } else {
			// 	$weus_data['weus_openid'] = $code2Session['openid'];
			// 	$weus_data['weus_session_key'] = $code2Session['session_key'];
			// 	$weus_data['weus_update_time'] = date('Y-m-d H:i:s');
			// 	$weus_id = DB::table('weixin_user')->insertGetId($weus_data);
			// }
			// $return_data['openid'] = $code2Session['openid'];
			return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
		} else {
			return response()->json(['code'=>500, 'msg'=>'登录凭证校验失败 '.$code2Session['errcode'], 'data'=>'']);
		}
    }

    // pc端扫码授权
    public function pcWeixinAuth(Request $request)
    {
		// 记录日志
		$log_record['request'] = $request->all();
		$log_record['time'] = date('Y-m-d H:i:s');
		$log_record['function'] = 'pcWeixinAuth';
		logFileRecord($log_record, 'wash/WeChatAuth', 2);

        $appid = config('apisystem.car_owner_appid');
        $appsecret = config('apisystem.car_owner_appsecret');
        // $js_code = "091xu9000devCM1u9f00097ZiS2xu90c";
        if (!isset($request['js_code']) || empty($request['js_code'])) {
        	return response()->json(['code'=>500, 'msg'=>'请授权登录 ', 'data'=>'']);
        }

        $js_code = $request['js_code'];//小程序传值
		// 登录凭证校验。
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$js_code."&grant_type=authorization_code";
        // $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx3d5338c9dbe01eaf&secret=23d512f5ebc9c1f3cf1b6f23a91ce77d&js_code=001xBp000RcdCM1VFD3003BHlZ0xBp0S&grant_type=authorization_code';
        $result = file_get_contents($url);
		$code2Session = json_decode($result, true);//小程序登录返回的数据
		if(!empty($code2Session['openid'])){
			$login_user_service = new LoginUserService();
			$return_data = $login_user_service->pcweixinAuth($code2Session,$request);
			// 记录日志
			$log_record['return_data'] = $return_data;
			$log_record['time'] = date('Y-m-d H:i:s');
			$log_record['function'] = 'pcWeixinAuth';
			logFileRecord($log_record, 'wash/new/WeChatAuth', 2);
			return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
		} else {
			return response()->json(['code'=>500, 'msg'=>'登录凭证校验失败 '.$code2Session['errcode'], 'data'=>'']);
		}
    }

	// 微信数据解密
	public function decryption(Request $request)
	{
		// $appid = 'wx4f4bc4dec97d474b';
		// $sessionKey = 'tiihtNczf5v6AKRyjwEUhQ==';

		// $encryptedData="CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM
		// 				QmRzooG2xrDcvSnxIMXFufNstNGTyaGS
		// 				9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+
		// 				3hVbJSRgv+4lGOETKUQz6OYStslQ142d
		// 				NCuabNPGBzlooOmB231qMM85d2/fV6Ch
		// 				evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6
		// 				/1Xx1COxFvrc2d7UL/lmHInNlxuacJXw
		// 				u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn
		// 				/Hz7saL8xz+W//FRAUid1OksQaQx4CMs
		// 				8LOddcQhULW4ucetDf96JcR3g0gfRK4P
		// 				C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB
		// 				6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns
		// 				/8wR2SiRS7MNACwTyrGvt9ts8p12PKFd
		// 				lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV
		// 				oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG
		// 				20f0a04COwfneQAGGwd5oa+T8yO5hzuy
		// 				Db/XcxxmK01EpqOyuxINew==";

		// $iv = 'r7BXXKkLb8qrSNn05n0qiA==';
		// 记录日志
		$log_record['request'] = $request->all();
		$log_record['time'] = date('Y-m-d H:i:s');
		$log_record['function'] = 'decryption';
		logFileRecord($log_record, 'wash/WeChatAuth', 2);

		$appid = config('apisystem.car_owner_appid');
        $appsecret = config('apisystem.car_owner_appsecret');
		if (isset($request['session_key']) && !empty($request['session_key'])) {
			$sessionKey = $request['session_key'];
		} else {
			$sessionKey = DB::table('weixin_user')
				->where("weus_openid", $request['openid'])
				->value('weus_session_key');
			if (isset($request['source']) && $request['source'] == 2) {
				$sessionKey = DB::table('admin')
					->where("adm_bjfw_openid", $request['openid'])
					->value('adm_session_key');
			}
		}
		$encryptedData = $request['encryptedData'];
		$iv = $request['iv'];
		$return_code = $this->decryptData($appid, $sessionKey, $encryptedData, $iv, $data);//微信数据解密
		if ($return_code == 200) {
			$return_data = json_decode($data, true);//小程序登录返回的数据
			return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
		} else {
			return response()->json(['code'=>500, 'msg'=>'解密失败 '.$return_code, 'data'=>'']);
		}
	}

	/**
	 * 检验数据的真实性，并且获取解密后的明文.
	 * @param $encryptedData string 加密的用户数据
	 * @param $iv string 与用户数据一同返回的初始向量
	 * @param $data string 解密后的原文
     *
	 * @return int 成功0，失败返回对应的错误码
	 */
	private function decryptData($appid, $sessionKey, $encryptedData, $iv, &$data)
	{
		$OK = 200;
		$IllegalAesKey = -41001;
		$IllegalIv = -41002;
		$IllegalBuffer = -41003;
		$DecodeBase64Error = -41004;

		if (strlen($sessionKey) != 24) {
			return $IllegalAesKey;
		}
		$aesKey=base64_decode($sessionKey);
        
		if (strlen($iv) != 24) {
			return $IllegalIv;
		}
		$aesIV=base64_decode($iv);

		$aesCipher=base64_decode($encryptedData);

		$result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
		$dataObj=json_decode( $result );
		if( $dataObj  == NULL )
		{
//			return $result."--".$IllegalBuffer;
            return $IllegalBuffer;
		}
		if( $dataObj->watermark->appid != $appid )
		{
//            return $result."--".$IllegalBuffer;
            return $IllegalBuffer;
		}
		$data = $result;
		return $OK;
	}

	/**
	 * 注册账号
	 * @authors ldj
	 * @email  909490343@qq.com
	 * @date   2023-11-17
	 * @param  Request          $request [description]
	 * @return [type]                    [description]
	 */
	public function register(Request $request){
		// 记录日志
		$log_record['request'] = $request->all();
		$log_record['time'] = date('Y-m-d H:i:s');
		$log_record['function'] = 'register';
		logFileRecord($log_record, 'wash/WeChatAuth', 2);

        $appid = config('apisystem.car_owner_appid');
        $appsecret = config('apisystem.car_owner_appsecret');
        $js_code = $request['js_code'];//小程序传值
		// 登录凭证校验。
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$js_code."&grant_type=authorization_code";
        $result = file_get_contents($url);
		$code2Session = json_decode($result, true);//小程序登录返回的数据

		if(!empty($code2Session['openid'])){
			$login_user_service = new LoginUserService();
			$return_data = $login_user_service->register($code2Session,$request);
		}
	}
}
