<?php

namespace App\Http\Controllers\WeChatApplet;

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

use DB;
use App\Services\WeChatApplet\Technician\LoginTechnicianService;

class WeChatThAuthController extends Controller
{
    // protected $appid = 'wx3d5338c9dbe01eaf';//半径服务
    // protected $appsecret = '23d512f5ebc9c1f3cf1b6f23a91ce77d';//小程序秘钥
    protected $appid = 'wx5a9e016f8ebb40c7';
    protected $appsecret = 'b190afa86b4fab975d46e701d27a04e5';//半径美装小程序秘钥

	// 微信授权
    public function weixinThAuth(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/weixinThAuth', 2);

        $appid = $this->appid;
        $appsecret = $this->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_Technician_service = new LoginTechnicianService();
			$return_data = $login_Technician_service->weixinthAuth($code2Session);
			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)
	{
		// 记录日志
		$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 = $this->appid;
		if (isset($request['session_key'])) {
			$sessionKey = $request['session_key'];
		} else {
			$sessionKey = DB::table('admin')
				->where("adm_open_id", $request['openid'])
				->value('adm_session_key');
		}
		$encryptedData = $request['encryptedData'];
		$iv = $request['iv'];
		$return_code = $this->decryptData($appid, $sessionKey, $encryptedData, $iv, $data);//微信数据解密
		if ($return_code == 0) {
			$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 = 0;
		$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 $IllegalBuffer;
		}
		if( $dataObj->watermark->appid != $appid )
		{
			return $IllegalBuffer;
		}
		$data = $result;
		return $OK;
	}
}
