<?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:'.($adInfo->source_url));
    }

    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();
    }
}