<?php

namespace App\Http\Controllers\Wap\Oauth;

use App\Modules\User\Services\WapReaderPageFissionService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Cookie;
use App\Modules\User\Services\UserService;
use Log;
use EasyWeChat\Foundation\Application;
use DB;
use Hashids;
use Redis;

class UsersV2Controller extends Controller
{
    public function user_oauth(Request $request){
        Log::info('UsersV2Controller--user_oauth--enter-----------');
        Log::info($request->all());
        $url = $request->get('redirect_url');
        $appid = $request->get('gzh_app_id');
        $channel_id = $request->get('channel_id');
        $sid = $request->get('sid');
        $secter = $this->getAppSecretByAppId($appid);
        $params['appid'] = $appid;
        $params['redirect_url'] = $url;
        $params['channel_id'] = $channel_id;
        $params['sid'] = $sid;
        $options = [
            'app_id'=>$appid,
            'secret'=>$secter,
            'oauth' => [
                'scopes'   => ['snsapi_base'],
                'callback' => env('AUTH_CALLBACK_URL').'?'.http_build_query($params),
            ],
        ];
        Log::info('$options is:');
        Log::info($options);
        $app = new Application($options);
        return $app->oauth->redirect();
    }


    public function wcCallbackParse(Request $request){
        Log::info('UsersV2Controller--wcCallbackParse--enter-----------');
        Log::info($request->all());
        $appid = $request->get('appid');
        $secret = $this->getAppSecretByAppId($appid);
        $url = $request->get('redirect_url');
        $distribution_channel_id = $request->get('channel_id');
        $send_order_id = $request->get('sid');
        $url = urldecode($url);
        $options = [
            'app_id'=>$appid,
            'secret'=>$secret,
        ];
        $url_info = parse_url($url);
        $app = new Application($options);

        $user = $app->oauth->user();
        $user_data = $user['original'];
        Log::info('$user_data is: ');
        Log::info($user_data);
        if(!isset($user_data['unionid'])){
            $user_data['unionid'] = $user_data['openid'];
        }
        $openid = $user_data['openid'];
        $unionid = $user_data['unionid'];
        $user = UserService::getUserByUnionAndChannelId($openid,$distribution_channel_id);
        !isset($url_info['path']) && $url_info['path'] = '/';
        $rp = [];
        $ip = '';
        if(isset($url_info['query'])){
            parse_str($url_info['query'],$rp);
            if(isset($rp['ip'])){
                $ip = $rp['ip'];
                unset($rp['ip']);
            }
        }
        !$user && $user = $this->createUser($openid,$unionid,$distribution_channel_id,$send_order_id,$ip);

        $query = ['auth_uid'=>$user->id,'atime'=>time()];
        $sign = get_sign($query);
        $query['sign'] = $sign;
        if($rp) $query = array_merge($query,$rp);

        $url = sprintf('%s://%s%s?%s',$url_info['scheme'],$url_info['host'],$url_info['path'],http_build_query($query));
        Log::info('wcCallbackParse back url is :');
        Log::info($url);
        if($send_order_id){
            try{
                Redis::hset('book_read:' . $user->id, 'send_order_id', $send_order_id);
            }catch (\Exception $e){}
        }
        //$previous = url()->previous();
        return redirect()->to($url)->withHeaders(['referer'=>url()->current()]);
    }

    public function wcCallbackParse2(Request $request){
        Log::info('UsersV2Controller--wcCallbackParse--enter-----------');
        Log::info($request->all());
        $appid = $request->get('appid');
        $secret = $this->getAppSecretByAppId($appid);
        $url = $request->get('redirect_url');
        $distribution_channel_id = $request->get('channel_id');
        $send_order_id = $request->get('sid');
        $auth_times = $request->get('auth_times',1);
        $url = urldecode($url);
        $options = [
            'app_id'=>$appid,
            'secret'=>$secret,
        ];
        $url_info = parse_url($url);
        $app = new Application($options);

        $user = $app->oauth->user();
        $user_data = $user['original'];
        Log::info('$user_data is: ');
        Log::info($user_data);
        if(!isset($user_data['unionid'])){
            $user_data['unionid'] = $user_data['openid'];
        }
        $openid = $user_data['openid'];
        $unionid = $user_data['unionid'];
        $user = UserService::getUserByUnionAndChannelId($openid,$distribution_channel_id);
        !isset($url_info['path']) && $url_info['path'] = '/';
        $ip = '';
        $rp = [];
        if(isset($url_info['query'])){
            parse_str($url_info['query'],$rp);
            if(isset($rp['ip'])){
                $ip = $rp['ip'];
                unset($rp['ip']);
            }
        }
        if(!$user){
            $auth_redirect_two_appids = specialChannelAuthInfo();
            if($auth_times == 1 && $auth_redirect_two_appids && isset($auth_redirect_two_appids[$distribution_channel_id])){
                $params['redirect_url'] = $request->get('redirect_url');
                $params['timestamp'] = time();
                $params['channel_id'] = $distribution_channel_id;
                $params['appid'] = $auth_redirect_two_appids[$distribution_channel_id];
                $params['sid'] = $send_order_id;
                $params['auth_times'] = 2;
                //$params['sign'] = $this->getSign($params, env('OAUTH_KEY'));
                $secret = $this->getAppSecretByAppId($auth_redirect_two_appids[$distribution_channel_id]);
                $options = [
                    'app_id' => $auth_redirect_two_appids[$distribution_channel_id],
                    'secret' => $secret,
                    'oauth' => [
                        'scopes' => ['snsapi_base'],
                        'callback' => env('AUTH_CALLBACK_URL_V2_2') . '?' . http_build_query($params),],];
                $app = new Application($options);
                return $app->oauth->redirect();
            }else{
                $user = $this->createUser($openid,$unionid,$distribution_channel_id,$send_order_id,$ip);
            }
        }

        $query = ['auth_uid'=>$user->id,'atime'=>time()];
        $sign = get_sign($query);
        $query['sign'] = $sign;
        if($rp) $query = array_merge($query,$rp);
        $url = sprintf('%s://%s%s?%s',$url_info['scheme'],$url_info['host'],$url_info['path'],http_build_query($query));
        Log::info('wcCallbackParse back url is :');
        Log::info($url);
        if($send_order_id){
            try{
                Redis::hset('book_read:' . $user->id, 'send_order_id', $send_order_id);
            }catch (\Exception $e){}
        }
        //$previous = url()->previous();
        return redirect()->to($url);
    }

    private function createUser($openid,$unionid,$distribution_channel_id,$send_order_id,$ip){
        $user =  UserService::addUser(
            ['openid' => $openid,
                'unionid' => $unionid,
                'distribution_channel_id' =>$distribution_channel_id,
                'send_order_id'=>$send_order_id,
                'is_new'=>1,
                'register_ip'=>$ip
            ]);
        // 注册动作
        $action_type = 'Register';
        $param = [
            'openid' => $openid,
            'uid' => isset($user->id)?$user->id:'0',
        ];
        UserService::PushUserActionToQueue($action_type,$distribution_channel_id,$param);
        return $user;
    }

    /**
     * 根据apid获取secret
     * @param $appId
     * @return string
     */
    private function getAppSecretByAppId($appId){
        $info = DB::table('official_setting')->where('appid',$appId)->select('secret')->first();
        if($info){
            return $info->secret;
        }
        return '';
    }

}
