<?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;

class UsersController extends Controller
{

    public function user_oauth(Request $request){
        $url = $request->input('redirect_url');

        $appid = $request->input('gzh_app_id');
        $secter = $this->getAppSecretByAppId($appid);
        $params['appid'] = $appid;
        $params['redirect_url'] = $url;
        $options = [
            'app_id'=>$appid,
            'secret'=>$secter,
            'oauth' => [
                'scopes'   => ['snsapi_base'],
                'callback' => env('AUTH_CALLBACK_URL').'?'.http_build_query($params),
            ],
        ];
        /*Log::info('official auth-------------');
        Log::info($request->all());
        Log::info($options);*/
        $app = new Application($options);
        return $app->oauth->redirect();
    }



    /**
     * 微信授权回掉
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function wcback(Request $request,$distribution_channel_id)
    {
        if(!is_numeric($distribution_channel_id)){
            $distribution_channel_id = decodeDistributionChannelId($distribution_channel_id);
        }
        $url = Cookie::get('auth_redirect');
        $uuid = $request->input('unionid');
        $openid = $request->input('openid');
        Log::info($request->all());
        Log::info('-------------------------' . urldecode($url));
        $url_info = parse_url(urldecode($url));
        //$distribution_channel_id = str_replace('site', '', explode('.', $url_info['host'])[0]);
        Log::info('distribution_channel_id-----------------------------');
        Log::info($distribution_channel_id);
        $user = UserService::getUserByUnionAndChannelId($openid,$distribution_channel_id);
        if(!$user){
            //if(in_array($distribution_channel_id,[4404])){
            if(array_key_exists($distribution_channel_id,specialChannelAuthInfo())){
                $url = urldecode($url);
                return redirect()->to($this->joinUrl($url));
            }
            $user = $this->createUser(
                [
                    'openid' => $openid,
                    'unionid' => $uuid,
                    'distribution_channel_id' => $distribution_channel_id,
                    'send_order_id' => Cookie::get('send_order_id')
                ]
            );
            
            // 注册动作
            $action_type = 'Register';
            $param = [
               'openid' => $openid,
               'uid' => isset($user->id)?$user->id:'0',
            ];
            UserService::PushUserActionToQueue($action_type,$distribution_channel_id,$param);
            
        }


        if($user && !empty($user->id)){

        }

        Cookie::queue(env('COOKIE_AUTH_WEB_WECHAT'), $user->id, env('U_COOKIE_EXPIRE'), null, null, false, false);
        Cookie::queue('reader_share_bid',null);
        Cookie::queue('reader_share_cid',null);

        return redirect()->to(urldecode($url));
    }

    /**
     * 微信授权回掉
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function wcbackV2(Request $request,$distribution_channel_id)
    {
        if(!is_numeric($distribution_channel_id)){
            $distribution_channel_id = decodeDistributionChannelId($distribution_channel_id);
        }
        $url = Cookie::get('auth_redirect');
        $uuid = $request->input('unionid');
        $openid = $request->input('openid');

        $user = UserService::getUserByUnionAndChannelId($openid,$distribution_channel_id);
        if(!$user){
            $user = $this->createUserV2(
                [
                    'openid' => $openid,
                    'unionid' => $uuid,
                    'distribution_channel_id' => $distribution_channel_id,
                    'send_order_id' => Cookie::get('send_order_id')
                ]
            );
            
            // 注册动作
            $action_type = 'Register';
            $param = [
	            'openid' => $openid,
	            'uid' => isset($user->id)?$user->id:'0',
            ];
            UserService::PushUserActionToQueue($action_type,$distribution_channel_id,$param);
            
        }

        Cookie::queue(env('COOKIE_AUTH_WEB_WECHAT'), $user->id, env('U_COOKIE_EXPIRE'), null, null, false, false);
        Cookie::queue('reader_share_bid',null);
        Cookie::queue('reader_share_cid',null);

        return redirect()->to(urldecode($url));
    }

    public function wcbackTest(Request $request,$distribution_channel_id)
    {
        if(!is_numeric($distribution_channel_id)){
            $distribution_channel_id = decodeDistributionChannelId($distribution_channel_id);
        }
        $param = $request->all();
        $param['distribution_channel_id'] = $distribution_channel_id;
        return $param;
    }

    private function joinUrl($url){
        if(strpos($url,'?') !== false){
            $result =   $url.'&auth=v2';
        }else{
            $result = $url.'?auth=v2';
        }
        return $result;
    }

    /**
     * 授权用户信息
     * @param $data
     * @return bool
     */
    protected function createUser($data)
    {
        if (empty($data['unionid']) || empty($data['openid'])) return false;
        /*$user = UserService::getUserByUnionAndChannelId($data['openid'],$data['distribution_channel_id']);
        if ($user) return $user;*/

        $user =  UserService::addUser(
            ['openid' => $data['openid'],
                'unionid' => $data['unionid'],
                'distribution_channel_id' => $data['distribution_channel_id'],
                'send_order_id'=>$data['send_order_id'],
                'is_new'=>1
            ]);
        if($user && !empty($user->id)){
            $this->share($user->id,$data['distribution_channel_id']);
        }
        return $user;
    }

    protected function createUserV2($data)
    {
        if (empty($data['unionid']) || empty($data['openid'])) return false;
        /*$user = UserService::getUserByUnionAndChannelId($data['openid'],$data['distribution_channel_id']);
        if ($user) return $user;*/

        $user =  UserService::addUser(
            ['openid' => $data['openid'],
                'unionid' => $data['unionid'],
                'distribution_channel_id' => $data['distribution_channel_id'],
                'send_order_id'=>$data['send_order_id'],
                'is_new'=>2
            ]);
        if($user && !empty($user->id)){
            $this->share($user->id,$data['distribution_channel_id']);
        }
        return $user;
    }

    private function share($uid,$distribution_channel_id){
        //阅读器裂变统计
        $share_from = Cookie::get('reader_share_bid');
        $share_cid = Cookie::get('reader_share_cid');
        if($share_from && $uid){
            $from_uid = 0;
            try{
                $share_from_arr = explode('-',$share_from);
                $share_bid = $share_from_arr[0];
                if(isset($share_from_arr[1])){
                    $from_uid = $share_from_arr[1];
                }
            }catch (\Exception $e){
                $share_bid = 0;
            }
            WapReaderPageFissionService::createV2($uid,$share_bid,$distribution_channel_id,'register',$from_uid,$share_cid);
        }
    }


    public function wcCallbackParse(Request $request){
        $appid = $request->input('appid');
        $secret = $this->getAppSecretByAppId($appid);
        $url = $request->input('redirect_url');

        if(strpos($url,'zsypay') > -1){

        }else{
            $url = urldecode($url);
        }

        $options = [
            'app_id'=>$appid,
            'secret'=>$secret,
        ];
        $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'];
        }

        if(strpos($url,'?') > -1){
            $url = $url.'&openid='.$user_data['openid'].'&unionid='.$user_data['unionid'];
        }else{
            $url = $url.'?openid='.$user_data['openid'].'&unionid='.$user_data['unionid'];
        }

        /*if(isset($url_arr['query'])){
            $url .= '&openid='.$user_data['openid'].'&unionid='.$user_data['unionid'];
        }else{
            $url .= '?openid='.$user_data['openid'].'&unionid='.$user_data['unionid'];
        }*/
        /*Log::info('url is --------------');
        Log::info($url);*/
        return redirect()->to($url);
    }

    /**
     * 根据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 '';
    }
}