<?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');
        }
        $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;
        $desc = substr($chapter_info->content,0,20).'...';
        //$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_rec_id'=>$share_user_info->id,'timestamp'=>time(),'cid'=>$cid]
        ;
        $url_param_str = arr_to_url($params);
        $sign = md5($url_param_str);
        $link = env('PROTOCOL').'://'.env('share_domain').'/share/jump?'.$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'),'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);
        $uid = $request->input('uid','');
        $cid = $request->input('cid','');
        $bid_encode = $request->input('bid','');
        $share_user_rec_id = $request->input('share_user_rec_id','');
        $timestamp = $request->input('timestamp','');
        $sign = $request->input('sign','');
        if(empty($distribution_channel_id)||empty($uid)||empty($cid)||empty($bid_encode)||empty($share_user_rec_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_rec_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_rec_id','buid');
        ShareBringUsersService::addShareUsers($data);
        $book_configs = BookConfigService::getBookById($bid);
        $readRecord = ReadRecordService::getRecordByUidBid($buid,$bid);

        if($readRecord) {
            $cid = explode('_',$readRecord)[0];
        }else {
            $cid = $book_configs->last_cid;
        }
        header('location:/reader?bid='.$bid_encode.'&cid='.$cid);
    }
}