<?php

namespace App\Http\Controllers\Wap\Subscribe;

use App\Modules\Cpa\Services\AdvertiseUserQueueService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\Subscribe\Services\OrderService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Modules\Channel\Services\ChannelSubscribeSettingService;
use Redis;
use Cookie;
use DB;

class LinkSubscribeController extends Controller
{
    public function index(Request $request)
    {
        $uid = $request->input('uid');
        $channel_id = $request->input('distribution_channel_id');
        $send_order_id = $request->input('send_order_id', 0);
        $appid = $request->input('appid');
        $bid = $request->input('bid', 0);
        $h5_scheme = env('H5_SCHEME', 'https');
        if (empty($uid) || empty($appid)) {
            $auth_url = $h5_scheme . '://' . _domain();
        } else {
            $sub_setting = ChannelSubscribeSettingService::getSubscribeTypeByAppId($appid);
            if ($sub_setting && strpos($sub_setting->force_subscribe_type, '3') !== false && !empty($sub_setting->resource_url)) {
                $url = $h5_scheme . '://' . _domain() . '/subauthback/?uid=' . $uid . '&distribution_channel_id=' . $channel_id . '&bid=' . $bid . '&send_order_id=' . $send_order_id . '&appid=' . $appid;
                $auth_url = env('QRCODE_AUTH_URL') . '?gzh_app_id=' . $appid . '&redirect_url=' . urlencode($url);
            } else {
                $auth_url = $h5_scheme . '://' . _domain();
            }
        }
        return redirect()->to($auth_url);

    }


    public function wxAuthCallBack(Request $request)
    {
        $uid = $request->input('uid');
        $bid = $request->input('bid', 0);
        $channel_id = $request->input('distribution_channel_id', 5);
        $openid = $request->input('openid');
        $appid = $request->input('appid');
        $send_order_id = $request->input('send_order_id', 0);
        $sub_setting = ChannelSubscribeSettingService::getSubscribeTypeByAppId($appid);
        if ($sub_setting && !empty($sub_setting->resource_url)) {
            Redis::hset('book:linksubscribe:openid:' . $openid . ':channelid:' . $channel_id, 'uid', $uid);
            Redis::hset('book:linksubscribe:openid:' . $openid . ':channelid:' . $channel_id, 'bid', $bid);
            Redis::hset('book:linksubscribe:openid:' . $openid . ':channelid:' . $channel_id, 'time', time());
            Redis::hset('book:linksubscribe:openid:' . $openid . ':channelid:' . $channel_id, 'send_order_id', $send_order_id);
            Redis::EXPIRE('book:linksubscribe:openid:' . $openid . ':channelid:' . $channel_id, 300);
            Redis::hset('force_subscribe_from_bid', $appid . '_' . $uid, $bid);
            Redis::hset('force_subscribe_from_send_order_id', $appid . '_' . $uid, $send_order_id);
            return redirect()->to($sub_setting->resource_url);
        } else {
            $h5_scheme = env('H5_SCHEME', 'https');
            $auth_url = $h5_scheme . '://site' . $channel_id . '.leyuee.com/';
            return redirect()->to($auth_url);
        }
    }


    public function subscribeView(Request $request)
    {
        $title = $request->input('title', '扫一扫');
        $img = $request->input('img');
        $head_img_pool = [
            'https://cdn-novel.iycdm.com/h5/subscribe/headimg/1.png',
            'https://cdn-novel.iycdm.com/h5/subscribe/headimg/2.png',
            'https://cdn-novel.iycdm.com/h5/subscribe/headimg/3.png'
        ];
        //$head_img = $request->input('head_img','');
        $num = Cookie::get('sub_random_num');
        if (!$num) {
            $num = random_int(10, 20);
            Cookie::queue('sub_random_num', $num);
        }
        $uid = $request->get('uid');
        $head_img = array_random($head_img_pool);
        $domain = _domain();
        $distribution_channel_id = str_replace('site', '', explode('.', $domain)[0]);
        if (!is_numeric($distribution_channel_id)) {
            $distribution_channel_id = decodeDistributionChannelId($distribution_channel_id);
        }
        $new_sub_page = env('NEW_SUB_PAGE', -1);
        $template = 2;
        if (in_array($distribution_channel_id, [123, 211, 2, 14])) {
            if ($uid % 2 == 0) {
                $template = 3;
            }
            //$this->userForceSubscribeTemplate($uid, $distribution_channel_id, $template);
        }

        if($this->appad($uid,$distribution_channel_id)){
            $this->userForceSubscribeTemplate($uid,$distribution_channel_id,4);
            return view('wap.subscribeV3', compact('title', 'img', 'head_img', 'num', 'template'));
        }else{
            return view('wap.subscribeV2', compact('title', 'img', 'head_img', 'num', 'template'));
        }
    }

    private function userForceSubscribeTemplate($uid, $distribution_channel_id, $template_type)
    {
        try {
            DB::table('user_force_subscribe_template')->insert([
                'uid' => $uid,
                'distribution_channel_id' => $distribution_channel_id,
                'template_type' => $template_type,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
        } catch (\Exception $e) {

        }
    }

    private function appad($uid, $distribution_channel_id)
    {
        if (!in_array($distribution_channel_id, explode(',', env('ADS_OPEN_SITE')))) {
            return false;
        }
        $force_subscribe_info = ForceSubscribeService::forceSubscribeUsersByUid(['uid' => $uid]);

        if (!$force_subscribe_info) {
            return false;
        }

        if ($force_subscribe_info->subscribe_time &&
            (time() - strtotime($force_subscribe_info->subscribe_time) >= 3 * 86400)
            && !OrderService::isPaidUser($uid) &&
            !AdvertiseUserQueueService::getUserAdvertise($uid)
        ) {
            return true;
        }
        return false;
    }
}
