<?php

namespace App\Http\Controllers\Wap\Advertises;

use App\Http\Controllers\Wap\BaseController;

use App\Modules\Book\Services\ChapterService;
use App\Modules\Cpa\Services\AdvertiseService;
use App\Modules\Cpa\Services\AdvertiseUsersService;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Cpa\Services\AdvertiseUserQueueService;
use App\Modules\ShareFree\Services\ShareBringUsersService;
use App\Modules\ShareFree\Services\ShareUsersService;
use App\Modules\User\Services\ReadRecordService;
use Illuminate\Http\Request;
use Redis;
use Hashids;
use DB;
use EasyWeChat\Foundation\Application;


class ShareController extends BaseController
{
    public function share(Request $request){
        $distribution_channel_id = $request->input('distribution_channel_id',0);
        $uid = $request->input('uid','');
        $cid = $request->input('cid','');
        $bid_encode = $request->input('bid','');
        if(empty($distribution_channel_id)||empty($uid)||empty($bid_encode)) {
            return response()->error('PARAM_EMPTY');
        }
        //$distribution_channel_id = decodeDistributionChannelId($distribution_channel_id);
        $bid =Hashids::decode($bid_encode)[0];
        $book_info = BookConfigService::getBookById($bid);
        if(!$book_info){
            return response()->error('PARAM_ERROR');
        }
        $chapter_info = ChapterService::getChapterById($book_info->first_cid);

        $book_name = $book_info->name;

        //加入用户分享记录
        $share_user_info = ShareUsersService::addShareUsers(compact('bid','uid','cid','distribution_channel_id','book_name'));
        $js_config = $this->getJSConfig();
        $bid = $bid_encode;
        $title = $book_info->book_name;
        mb_internal_encoding("UTF-8");
        $desc = mb_substr(str_replace(["\n","\r\n","\t"],'\\',trim($chapter_info->content)),0,40).'...';
        //$link = env('PROTOCOL').'://site'.Hashids::encode($distribution_channel_id)._domain().'/reader?bid='.$bid;
        $params =[
            'uid'=>$uid,'bid'=>$bid,'distribution_channel_id'=>$distribution_channel_id,
            'share_user_id'=>$share_user_info->id,'timestamp'=>time(),'cid'=>$cid]
        ;
        $url_param_str = arr_to_url($params);
        $sign = md5($url_param_str);

        $share_bring_users = ShareBringUsersService::getShareSuccessUsers($share_user_info->id);
        $share_bring_users = json_decode(json_encode($share_bring_users),true);
        $url_format = '%s://site%s.%s.com/';
        /*$link =  sprintf(
            $url_format,
            env('PROTOCOL'),
            encodeDistributionChannelId($distribution_channel_id),
            env('CUSTOM_HOST')
        );
        $link .= 'share/outjump?'.$url_param_str.'&sign='.$sign;*/
        $link = env('PROTOCOL').'://'.env('share_domain').'/share/outjump?'.$url_param_str.'&sign='.$sign;
        \Log::info('link:'.$link);
        $imgUrl=$book_info->cover;

        return view('wap.share',['params'=>compact('bid','book_name','uid','timestamp','my_sign'),'share_bring_users'=>$share_bring_users,'js_config'=>$js_config,'share_config'=>compact('title','desc','link','url','imgUrl')]);
    }

    private function getJSConfig(){
        $options = [
            'debug'  => true,
            'app_id' => env('JS_AppId'),
            'secret' => env('JS_AppSecret'),
            'token'  => 'easywechat',

            'log' => [
                'level' => 'debug',
                'file'  => storage_path('logs/easyWecaht.log'), // XXX: 绝对路径！！！！
            ],

            //...
        ];

        $app = new Application($options);
        $js = $app->js->config(array('onMenuShareQQ', 'onMenuShareWeibo','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQZone'), $debug = false, $beta = false, $json = false);

        return $js;
    }

    public function jump(Request $request){
        $distribution_channel_id = $request->input('distribution_channel_id',0);
        //$distribution_channel_id = decodeDistributionChannelId($distribution_channel_id);
        $uid = $request->input('uid','');
        $cid = $request->input('cid','');
        $bid_encode = $request->input('bid','');
        $share_user_id = $request->input('share_user_id','');
        $timestamp = $request->input('timestamp','');
        $sign = $request->input('sign','');
        if(empty($distribution_channel_id)||empty($uid)||empty($cid)||empty($bid_encode)||empty($share_user_id)||empty($sign)) {
            return response()->error('PARAM_EMPTY');
        }
        $bid=$bid_encode;
        $sign_str = arr_to_url(compact('distribution_channel_id','uid','cid','bid','share_user_id','timestamp'));
        $my_sign = md5($sign_str);
        /*if($sign != $my_sign) {
            return response()->error('WAP_SIGN_ERROR');
        }*/
        $bid = Hashids::decode($bid_encode)[0];
        $buid = $this->uid;
        $data = compact('uid','bid','cid','share_user_id','buid');
        \Log::info(json_encode($data));
        if($uid != $buid){
            ShareBringUsersService::addShareUsers($data);
        }
        $book_configs = BookConfigService::getBookById($bid);
        $readRecord = ReadRecordService::getRecordByUidBid($buid,$bid);

        if($readRecord) {
            $cid = explode('_',$readRecord)[0];
        }else {
            $cid = $book_configs->first_cid;
        }
        $url_format = '%s://site%s.%s.com/';
        $jump_link =  sprintf(
            $url_format,
            env('PROTOCOL'),
            encodeDistributionChannelId($distribution_channel_id),
            env('CUSTOM_HOST')
        );
        //\Log::info('jump_link:'.$jump_link.'reader?bid='.$bid_encode.'&cid='.$cid);
        header('location:'.$jump_link.'reader?bid='.$bid_encode.'&cid='.$cid);
    }

    public function ShareJump(Request $request) {
        $arg = $request->all();
        $distribution_channel_id = $arg['distribution_channel_id'];
        $data = array(
            'distribution_channel_id'=>$arg['distribution_channel_id'],
            'uid'=>$arg['uid'],
            'cid'=>$arg['cid'],
            'bid'=>$arg['bid'],
            'share_user_id'=>$arg['share_user_id'],
            'timestamp'=>$arg['timestamp']
        );
        $sign_str = arr_to_url($data);
        $sign = $arg['sign'];
        $my_sign = md5($sign_str);
        if($sign != $my_sign) {
            return response()->error('WAP_SIGN_ERROR');
        }
        //$link = env('PROTOCOL').'://'.env('share_domain').'/share/jump?'.$sign_str.'&sign='.$sign;
        $url_format = '%s://site%s.%s.com/';
        $link =  sprintf(
            $url_format,
            env('PROTOCOL'),
            //TODO 上线时改成加密
            encodeDistributionChannelId($distribution_channel_id),
            env('CUSTOM_HOST')
        );
        $link .= 'share/jump?'.$sign_str.'&sign='.$sign;
        header('location:'.$link);
    }
}