<?php

namespace App\Http\Controllers\WapAlipay\Web;

use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Cookie;
use DB;
use Redis;
use App\Modules\SendOrder\Services\SendOrderService;

class RedirectController extends Controller
{
    /**
     * 推广链接跳转
     * @param Request $request
     * @param $param
     * @return \Illuminate\Http\RedirectResponse
     */
    public function index(Request $request, $t, $domain, $param)
    {
        $h5_scheme = 'https';
        if(is_numeric($t)){
            //不是加密site 重定向到加密site
            $domain_distribution_channel_id = $t;
        }else{
            $domain_distribution_channel_id = decodeDistributionChannelId($t);
        }

        if(empty($domain_distribution_channel_id)){
            return response()->error('UNKNOWN_ERROR');
        }
        $uid = Cookie::get(env('COOKIE_AUTH_WEB_WECHAT'));
        if($uid){
            try{
                Redis::hset('book_read:' . $uid, 'send_order_id', $param);
            }catch (\Exception $e){}
        }
        $link = SendOrderService::getRedirectUrlById($param);
        $query_param = $request->except('_url');
        $query_param['soid'] = $param;
        $query_param['source'] = 'wechatmsg';
        $query = '';
        if ($query_param) {
            $query = http_build_query($query_param);
        }
        if ($link) {
            //访问时的site id与派单的site id 不一致 直接返回首页
            if($link->distribution_channel_id != $domain_distribution_channel_id){
                return redirect()->to($h5_scheme.'://' . _domain());
            }
            $key = date('Y-m-d');
            Cookie::queue('send_order_id', $param, env('U_COOKIE_EXPIRE'), null, null, false, false);
            $url = secure_url('/') . $link->redirect_url;
            if ($query) {
                if (strpos($link->redirect_url, '?')) {
                    $url = secure_url('/') . $link->redirect_url . '&' . $query;
                } else {
                    $url = secure_url('/') . $link->redirect_url . '?&' . $query;
                }
            }
            $send_order_flag = Cookie::get('send_order_flag');
            $send_orders = explode(',', $send_order_flag);
            //uv
            if (!in_array($param, $send_orders)) {
                Redis::hincrby('send_order_uv_' . $param, $key, 1);
                Redis::hincrby('send_order_uv_' . $param, 'total', 1);
                array_push($send_orders, $param);
                $str = implode(',', $send_orders);
                Cookie::queue('send_order_flag', $str, env('U_COOKIE_EXPIRE'), null, null, false, false);
            }
            //pv
            Redis::hincrby('send_order_pv_' . $param, $key, 1);//每天
            Redis::hincrby('send_order_pv_' . $param, 'total', 1);//汇总
            Redis::sadd('send_order' . $key, $param);
            //$key = date('Y-m-d');
            if (!$link->send_time) {
                $uv = Redis::hget('send_order_uv_' . $param, $key);
                $this->updateSendOrderTime($param, $uv);
            }
            //
            $redirect_path = $request->get('redirect_path');
           if($redirect_path){
               $redirect_path = urldecode($redirect_path);
               $url = secure_url('/') .$redirect_path;
               return redirect()->to($url);
           }else{
               return redirect()->to($url);
           }
        }
        return redirect()->to(parse_url(url()->current())['scheme'] . '://' . _domain() . '/?' . $query);
    }


    public function testLogin(Request $request)
    {

        $siteid = $request->input('siteid');
        if (env('APP_ENV', '') == 'local') {
            echo encodeDistributionChannelId($siteid);
            Cookie::queue(env('COOKIE_AUTH_WEB_WECHAT'), 1, env('U_COOKIE_EXPIRE'), null, null, false, false);
        }
    }

    public function help()
    {
        $title = '帮助';
        return view('wap.help', compact('title'));
    }

    protected function updateSendOrderTime($send_order_id, $uv)
    {
        if ($uv && $uv >= 20) {
            try {
                SendOrderService::updateSendOrderTime($send_order_id);
                return true;
            } catch (\Exception $e) {

            }
        }
        return false;
    }
}
