<?php

namespace App\Http\Controllers\Wap\User;

use App\Modules\Activity\Services\ActivityService;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Channel\Models\Channel;
use App\Modules\Subscribe\Models\BookOrder;
use App\Modules\Subscribe\Models\YearOrder;
use App\Modules\Subscribe\Services\YearOrderService;
use App\Modules\User\Models\User;
use App\Modules\User\Services\ReadRecordService;
use App\Modules\User\Services\UserBindHkWelfareService;
use App\Modules\User\Services\UserService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Hashids;
use EasyWeChat\Foundation\Application;
use Log;
use Exception;
use Redis;
use Cookie;
use DB;

/**
 * 朋友圈链接
 * Class CoflController
 * @package App\Http\Controllers\Wap\User
 */
class CoflController extends Controller
{
    public function index(Request $request){
        $bid = $request->get('bid');
        if(empty($bid)){
            $default_ink = $this->getLink();
            return redirect()->to($default_ink);
        }
        $openid = $request->get('openid');
        //授权
        $params = $request->except('_url');
        if(empty($openid)){
            //$url = str_replace('http://', env('PROTOCOL') . '://', url()->current() . '?' . http_build_query($params));
            $url = url()->current() . '?' . http_build_query($params);
            $params['redirect_url'] = urlencode($url);
            $app = new Application($this->auth($params));
            return $app->oauth->redirect();
        }
        try{
            if(is_numeric($bid) && $bid == 6500 ){
                $params['bid'] = Hashids::encode($bid);
            }else{
                $bid = Hashids::decode($bid)[0];
            }
        }catch (Exception $e){
            return redirect()->to($this->getLink());
        }
        $crm = $request->get('crm','book_'.$bid);
        if(!$bid) return redirect()->to($this->getLink());
        //获取用户
        //$user = $this->getUsers($openid);
        $test_param = $request->input('test',0);
        //if($test_param ==1 || $test_param =='1' ) {
        $user = $this->getUsersV2($openid);
        //}

        if(!$user[0]){
            $user[1] = 123;
        }
        //有阅读纪录的跳转
        $read_record = ReadRecordService::getByField($user[0],$bid);
        if($read_record){
            $cid = explode('_',$read_record)[0];
        }else{
            //没有阅读记录的跳转
            $book_info = BookConfigService::getBookById($bid);
            $cid = $book_info->first_cid;
        }
        $params['cid'] = $cid;
        $params['crm']  ='book_'.$bid;
        if(isset($params['openid']))  unset($params['openid']);
        if(isset($params['unionid']))  unset($params['unionid']);
        $url = $this->getLink($user[1]).'reader?'.http_build_query($params);
        $this->stats('book',$crm);
        $this->statsDetail($user[0],'book',$bid);
        return redirect()->to($url);
    }

    public function freeCurrencyView(Request $request){
        $openid = $request->get('openid');
        //授权
        $params = $request->except('_url');
        if(empty($openid)){
            //$url = str_replace('http://', env('PROTOCOL') . '://', url()->current() . '?' . http_build_query($params));
            $url = url()->current() . '?' . http_build_query($params);
            $params['redirect_url'] = urlencode($url);
            $app = new Application($this->auth($params));
            return $app->oauth->redirect();
        }
        $uri = $request->path();
        $token = $request->get('token');
        $rfee = $request->get('amount');
        $crm = $request->get('crm','reward');
        $source = $request->get('wx','none');
        $type = 'CRM';
        $user = $this->getUsersV2($openid);
        if($uri == 'freethrhcurrency'){
            //$fee = 300;
            $fee = 500;
            $this->stats('reward_300',$crm);
        }elseif($uri == 'wfreecurrency'){
            $fee = 200;
            $type = 'WCRM';
            $user = $this->getUsers($openid);
        }elseif ($uri == 'frocefreethrhcurrency'){
            //$fee = 200;
            $fee = 500;
            $type = 'CRM_FORCE';
        }
        else{
            $this->stats('reward_200',$crm);
            $fee = $this->freeCurrencyFee($token,$rfee);
        }
        //$user = $this->getUsers($openid);

        if(!$user || !$user[0] || !$user[1]) return redirect()->to($this->getLink().'?'.http_build_query($params));

        if($type == 'CRM'){
            $this->statsDetail($user[0],'reward',0);
        }elseif ($type == 'CRM_FORCE'){
            $this->statsDetail($user[0],'forcereward',0);
        } else{
            $this->statsDetail($user[0],'wreward',0);
        }
        $get_free_currency = UserBindHkWelfareService::isHasGet($user[0]);
        if($get_free_currency){
            //已经领过
            if(isset($user[2]) && !empty($user[2]) && isset($user[3]) && !empty($user[3])){
                $bid = Hashids::encode($user[2]);
                $cid = $user[3];
                $params['bid'] = $bid;
                $params['cid'] = $cid;
                $link = $this->getLink($get_free_currency->distribution_channel_id).'reader?'.http_build_query($params);
            }else{
                $link = $this->getLink($get_free_currency->distribution_channel_id).'recent?'.http_build_query($params);
            }
            return view('jump.bindHkFreeCurrency',['fee'=>$fee,'url'=>$link,'is_get'=>1,'uid'=>$get_free_currency->uid,'source'=>$source]);
        }else{
            if(isset($user[2]) && !empty($user[2]) && isset($user[3]) && !empty($user[3])){
                $bid = Hashids::encode($user[2]);
                $cid = $user[3];
                $params['bid'] = $bid;
                $params['cid'] = $cid;
                $link = $this->getLink($user[1]).'reader?'.http_build_query($params);
            }else{
                $link = $this->getLink($user[1]).'recent?'.http_build_query($params);
            }
            $this->getReward($user[0],$fee,$source,$type);
            return view('jump.bindHkFreeCurrency',['fee'=>$fee,'url'=>$link,'is_get'=>0,'uid'=>$user[0],'source'=>$source]);
        }
    }


    public function freeCurrencyViewOther(Request $request){
        $openid = $request->get('openid');
        //授权
        $params = $request->except('_url');
        if(empty($openid)){
            $url = url()->current() . '?' . http_build_query($params);
            $params['redirect_url'] = urlencode($url);
            $app = new Application($this->auth($params));
            return $app->oauth->redirect();
        }
        $token = $request->get('token');
        $fee = 0;
        $type = 'NCRM_'.$fee;
        if($token){
            $info = DB::table('crm_free_currency_token')->where('token',$token)->where('is_enable',1)->first();
            if($info) {
                $fee = $info->amount;
                $type = $info->type;
            }
        }
        $user = $this->getUsersV2($openid);
        if(!$user || !$user[0] || !$user[1] || !$fee) return redirect()->to($this->getLink().'?'.http_build_query($params));
        $crm = 'new_reward';
        $source = $request->get('wx','none');

        $this->stats($crm.'_'.$fee,$crm);

        $this->statsDetail($user[0],'new_reward_'.$fee,0);

        $get_free_currency = UserBindHkWelfareService::getByOpenidToken($openid,$token);
        if($get_free_currency){
            //已经领过
            $link = $this->getLink($user[1]).'recent?'.http_build_query($params);
            return view('crm.bindHkFreeCurrencyV2',['fee'=>$fee,'url'=>$link,'is_get'=>1,'uid'=>$get_free_currency->uid,'source'=>$source]);
        }else{
            $link = $this->getLink($user[1]).'recent?'.http_build_query($params);
            //$this->getReward($user[0],$fee,$source,$type,$token);
            $this->getRewardV2($user[0],$openid,$fee,$type,$source,$token);
            return view('crm.bindHkFreeCurrencyV2',['fee'=>$fee,'url'=>$link,'is_get'=>0,'uid'=>$user[0],'source'=>$source]);
        }
    }

    private function freeCurrencyFee($token,$fee){
        if(!$token || !$fee) return 200;
        $param['fee'] = $fee;
        if( _sign($param,env('SECRET_KEY')) == $token)  return $fee;
        return 200;
    }

    public function freeCurrencyPost(Request $request){
        $uid = $request->post('uid');
        $fee = $request->post('fee',200);
        $source = $request->post('source','');
        $result = UserBindHkWelfareService::getfreeCurrency($uid,$fee,'CRM',$source);
        if($result){
            UserService::addBalance($uid,$fee,0,$fee);
        }
        return response()->success(['uid'=>$uid,'result'=>$result]);
    }
    private function getReward($uid,$fee,$source,$crm='CRM'){
        $result = UserBindHkWelfareService::getfreeCurrency($uid,$fee,$crm,$source);
        if($result){
            UserService::addBalance($uid,$fee,0,$fee);
        }
    }

    private function getRewardV2($uid,$openid,$fee,$type,$source,$token){
        $result = UserBindHkWelfareService::getfreeCurrencyV2($uid,$openid,$fee,$type,$source,$token);
        if($result){
            UserService::addBalance($uid,$fee,0,$fee);
        }
    }
    public function activity(Request $request){
        $token = $request->get('token');
        if(empty($token)){
            $default_ink = $this->getLink();
            return redirect()->to($default_ink);
        }
        $openid = $request->get('openid');
        //授权
        $params = $request->except('_url');
        if(empty($openid)){
            $url = url()->current() . '?' . http_build_query($params);
            $params['redirect_url'] = urlencode($url);
            $app = new Application($this->auth($params));
            return $app->oauth->redirect();
        }
        $crm = $request->get('crm');
        $this->stats('activity',$crm);
        $activity = ActivityService::getByToken($token);
        if($activity){
            $user = $this->getUsersV2($openid);
            $distribution_channel_id = (isset($user[1]) && !empty($user[1]))?$user[1]:123;
            $url_format = '%s://site%s.%s.com%s';
            $activity_page = $activity->activity_page ;
            if($activity->id == 6000){
                $activity_page = '/activity/common?token=LNyAqbFMgvkmvnHP8PXV3DYPIIhQm3oe';
            }
            $url = sprintf($url_format, env('PROTOCOL'), encodeDistributionChannelId($distribution_channel_id),
                env('CUSTOM_HOST'),
                $activity_page
            );
            return redirect()->to($url);
        }
        $default_ink = $this->getLink();
        return redirect()->to($default_ink);
    }

    public function indexRoot(Request $request){
        $openid = $request->get('openid');
        //授权
        $params = $request->except('_url');
        if(empty($openid)){
            $url = url()->current() . '?' . http_build_query($params);
            $params['redirect_url'] = urlencode($url);
            $app = new Application($this->auth($params));
            return $app->oauth->redirect();
        }
        list($uid,$distribution_channel_id) = $this->getUsersV2($openid);
        $link = $this->getLink($distribution_channel_id);
        $crm = $request->get('crm','index');
        $params['crm'] = $crm;
        $link  = $link.'?'.http_build_query($params);
        $this->stats('index',$crm);
        $this->statsDetail($uid,'index',0);
        return redirect()->to($link);
    }

    public function recent(Request $request){
        $openid = $request->get('openid');
        //授权
        $params = $request->except('_url');
        if(empty($openid)){
            $url = url()->current() . '?' . http_build_query($params);
            $params['redirect_url'] = urlencode($url);
            $app = new Application($this->auth($params));
            return $app->oauth->redirect();
        }
        $user = $this->getUsersV2($openid);
        if(!$user[0]){
            $distribution_channel_id = 123;
        }else{
            $distribution_channel_id = $user[1];
        }
        $crm = $request->get('crm');
        $this->stats('recent',$crm);
        $this->statsDetail($user[0],'recent',0);
        $link = $this->getLink($distribution_channel_id).'recent?'.http_build_query($params);
        return redirect()->to($link);
    }

    public function person(Request $request){
        $openid = $request->get('openid');
        //授权
        $params = $request->except('_url');
        if(empty($openid)){
            $url = url()->current() . '?' . http_build_query($params);
            $params['redirect_url'] = urlencode($url);
            $app = new Application($this->auth($params));
            return $app->oauth->redirect();
        }
        $user = $this->getUsersV2($openid);
        if(!$user[0]){
            $distribution_channel_id = 123;
        }else{
            $distribution_channel_id = $user[1];
        }
        $crm = $request->get('crm');
        $this->stats('person',$crm);
        $this->statsDetail($user[0],'person',0);
        $link = $this->getLink($distribution_channel_id).'person?'.http_build_query($params);
        return redirect()->to($link);
    }

    public function sign(Request $request){
        $openid = $request->get('openid');
        //授权
        $params = $request->except('_url');
        if(empty($openid)){
            $url = url()->current() . '?' . http_build_query($params);
            $params['redirect_url'] = urlencode($url);
            $app = new Application($this->auth($params));
            return $app->oauth->redirect();
        }
        $user = $this->getUsersV2($openid);
        if(!$user[0]){
            $distribution_channel_id = 123;
        }else{
            $distribution_channel_id = $user[1];
        }
        $crm = $request->get('crm');
        $uri = $request->path();
        if($uri == 'sign'){
            $this->stats('sign',$crm);
            $this->statsDetail($user[0],'sign',0);
        }elseif($uri == 'wsign'){
            $this->stats('wsign',$crm);
            $this->statsDetail($user[0],'wsign',0);
        }
        $link = $this->getLink($distribution_channel_id).'sign?'.http_build_query($params);
        return redirect()->to($link);
    }

    private function getUsers($openid){
        $users = User::where('openid',$openid)->select('id','distribution_channel_id')->get();
        if($users->isEmpty()) return [0,0,0,0];
        $temp = null;
        $distribution_channel_id = 0;
        $uid = 0;
        $bid = 0;
        $cid = 0;
        foreach ($users as $user){
            $last_read = ReadRecordService::getByField($user->id,'last_read');
            if(!$last_read) continue;
            if(!$temp ){
                $distribution_channel_id = $user->distribution_channel_id;
                $uid  = $user->id;
                $temp = $last_read;
            }else{
                $temp_last_read_info = explode('_',$temp);
                $last_read_info = explode('_',$last_read);
                if($last_read_info[2] > $temp_last_read_info[2]){
                    $uid = $user->id;
                    $distribution_channel_id = $user->distribution_channel_id;
                    $temp = $last_read;
                    $bid = $last_read_info[0];
                    $cid = $last_read_info[1];
                }
            }
        }
        return [$uid,$distribution_channel_id,$bid,$cid];
    }

    /**
     * @param $openid
     * @return array
     */
    private function getUsersV2($openid){
        $friend_link_uid_bind = DB::table('friend_link_uid_bind')->where('openid',$openid)->orderBy('id','desc')->first();
        if($friend_link_uid_bind) {
            $user = User::where('id',$friend_link_uid_bind->uid)->select('id','distribution_channel_id')->first();
            if($user) {
                return [$user->id,$user->distribution_channel_id];
            }
        }
        //外部渠道导粉
        if(Redis::hget('crm:out_guide_exposure_user',$openid)){
            Log::info('------------getUsersV2-outer---start--------------------------------');
            Log::info('getUsersV2 $openid is:'.$openid);
            $user = $this->createUser($openid,$openid,5204,0,'');
            Log::info('$user = $this->createUser($openid,$openid,5204,0):');
            Log::info($user);
            $uid = $user->id;
            $distribution_channel_id = 5204;
            $ouid = Redis::hget('crm:out_guide_exposure_user',$openid);
            Log::info('$ouid is :'.$ouid);
            UserService::transfer($ouid,$uid,5204);
            $insert_data = ['uid'=>$uid,'openid'=>$openid ,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
            DB::table('friend_link_uid_bind')->insert($insert_data);

            Redis::hdel('crm:out_guide_exposure_user',$openid);
            Log::info([$uid,$distribution_channel_id]);
            Log::info('------------getUsersV2-outer---end--------------------------------');
            return [$uid,$distribution_channel_id];
        }
        $inner_channels = Channel::join('channel_users','channel_users.id','=','distribution_channels.channel_user_id')
            ->select('distribution_channels.id')
            ->whereIn('channel_users.id',explode(',',redisEnv('PROMOTION_GROUP_CHANNEL_USER_ID')))
            ->get()
            ->pluck('id')
            ->toArray();

        //\Log::info($inner_channels);
        $users = User::where('openid',$openid)->select('id','distribution_channel_id')->get();
        \Log::info('users:openid:'.$openid);
        if($users->isEmpty()) return [0,0];
        $temp = null;
        $distribution_channel_id = 0;
        $uid = 0;
        $inner_channel_uid_list = [];
        //先筛网站运营部UID
        foreach ($users as $user){
            if(in_array($user->distribution_channel_id,$inner_channels)) {
                $inner_channel_uid_list[] = $user;
            }
        }
        if(count($inner_channel_uid_list) == 1) {
            $insert_data = ['uid'=>$inner_channel_uid_list[0]->id,'openid'=>$openid ,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
            \Log::info('anchor:count $inner_channel_uid_list =1');
            DB::table('friend_link_uid_bind')->insert($insert_data);
            return [$inner_channel_uid_list[0]->id,$inner_channel_uid_list[0]->distribution_channel_id];
        }
        if(count($inner_channel_uid_list)>1) {
            //有多个网站运营部UID，针对网站运营部UID进入到下一步筛选
            $users = $inner_channel_uid_list;
        }
        //筛选包年UID
        $uid_list = [];
        foreach ($users as $item) {
            $uid_list[] =$item->id;
        }
        $year_order = YearOrder::whereIn('uid',$uid_list)->orderBy('end_time','desc')->first();
        if($year_order) {
            foreach ($users as $item) {
                if($item->id == $year_order->uid) {
                    //筛选包年结束时间最后的UID
                    $insert_data = ['uid'=>$item->id,'openid'=>$openid ,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
                    \Log::info('anchor:year_order');
                    DB::table('friend_link_uid_bind')->insert($insert_data);
                    return [$item->id,$item->distribution_channel_id];
                }
            }
        }
        //按订阅章节数最多的筛选
        $users_select = ['id'=>0,'count'=>0,'user'=>null,'create_time'=>0];
        foreach ($users as $each){
            $table_prefix = ($each->id)%512;
            $chapter_count = DB::connection('chapter_order_mysql')
                ->table('chapter_orders'.$table_prefix)
                ->where('created_at','>=',date('Y-m-d H:i:s',strtotime('-3 day')))
                ->where('uid',$each->id)
                //->where('bid',$bid)
                ->count('id');
            $book_order = BookOrder::where('uid',$each->id)
                //->where('bid',$bid)
                ->where('created_at','>=',date('Y-m-d H:i:s',strtotime('-3 day')))
                ->first();
            if($book_order) {
                $chapter_count += 30;
            }
            //$each->chapter_count = $chapter_count;
            if($chapter_count>$users_select['count']) {
                $users_select['id'] = $each->id;
                $users_select['count'] = $chapter_count;
                $users_select['user'] = $each;
            }
        }
        if($users_select['id'] >0) {
            $insert_data = ['uid'=>$users_select['user']->id,'openid'=>$openid ,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
            \Log::info('anchor:subs_chapter');
            DB::table('friend_link_uid_bind')->insert($insert_data);
            return [$users_select['user']->id,$users_select['user']->distribution_channel_id];
        }
        //有订阅记录的

        foreach ($users as $value) {
            $table_prefix = ($value->id)%512;
            $chapter_order = DB::connection('chapter_order_mysql')
                ->table('chapter_orders'.$table_prefix)
                ->where('uid',$value->id)
                //->where('bid',$bid)
                ->orderBy('created_at','desc')
                ->first();
            $book_order = BookOrder::where('uid',$value->id)
                //->where('bid',$bid)
                ->first();
            if($chapter_order ){
                if(strtotime($chapter_order->created_at) > $users_select['create_time']) {
                    $users_select['id'] = $value->id;
                    $users_select['create_time'] = strtotime($chapter_order->created_at);
                    $users_select['user'] = $value;
                }
            }
            if($book_order){
                if(strtotime($book_order->created_at) > $users_select['create_time']){
                    $users_select['id']=$value->id;
                    $users_select['create_time']= strtotime($book_order->created_at);
                    $users_select['user']= $value;
                }
            }

        }
        if($users_select['id'] >0) {
            $insert_data = ['uid'=>$users_select['user']->id,'openid'=>$openid ,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
            \Log::info('anchor:subs_');
            DB::table('friend_link_uid_bind')->insert($insert_data);
            return [$users_select['user']->id,$users_select['user']->distribution_channel_id];
        }

        if(count($inner_channel_uid_list)>1) {
            //有多个网站运营部UID，针对网站运营部UID进入到下一步筛选
            $insert_data = ['uid'=>$inner_channel_uid_list[0]->id,'openid'=>$openid ,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
            \Log::info('anchor:count $inner_channel_uid_list >1');
            DB::table('friend_link_uid_bind')->insert($insert_data);
            return [$inner_channel_uid_list[0]['id'],$inner_channel_uid_list[0]['distribution_channel_id']];
        }

        \Log::info('anchor:over');
        return [0,0];
    }

    private function getUsersV3($openid){
        //5204
        //\Log::info($inner_channels);
        $users = User::where('openid',$openid)->select('id','distribution_channel_id')->get();

        if($users->isEmpty()) return [0,0];

        if(count($users) == 1){
            return [$users->first()->id,$users->first()->distribution_channel_id];
        }
        $temp = null;

        //筛选包年UID
        $uid_list = [];
        foreach ($users as $item) {
            $uid_list[] =$item->id;
        }
        $year_order = YearOrder::whereIn('uid',$uid_list)->orderBy('end_time','desc')->first();
        if($year_order) {
            foreach ($users as $item) {
                if($item->id == $year_order->uid) {
                    //筛选包年结束时间最后的UID
                    return [$item->id,$item->distribution_channel_id];
                }
            }
        }
        //按订阅章节数最多的筛选
        $users_select = ['id'=>0,'count'=>0,'user'=>null,'create_time'=>0];
        foreach ($users as $each){
            $table_prefix = ($each->id)%512;
            $chapter_count = DB::connection('chapter_order_mysql')
                ->table('chapter_orders'.$table_prefix)
                ->where('created_at','>=',date('Y-m-d H:i:s',strtotime('-3 day')))
                ->where('uid',$each->id)
                //->where('bid',$bid)
                ->count('id');
            $book_order = BookOrder::where('uid',$each->id)
                //->where('bid',$bid)
                ->where('created_at','>=',date('Y-m-d H:i:s',strtotime('-3 day')))
                ->first();
            if($book_order) {
                $chapter_count += 30;
            }
            //$each->chapter_count = $chapter_count;
            if($chapter_count>$users_select['count']) {
                $users_select['id'] = $each->id;
                $users_select['count'] = $chapter_count;
                $users_select['user'] = $each;
            }
        }
        if($users_select['id'] >0) {
            $insert_data = ['uid'=>$users_select['user']->id,'openid'=>$openid ,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
            return [$users_select['user']->id,$users_select['user']->distribution_channel_id];
        }
        //有订阅记录的
        foreach ($users as $value) {
            $table_prefix = ($value->id)%512;
            $chapter_order = DB::connection('chapter_order_mysql')
                ->table('chapter_orders'.$table_prefix)
                ->where('uid',$value->id)
                //->where('bid',$bid)
                ->orderBy('created_at','desc')
                ->first();
            $book_order = BookOrder::where('uid',$value->id)
                //->where('bid',$bid)
                ->first();
            if($chapter_order ){
                if(strtotime($chapter_order->created_at) > $users_select['create_time']) {
                    $users_select['id'] = $value->id;
                    $users_select['create_time'] = strtotime($chapter_order->created_at);
                    $users_select['user'] = $value;
                }
            }
            if($book_order){
                if(strtotime($book_order->created_at) > $users_select['create_time']){
                    $users_select['id']=$value->id;
                    $users_select['create_time']= strtotime($book_order->created_at);
                    $users_select['user']= $value;
                }
            }

        }
        if($users_select['id'] >0) {
            return [$users_select['user']->id,$users_select['user']->distribution_channel_id];
        }
        return [0,0];
    }


    private function getLink($distribution_channel_id=123){
        $url_format = '%s://site%s.%s.com/';
        return  sprintf(
            $url_format,
            env('PROTOCOL'),
            encodeDistributionChannelId($distribution_channel_id),
            env('CUSTOM_HOST')
        );
    }

    private function auth($param){
        $param['appid'] = 'wx9d389a73b88bbeae';
        $options = [
            'app_id' => 'wx9d389a73b88bbeae',
            'secret' => '2f6594bb595dfa256b5512e43a32a3d3',
            'oauth' => [
                'scopes' => ['snsapi_base'],
                'callback' => env('AUTH_CALLBACK_URL') . '?' . http_build_query($param),
            ],
        ];
        return $options;
    }

    private function stats($page,$flag){
        if(!$page || !$flag) return ;
        $flag = trim($flag);
        //pv
        $day = date('Y-m-d');
        $pv_key = sprintf('crm:pv:%s',$flag);
        Redis::hincrby($pv_key, $day, 1);
        //Redis::hincrby($pv_key, 'total', 1);
        Redis::sadd('crm_'.$day,$flag);
        //uv
        $cookie_flag = Cookie::get('crm_flag');
        if(!$cookie_flag || $cookie_flag != $flag){
            $uv_key = sprintf('crm:uv:%s',$flag);
            Redis::hincrby($uv_key, $day, 1);
            //Redis::hincrby($uv_key, 'total', 1);
        }
        Cookie::queue('crm_flag', $flag, env('U_COOKIE_EXPIRE'), null, null, false, false);
    }

    private function statsDetail($uid,$page,$bid=0)
    {
        try{
            DB::table('crm_visit_detail')->insert([
                'uid'=>$uid,'page'=>$page,
                'bid'=>$bid,'day'=>date('Y-m-d'),
                'created_at'=>date('Y-m-d H:i:s'),
                'updated_at'=>date('Y-m-d H:i:s')
            ]);
        }catch (\Exception $e){}

    }


    public function longActivity(Request $request)
    {
        $openid = $request->get('openid');
        //授权
        $params = $request->except('_url');
        if(empty($openid)){
            $url = url()->current() . '?' . http_build_query($params);
            $params['redirect_url'] = urlencode($url);
            $app = new Application($this->auth($params));
            return $app->oauth->redirect();
        }
        $user = $this->getUsersV2($openid);
        if(!$user[0]){
            $distribution_channel_id = 123;
        }else{
            $distribution_channel_id = $user[1];
        }
        $crm = $request->get('crm');
        $this->stats('activity',$crm);
        $baselink  = $this->getLink($distribution_channel_id).'activity/crm?'.http_build_query($params);
        if(isset($params['token']) && !empty($params['token'])){
            return redirect()->to($baselink.'activity/crm?'.http_build_query($params));
        }
        return redirect()->to($baselink);
    }

    public function yearActivity(Request $request)
    {
        $openid = $request->get('openid');
        //授权
        $params = $request->except('_url');
        if(empty($openid)){
            $url = url()->current() . '?' . http_build_query($params);
            $params['redirect_url'] = urlencode($url);
            $app = new Application($this->auth($params));
            return $app->oauth->redirect();
        }
        $user = $this->getUsersV2($openid);
        if(!$user[0]){
            $distribution_channel_id = 123;
        }else{
            $distribution_channel_id = $user[1];
        }
        $crm = $request->get('crm','crm_year_activity');
        $params['crm'] = $crm;
        $this->stats('activity',$crm);
        $this->statsDetail($user[0],'year_activity',0);
        $baselink  = $this->getLink($distribution_channel_id).'activity/crmy?'.http_build_query($params);
        return redirect()->to($baselink);
    }

    public function guidePersonal(Request $request){
        $openid = $request->get('openid');
        //授权
        $params = $request->except('_url');
        if(empty($openid)){
            $url = url()->current() . '?' . http_build_query($params);
            $params['redirect_url'] = urlencode($url);
            $app = new Application($this->auth($params));
            return $app->oauth->redirect();
        }
        list($uid,$distribution_channel_id) = $this->getUsersV2($openid);

        $link = $this->getLink($distribution_channel_id);
        $get_info = UserBindHkWelfareService::isHasGet($uid);
        if($get_info)   redirect()->to($link);
        $crm = $request->get('crm','guide_personal');
        $params['crm'] = $crm;
        $params['uid'] = $uid;
        $link  = $link.'guidestrem?'.http_build_query($params);
        $this->stats('index',$crm);
        $this->statsDetail($uid,'guidePersonal',0);
        return redirect()->to($link);
    }

    public function guidePersonalAccount(Request $request,$channel_id){
        $uid = $request->get('uid',0);
        $fee = $request->get('fee',200);
        $get_info = UserBindHkWelfareService::isHasGet($uid);

        if($get_info)   return back();
        $old_id = ReadRecordService::getByField($uid,'person_account_id');
        if($old_id){
            $old_personal_info = DB::table('personal_account_list')->where('id',$old_id)->first();
            if($old_personal_info && $old_personal_info->is_enable == 1){
                return view('jump.guidePersonalAccountOurs',['img'=>$old_personal_info->url,'name'=>$old_personal_info->name,'fee'=>$fee]);
            }
        }

        $distribution_channel_id = decodeDistributionChannelId($channel_id);
        //$distribution_channel_id = $channel_id;
        //if(in_array($distribution_channel_id,Redis::SISMEMBER('')));
        //$out = false;
        $group = 'ACTIVE';
        if(Redis::SISMEMBER('crm:out_channel_sites',$distribution_channel_id)){
            //$out = true;
            $group = 'OUT_ACTIVE';
            $env_config = redisEnvMulti('OUT_ACTIVE_GUIDE_PERSONAL_ACCOUNT_OURS_QRCODE',
                'OUT_ACTIVE_GUIDE_PERSONAL_ACCOUNT_MAX_UV','OUT_ACTIVE_GUIDE_PERSONAL_ACCOUNT_ID',
                'OUT_ACTIVE_GUIDE_PERSONAL_ACCOUNT_MAX_EVERY_UV');
        }else{
            $env_config = redisEnvMulti('ACTIVE_GUIDE_PERSONAL_ACCOUNT_OURS_QRCODE',
                'ACTIVE_GUIDE_PERSONAL_ACCOUNT_MAX_UV','ACTIVE_GUIDE_PERSONAL_ACCOUNT_ID',
                'ACTIVE_GUIDE_PERSONAL_ACCOUNT_MAX_EVERY_UV');
        }
        if(empty($env_config[0])){
            return back();
        }
        //$img = empty($env_config[0])?'https://cdn-novel.iycdm.com/h5/personal_account/chenchen.jpg':$env_config[0];
        $img =$env_config[0];
        $max = empty($env_config[1])?100:$env_config[1];
        $max = (int)$max;
        $one_loop_max = empty($env_config[3])?10:$env_config[3];
        $now_id = (int)$env_config[2];

        if($group == 'OUT_ACTIVE'){
            $uv_key = 'out_active_guide_personal_uv';
        }else{
            $uv_key = 'active_guide_personal_uv';
        }
        $uv = Redis::scard($uv_key);
        $personal_info = DB::table('personal_account_list')->where('id',$now_id)->select('count')->first();
        if(!$personal_info){
            return back();
        }
        $total_max = (int)($personal_info->count+$uv);
        //Log::info('$total_max is: '.);
        if($uv >= $one_loop_max || $total_max>=$max){
            if($total_max>=$max){
                DB::table('personal_account_list')->where('id',$now_id)->update([
                    'status'=>2,
                    'count'=>$total_max,
                    'updated_at'=>date('Y-m-d H:i:s')
                ]);
            }else{
                DB::table('personal_account_list')->where('id',$now_id)->increment('count',$uv,[
                    'updated_at'=>date('Y-m-d H:i:s')
                ]);
            }

            $account = DB::table('personal_account_list')
                ->where('is_enable',1)
                ->whereIn('status',[1,0])
                ->select('id','url')
                ->where('group',$group)
                ->where('count','<',$max)
                ->orderBy('count','asc')
                ->orderBy('id')
                ->first();
            Redis::del($uv_key);
            if($account){
                DB::table('personal_account_list')->where('id',$account->id)->update([
                    'status'=>1,
                    'updated_at'=>date('Y-m-d H:i:s')
                ]);
                $img = $account->url;
                $now_id = $account->id;
                Redis::Hmset('env',$group.'_GUIDE_PERSONAL_ACCOUNT_OURS_QRCODE',$account->url,$group.'_GUIDE_PERSONAL_ACCOUNT_ID',$account->id);
            }else{
                Redis::Hmset('env',$group.'_GUIDE_PERSONAL_ACCOUNT_OURS_QRCODE','',$group.'_GUIDE_PERSONAL_ACCOUNT_ID','');
                return back();
            }
        }
        Redis::sadd($uv_key,$uid);

        if($uid){
            if($group == 'OUT_ACTIVE'){
                DB::table('ad_pdd')->insert([
                    'uid'=>$uid,
                    'img'=>'OUT_GUIDE_PERSONAL_ACCOUNT_'.$now_id,
                    'date'=>date('Y-m-d'),
                    'created_at'=>date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s')
                ]);
                $user = UserService::getById($uid);
                Redis::hset('crm:out_guide_exposure_user',$user->openid,$uid);
            }else{
                DB::table('ad_pdd')->insert([
                    'uid'=>$uid,
                    'img'=>'GUIDE_PERSONAL_ACCOUNT_'.$now_id,
                    'date'=>date('Y-m-d'),
                    'created_at'=>date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s')
                ]);
            }
            ReadRecordService::setByField($uid,'person_account_id',$now_id);
        }
        $name = '';
        $name_info = DB::table('personal_account_list')->where('id',$now_id)->select('name')->first();
        if($name_info){
            $name = $name_info->name;
        }
        /*if(in_array($channel_id,explode(',',redisEnv('GUIDE_PERSONAL_ACCOUNT_WEID_SITES')))){
            $imgs = redisEnv('GUIDE_PERSONAL_ACCOUNT_WEID_QRCODE',[]);
            if($imgs) $imgs = json_decode($imgs,1);
            $page = 'jump.guidePersonalAccount';
        }else{
            $imgs = redisEnv('GUIDE_PERSONAL_ACCOUNT_OURS_QRCODE',[]);
            if($imgs) $imgs = json_decode($imgs,1);
            $page = 'jump.guidePersonalAccountOurs';
        }*/
        $page = 'jump.guidePersonalAccountOurs';
        $time = strtotime(date('Y-m-d',time()+86400))-time();
        //Cookie::queue('crm_person_img', $img,$time);
        //Cookie::queue('crm_person_name', $name,$time);
        //$page = 'jump.guidePersonalAccount';
        //$img = collect($imgs)->random();
        return view($page,['img'=>$img,'name'=>$name,'fee'=>$fee]);
    }

    public function r(Request $request,$number){
        switch ($number){
            case 1:
                //首页
                break;
            case 2:
                //阅读器
                break;
            case 3:
                //阅读器
                break;
            case 4:
                //个人中心
                break;
            case 5:
                //最近阅读
                break;
            case 6:
        }
    }

    public function freeCurrencyViewForTransfer(Request $request){
        $openid = $request->get('openid');
        //授权
        $params = $request->except('_url');
        if(empty($openid)){
            //$url = str_replace('http://', env('PROTOCOL') . '://', url()->current() . '?' . http_build_query($params));
            $url = url()->current() . '?' . http_build_query($params);
            $params['redirect_url'] = urlencode($url);
            $app = new Application($this->auth($params));
            return $app->oauth->redirect();
        }

        $crm = $request->get('crm','treward');
        $source = $request->get('wx','none');
        $fee = 500;
        $type = 'TCRM';
        $this->stats('treward_500',$crm);

        $crm_transfer_uid_bind = DB::table('crm_transfer')->where('openid',$openid)->first();
        if($crm_transfer_uid_bind) {
            $user = User::where('id',$crm_transfer_uid_bind->to_uid)->select('id','distribution_channel_id')->first();
            $uid = $crm_transfer_uid_bind->to_uid;
            $distribution_channel_id = 5204;
        }else{
            list($ouid,$distribution_channel_id) = $this->getUsersV3($openid);
            $user = $this->createUser($openid,$openid,5204,0,'');
            $uid = $user->id;
            $distribution_channel_id = 5204;
            UserService::transfer($ouid,$uid,5204);
            $insert_data = ['uid'=>$uid,'openid'=>$openid ,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
            DB::table('friend_link_uid_bind')->insert($insert_data);
        }

        if(!$uid) return redirect()->to($this->getLink($distribution_channel_id).'?'.http_build_query($params));

        $this->statsDetail($uid,'treward',0);

        $get_free_currency = UserBindHkWelfareService::isHasGet($uid);
        if($get_free_currency){
            //已经领过
            $link = $this->getLink($distribution_channel_id).'recent?'.http_build_query($params);
            return view('jump.bindHkFreeCurrency',['fee'=>$fee,'url'=>$link,'is_get'=>1,'uid'=>$uid,'source'=>$source]);
        }else{
            $link = $this->getLink($distribution_channel_id).'recent?'.http_build_query($params);
            $this->getReward($uid,$fee,$source,$type);
            return view('jump.bindHkFreeCurrency',['fee'=>$fee,'url'=>$link,'is_get'=>0,'uid'=>$uid,'source'=>$source]);
        }
    }

    private function createUser($openid,$unionid,$distribution_channel_id,$send_order_id,$ip){
        $user = UserService::getUserByOpenidAndChannelId($openid,$distribution_channel_id);
        if($user){
            return $user;
        }
        $user = null;
        try{
            $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
                ]);
        }catch (\Exception $e){
            myLog('user-error')->info($e);
        }

        // 注册动作
        $action_type = 'Register';
        $param = [
            'openid' => $openid,
            'uid' => isset($user->id)?$user->id:'0',
        ];
        UserService::PushUserActionToQueue($action_type,$distribution_channel_id,$param);
        return $user;
    }
}
