<?php
namespace app\shared\logic\user;
use think\Controller;
use think\facade\Request;
use think\facade\Cache;
use app\shared\model\WeixinUser;
use app\shared\model\User;
use app\shared\model\App;
use think\exception\ValidateException;
class LoginForm extends Base
{
	//账号登录
	public function account_login(){
		
		if($data=request()->post()){
			 try {
	            $rule = [
		             'account|账号'   => 'require',
		             'password|密码'=>'require',
		         ];
	            $this->validate($data,$rule);
	         }catch (ValidateException $e){
	            return fetchJson([],$e->getError(),1);
	         }
	        $account=User::where(['acid'=>$this->acid,'account'=>$data['account'],'password'=>md5($data['account'])])->find();
            if(!$account){
           		return fetchJson('','账号或密码错误',1);
            }
            $account->access_token=create_access_token(4);
            $account->save();
            return fetchJson($account,'登录成功');
	    }
	    return fetchJson('','请求错误',1);
	}
	//小程序登录
	public function wxapp_login(){
        if($data=request()->post()){
			 try {
	            $rule = [
		             'code|Code'   => 'require',
		             'encryptedData|EncryptedData'=>'require',
		             'iv|IV' => 'require',
		         ];
	            $this->validate($data,$rule);
	         }catch (ValidateException $e){
	            return fetchJson([],$e->getError(),1);
	         }
	         $wechatapp=App::where('id',$this->acid)->find();
			 $appid = $wechatapp->wxapp_app_id;
			 $appsecret=$wechatapp->wxapp_app_secret;
	         $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$data['code']}&grant_type=authorization_code";
			 $request=httpRequest($url);
	         $request=json_decode($request);
	         if(isset($request->openid)){
	         	$sessionKey=$request->session_key;
	         	$encryptedData=$data['encryptedData'];
	         	$iv=$data['iv'];
		        $pc = new WXBizDataCrypt($appid, $sessionKey);
				$errCode = $pc->decryptData($encryptedData, $iv, $data);
				if ($errCode == 0) {
				   $data=json_decode($data,true);

				   $unionid=isset($data['unionId'])?$data['unionId']:-1;
				   if($unionid==-1){
				   		$user=WeixinUser::where([
				   			'acid'=>$this->acid,
				   			'wxapp_open_id'=>$request->openid
				   		])->find();
				   }else{
				   		//开放平台的
				   		$user=WeixinUser::where([
				   			'acid'=>$this->acid,
				   			'wx_union_id'=>$data['unionId']
				   		])->find();
				   }
		           if(!$user)
		           	   $user=new WeixinUser();
					   $user->acid=$this->acid;
					   $user->avatar_url=$data['avatarUrl'];
					   $user->sex=$data['gender']==1?'男':'女';
					   $user->city=$data['city'];
					   $user->country=$data['country'];
					   $user->province=$data['province'];
					   $user->wx_union_id=$unionid;
					   $user->save();
		           }
		           $user->nickname=emoji_decode($data['nickName']);
				   $user->avatar_url=$data['avatarUrl'];
		           $user->mobile=input('phone');
		           $user->wxapp_open_id=$request->openid;
		           $user->save();
		           if(!$user->mobile){
		            	return fetchJson('','请获取手机号码',1);
		           }
		           $account=User::where(['acid'=>$this->acid,'account'=>$user->mobile])->find();
		           $user['is_new_user']=0;
		           if(!$account){
		           		$account=new User();
		           		$account->acid=$this->acid;
		           		$account->account=$user->mobile;
		           		$account->password=md5($user->mobile);
		           		$account->parent_id=input('parent_id');
		           		$account->save();
		           		//发放新人优惠券
		           		$isSend=\app\shared\model\Coupon::giveUserCoupon($account->id,1,$this->acid);
		           		$user['is_new_user']=$isSend?1:0;
		           }
		           $account->nickname=$user->nickname;
		           $account->avatar_url=$user->avatar_url;
		           $account->access_token=create_access_token(4);
		           $account->save();
		           $user['access_token']=$account->access_token;
		           return fetchJson($user,'登录成功');
				}else{
	               return fetchJson('','解析错误',1);
				}
	         }
	         return fetchJson('','检查微信参数是否错误',1);
     }
     public function getWxapp(){
     	  if($data=request()->post()){
			 try {
	            $rule = [
		             'code|Code'   => 'require',
		             'encryptedData|EncryptedData'=>'require',
		             'iv|IV' => 'require',
		         ];
	            $this->validate($data,$rule);
	         }catch (ValidateException $e){
	            return fetchJson([],$e->getError(),1);
	         }
	         $wechatapp=App::where('id',$this->acid)->find();
			 $appid = $wechatapp->wxapp_app_id;
			 $appsecret=$wechatapp->wxapp_app_secret;
	         $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$data['code']}&grant_type=authorization_code";
			 $request=httpRequest($url);
	         $request=json_decode($request);
	         if(isset($request->openid)){
	         	$sessionKey=$request->session_key;
	         	$encryptedData=$data['encryptedData'];
	         	$iv=$data['iv'];
		        $pc = new WXBizDataCrypt($appid, $sessionKey);
				$errCode = $pc->decryptData($encryptedData, $iv, $data);
				if ($errCode == 0) {
				   $data=json_decode($data,true);

				   $unionid=isset($data['unionId'])?$data['unionId']:-1;
				   if($unionid==-1){
				   		$user=WeixinUser::where([
				   			'acid'=>$this->acid,
				   			'wxapp_open_id'=>$request->openid
				   		])->find();
				   }else{
				   		//开放平台的
				   		$user=WeixinUser::where([
				   			'acid'=>$this->acid,
				   			'wx_union_id'=>$data['unionId']
				   		])->find();
				   }
		           if(!$user)
		           	   $user=new WeixinUser();
					   $user->acid=$this->acid;
					   $user->avatar_url=$data['avatarUrl'];
					   $user->sex=$data['gender']==1?'男':'女';
					   $user->city=$data['city'];
					   $user->country=$data['country'];
					   $user->province=$data['province'];
					   $user->wx_union_id=$unionid;
					   $user->save();
		           }
		           $user->nickname=emoji_decode($data['nickName']);
				   $user->avatar_url=$data['avatarUrl'];
		           $user->wxapp_open_id=$request->openid;
		           $user->save();
		           $user['is_new_user']=1;
		           if($user->mobile){
		   		 		 $user['is_new_user']=0;
		   		 		 $user['access_token']=User::where(['acid'=>$this->acid,'account'=>$user->mobile])->value('access_token');
		   		 		 if(!$user['access_token']){
		   		 		 	$user['is_new_user']=1;
		   		 		 }
		   		   }
		           return fetchJson($user,'登录成功');
				}else{
	               return fetchJson('','解析错误',1);
				}
	         }
	         return fetchJson('','检查微信参数是否错误',1);
     }
    public function mobileLogin(){
    	$data=request()->post();
    	try {
            $rule = [
	             'mobile|手机号码'   => 'require',
	             'wxapp_open_id|OpenId'   => 'require',
	         ];
            $this->validate($data,$rule);
         }catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
         }
         $user=WeixinUser::where([
   			'acid'=>$this->acid,
   			'wxapp_open_id'=>$data['wxapp_open_id']
   		 ])->find();
   		 $is_new_user=0;
   		 if($user){
   		 	$user->mobile=$data['mobile'];
   		 	$user->save();
   		 }else{
   		 	return fetchJson([],'登录错误',1);
   		 }
   		 $account=User::where(['acid'=>$this->acid,'account'=>$user->mobile])->find();
         if(!$account){
       		$account=new User();
       		$account->acid=$this->acid;
       		$account->account=$user->mobile;
       		$account->password=md5($user->mobile);
       		$account->parent_id=input('parent_id');
       		$account->save();
       		//发放新人优惠券
       		$send=\app\shared\model\Coupon::giveUserCoupon($account->id,1,$this->acid);
       		$is_new_user=$send?1:0;;
        }
        $account->nickname=$user->nickname;
        $account->avatar_url=$user->avatar_url;
        $account->access_token=create_access_token(4);
        $account->save();
        $account['is_new_user']=$is_new_user;
        return fetchJson($account,'登录成功');

    }
	//获取手机号码
	public function wxapp_getphone(){
		if($data=request()->post()){
			try {
	            $rule = [
		             'code|Code'   => 'require',
		             'encryptedData|EncryptedData'=>'require',
		             'iv|IV' => 'require',
		         ];
	            $this->validate($data,$rule);
	         }catch (ValidateException $e){
	            return fetchJson([],$e->getError(),1);
	         }
	         $wechatapp=App::where('id',$this->acid)->find();
			 $appid = $wechatapp->wxapp_app_id;
			 $appsecret=$wechatapp->wxapp_app_secret;
	         $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$data['code']}&grant_type=authorization_code";
			 $request=httpRequest($url);
	         $request=json_decode($request);

	     	 $sessionKey=$request->session_key;
	     	 $encryptedData=$data['encryptedData'];
	     	 $iv=$data['iv'];
	         $pc = new WXBizDataCrypt($appid, $sessionKey);
			 $errCode = $pc->decryptData($encryptedData, $iv, $res);
			 if ($errCode == 0) {
			 	 $data=json_decode($res,true);
			    return fetchJson($data);
			 }else{
			 	return fetchJson('','检查微信参数是否错误',1);
			 }
		}
		return fetchJson('','请求错误',1);
	}
	//H5公众号登录
	public function web_wx_login(){
    	$wechatapp=App::where('id',$this->acid)->find();
		$appid =$wechatapp->wx_app_id;
        $redirect_uri=request()->domain().request()->baseFile();
		$redirect_uri=str_replace('index','dc_wx_h5/wx'.$this->acid.'/web_wx_login',$redirect_uri);
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state='.time().'#wechat_redirect';
        header("Location: $url");
    }
	public function web_wx_login_redirect_uri(){
    	$wx=WechatApp::where('acid',$this->acid)->find();
    	$code=input('code');
    	$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$wx->wx_app_id}&secret={$wx->app_secret}&code={$code}&grant_type=authorization_code";
    	$res=httpRequest($url);
    	$res=json_decode($res);
    	if(isset($res->access_token)){
    		$user_url="https://api.weixin.qq.com/sns/userinfo?access_token={$res->access_token}&openid={$res->openid}&lang=zh_CN";
    		$res_user=httpRequest($user_url);
    		$data=json_decode($res_user,1);
    		$unionid=isset($data['unionid'])?$data['unionid']:-1;
		    if($unionid==-1){
		   		$user=User::where(['acid'=>$this->acid,'wx_open_id'=>$data['unionid']])->find();
		    }else{
		   		//开放平台的
		   		$user=User::where(['acid'=>$this->acid,'wx_union_id'=>$data['unionid']])->find();
		    }
            if(!$user){
           	    $user=new User();
			    $user->acid=$this->acid;
			    $user->nickname=$data['nickname'];
			    $user->avatar_url=$data['headimgurl'];
			    $user->phone='0';
			    $user->access_token=self::create_token();
			    $user->sex=$data['sex']==1?'男':'女';
			    $user->city=$data['city'];
			    $user->country=$data['country'];
			    $user->province=$data['province'];
			    $user->level=-1;
			    $user->status=0;
			    $user->unionid=$unionid;
           }
           $user->wx_openid=$data['openid'];
           $user->save();
           $redirect_uri=$this->request->domain().$this->request->baseFile();
           $redirect_uri=str_replace('index.php','dc_wx_h5/#/pages/login/login?access_token='.$user->access_token,$redirect_uri);
           header("Location: $redirect_uri");
    	}else{
    		$this->error($res->error);
    	}
    }
    //获取access_token
    static public function web_wx_access_token($wx){
    	$access_token=Cache::get('web_wx_access_token_acid'.$wx->acid);
    	if ($access_token) {
    		return ['code'=>0,'msg'=>'','data'=>$access_token];
    	}
    	$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wx->app_id}&secret={$wx->app_secret}";
    	$res=httpRequest($url);
    	$res=json_decode($res);
    	if(isset($res->access_token)){
    		Cache::set('web_wx_access_token_acid'.$wx->acid,$res->access_token,3600);
    		return ['code'=>0,'msg'=>'','data'=>$res->access_token];
    	}else{
    		return ['code'=>$res->errcode,'data'=>'','msg'=>$res->errmsg];
    	}
    }
}
class WXBizDataCrypt
{
    private $appid;
	private $sessionKey;
	/**
	 * 构造函数
	 * @param $sessionKey string 用户在小程序登录后获取的会话密钥
	 * @param $appid string 小程序的appid
	 */
	public function __construct( $appid, $sessionKey)
	{
		$this->sessionKey = $sessionKey;
		$this->appid = $appid;
	}


	/**
	 * 检验数据的真实性，并且获取解密后的明文.
	 * @param $encryptedData string 加密的用户数据
	 * @param $iv string 与用户数据一同返回的初始向量
	 * @param $data string 解密后的原文
     *
	 * @return int 成功0，失败返回对应的错误码
	 */
	public function decryptData( $encryptedData, $iv, &$data )
	{
		if (strlen($this->sessionKey) != 24) {
			return ErrorCode::$IllegalAesKey;
		}
		$aesKey=base64_decode($this->sessionKey);

        
		if (strlen($iv) != 24) {
			return ErrorCode::$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 ErrorCode::$IllegalBuffer;
		}
		if( $dataObj->watermark->appid != $this->appid )
		{
			return ErrorCode::$IllegalBuffer;
		}
		$data = $result;
		return ErrorCode::$OK;
	}

}
class ErrorCode
{
	public static $OK = 0;
	public static $IllegalAesKey = -41001;
	public static $IllegalIv = -41002;
	public static $IllegalBuffer = -41003;
	public static $DecodeBase64Error = -41004;
}
