<?php

namespace App\Http\Controllers\Wap\Advertises;

use App\Http\Controllers\Wap\BaseController;

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\User\Services\ReadRecordService;
use Illuminate\Http\Request;
use Redis;
use Hashids;
use DB;

class AdvertiseController extends BaseController
{
    public function jump(Request $request){
        //$bid=$request->input('bid','');
        $uid_pre=$request->input('uid','');
        if(empty($uid_pre)){
            return response()->error('PARAM_ERROR');
        }
        $uid = Hashids::decode($uid_pre)[0];
        \Log::info('---uid:'.$uid);
        $bid= ReadRecordService::getSimpleFirstReadRecord($uid);   //TODO 获取最近阅读
        $books_info = BookConfigService::getBookById($bid);
        $book_name=$books_info->book_name;
        //$bid=$books_info[''];
        Redis::incr("advertise_jump_h5_pv:");

        $uid=$uid_pre;
        $ads = $this->getOneAd(1);
        $timestamp = time();
        $private_key = '^^zhuishuyun';
        $bid=Hashids::encode($bid);
        $pre_str = arr_to_url(compact('bid','uid','timestamp'));
        \Log::info('pre_str:'.$pre_str);
        $my_sign = md5($pre_str.$private_key);
        $ua = $_SERVER['HTTP_USER_AGENT'];
        $my_bid = $bid;
        if($my_bid && preg_match('/Android/',$ua)) {
            try{
                AdvertiseUsersService::addAdAccessRec(['uid'=>Hashids::decode($uid)[0],
                    'bid'=>Hashids::decode($my_bid)[0],
                    'position'=>'JUMP',
                    'created_at'=>date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s'),
                    'remark'=>$ua
                ]);
            }catch(\Exception $e){
                \Log::error('insert into advertise_access_rec failded:'.$e->getMessage());
            }
        }
        return view('wap.advertise',['params'=>compact('bid','book_name','uid','timestamp','my_sign'),'ads'=>$ads]);
    }

    public function jumpToSource(Request $request){
        $bid=$request->input('bid','');
        $uid=$request->input('uid','');
        $ad =$request->input('ad','');
        $timestamp = $request->input('timestamp','');
        $sign = $request->input('sign','');
        if(empty($bid)||empty($uid)||empty($ad)){
            return response()->error('PARAM_EMPTY');
        }
        //签名
        $pre_str = arr_to_url(compact('bid','uid','timestamp'));
        \Log::info('my_pre_str:'.$pre_str);
        $private_key = '^^zhuishuyun';
        $my_sign = md5($pre_str.$private_key);
        //签名时间超过两小时过期
        $now = time();
        if(($now-$timestamp) > 60*60*2){
            return response()->error('PARAM_ERROR');
        }
        if($my_sign != $sign){
            return response()->error('PARAM_ERROR');
        }
        \Log::info('ad:'.$ad);
        $bid=Hashids::decode($bid)[0];
        $uid = Hashids::decode($uid)[0];
        \Log::info('bid:'.$bid.':uid:'.$uid);
        $AdUers = AdvertiseUsersService::addOrUpdateAdUsers(['bid'=>$bid,'uid'=>$uid,'advertise_id'=>$ad]);
        \Log::info('ad_users:'.$AdUers);
        \Log::info('ad_users:----');
        $toQueue = array(
            'uid'=>$uid,
            'bid'=>$bid,
            'ad_user_id'=>$AdUers->id,
            'advertise_id'=>$ad,
            //'add_time'=>time(),
            'status'=>0
        );
        AdvertiseUserQueueService::addToQueue($toQueue);
        $adInfo = AdvertiseService::getOneById($ad);
        \Log::info($adInfo);
        header('Location:'.'https://url.cn/5T6fJWf');
    }

    public function getAds(Request $request){
        $uid=$request->input('uid','');
        if(empty($uid)) {
            return response()->error('PARAM_EMPTY');
        }
        $ads = AdvertiseService::getAds();
        foreach ($ads as &$ad){
            $adv = AdvertiseUsersService::getOne(['uid'=>$uid,'advertise_id'=>$ad->advertise_id]);
            if($adv){
                $ad->is_download=1;
            }else{
                $ad->is_download =0;
            }
        }
        return response()->success($ads);
    }

    private static function getAdvs($uid) {
        $ads = AdvertiseService::getAds();
        foreach ($ads as &$ad){
            $adv = AdvertiseUsersService::getOne(['uid'=>$uid,'advertise_id'=>$ad->advertise_id]);
            if($adv){
                $ad->is_download=1;
            }else{
                $ad->is_download =0;
            }
        }
        return $ads;
    }
    private function getOneAd($id) {
        $ads = AdvertiseService::getOneById($id);
        return $ads;
    }

    /**
     * 点击下载按钮上报
     * @param Request $request
     * @return mixed
     */
    public function recieveUserBehavior(Request $request){
        $uid = $request->input('uid','');
        $bid = $request->input('bid','');
        $uid=Hashids::decode($uid)[0];
        $bid=Hashids::decode($bid)[0];
        $position = $request->input('position','');
        $params = compact('uid','bid','position');
        $params['created_at'] = $params['updated_at'] = date('Y-m-d H:i:s');
        $ua = $_SERVER['HTTP_USER_AGENT'];
        $params['remark'] = $ua;
        DB::table('advertise_access_rec')->insert($params);
        return response()->success();
    }

    
    public function pddAd(Request $request){
        $links = [
            '2019041501'=>'https://mobile.yangkeduo.com/duo_brand_sales.html?pid=8571127_60403841&cpsSign=CM8571127_60403841_29e8aa97a487aa94a63fd31f45da38cf&duoduo_type=2',
            '2019041502'=>'https://mobile.yangkeduo.com/duo_nine_nine.html?pid=8571127_60403841&cpsSign=CM8571127_60403841_d766485b4f32d85c227b4cefd604a02d&duoduo_type=2',
            '2019041601'=>'https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id=7539798822&pid=8585481_60984090&cpsSign=190416_CC8585481_60984090_03b2f7fa0ef1e609c2249cc365b42f3e&duoduo_type=2',
            '2019041602'=>'https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id=190857743&pid=8585481_60984090&cpsSign=190416_CC8585481_60984090_f1ef254d6b95420817e9d398b9b0ab63&duoduo_type=2',
            '2019041603'=>'https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id=6748389609&pid=8585481_60984090&cpsSign=190416_CC8585481_60984090_3dfafd4426b6ac11cff1bb7e7f274871&duoduo_type=2',
            '2019041604'=>'https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id=2200177&pid=8585481_60984090&cpsSign=190416_CC8585481_60984090_bb29ca22aaa8ed3d9927f312ff9f4eb0&duoduo_type=2',
            '2019041605'=>'https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id=6878198875&pid=8585481_60984090&cpsSign=190416_CC8585481_60984090_8e4542ff01347e7d0b4e63e5d0cada0d&duoduo_type=2',
            '2019041606'=>'https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id=25858329&pid=8585481_60984090&cpsSign=190416_CC8585481_60984090_430a54cf797bfd73fa5baf31a240d600&duoduo_type=2',
            '2019041607'=>'https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id=3785330482&pid=8585481_60984090&cpsSign=190416_CC8585481_60984090_904632cdd98a39a26f618dfbe0c4e482&duoduo_type=2',
            '2019041608'=>'https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id=4220538441&pid=8585481_60984090&cpsSign=190416_CC8585481_60984090_9ff313f511eaa7df46b9358524421825&duoduo_type=2',
            '2019041609'=>'https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id=4330142633&pid=8585481_60984090&cpsSign=190416_CC8585481_60984090_3cd524bbc1d78b76e56c5c0e13020ee9&duoduo_type=2',
            '2019041610'=>'https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id=5826309739&pid=8585481_60984090&cpsSign=190416_CC8585481_60984090_cd18616d2a6b5ae15d5cd24b24717785&duoduo_type=2',
            '2019041611'=>'https://mobile.yangkeduo.com/duo_theme_activity.html?themeId=5595&pid=8585481_60984090&cpsSign=190416_CT8585481_60984090_c5aef71fd6a8b510ccd8a400dc6500a1&duoduo_type=2',
            '2019041612'=>'https://mobile.yangkeduo.com/duo_theme_activity.html?themeId=5328&pid=8585481_60984090&cpsSign=190416_CT8585481_60984090_7bb6baecf55ccece8887e36499400351&duoduo_type=2',
            '2019041613'=>'https://mobile.yangkeduo.com/duo_theme_activity.html?themeId=5198&pid=8585481_60984090&cpsSign=190416_CT8585481_60984090_d26f463995bf7df3d5db6d71be5e5924&duoduo_type=2',
            '2019041614'=>'https://mobile.yangkeduo.com/duo_theme_activity.html?themeId=4274&pid=8585481_60984090&cpsSign=190416_CT8585481_60984090_cd454f3cc9f5eb6e9a26e00bf01a8d03&duoduo_type=2',
            '2019041615'=>'https://mobile.yangkeduo.com/duo_theme_activity.html?themeId=5505&pid=8585481_60984090&cpsSign=190416_CT8585481_60984090_9cc457adb40cf436e8477f06535bb706&duoduo_type=2'
        ];
        $links  = Redis::get('advertise:pdd');
        if($links){
            $links = json_decode($links,1);
        }
        $link_key = $request->get('link','2019041501');
        if($this->uid){
            try{
                //$key = sprintf('pddad:uv:%s:%s',$link_key,date('Y-m-d'));
                //Redis::sadd($key,$this->uid);
                DB::table('ad_pdd')->insert([
                    'uid'=>$this->uid,
                    'img'=>sprintf('https://cdn-novel.iycdm.com/h5/ad/pdd/%s.jpg',$link_key),
                    'date'=>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){}
        }

        $link_key = $request->get('link','2019041501');
        return redirect()->to($links[$link_key]);
    }
}