<?php

namespace App\Http\Controllers\Wap\Web;

use App\Modules\Book\Services\BookConfigService;
use App\Modules\Book\Services\ChapterService;
use App\Modules\OfficialAccount\Models\CustomSendMsgs;
use App\Modules\OfficialAccount\Models\WechatTemplateMsgs;
use App\Modules\OfficialAccount\Models\WechatTemplates;
use App\Modules\Subscribe\Services\OrderService;
use App\Modules\User\Services\ReadRecordService;
use Illuminate\Routing\Controller;
use App\Http\Controllers\Wap\BaseController;
use Illuminate\Http\Request;
use Cookie;
use DB;
use Redis;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\Statistic\Services\WapVisitStatService;
use Hashids;
use Log;

class RedirectController extends BaseController
{
    private $alluv;
    /**
     * 推广链接跳转
     * @param Request $request
     * @param $param
     * @return \Illuminate\Http\RedirectResponse
     */
    public function index(Request $request, $t, $domain, $param)
    {
        $this->send_order_id = $param;
        $h5_scheme = 'https';
        //判断派单链接有没有进黑名单
        $black_send_order_ids = explode(',', env('BLACK_SEND_ORDER_IDS'));
        if(in_array($param,$black_send_order_ids))
        {
            abort(404);
        }

        if(is_numeric($t)){
            //不是加密site 重定向到加密site
            $domain_distribution_channel_id = $t;
            //$domain_distribution_channel_id = encodeDistributionChannelId($t);
            //$en_domain = str_replace('site'.$t,'site'.$domain_distribution_channel_id,_domain());
            //\Log::info('yun redirect is :'.env('H5_SCHEME','https').'://' . $en_domain. '/yun/' . $param);
            //return redirect()->to( $h5_scheme.'://' . $en_domain. '/yun/' . $param);
        }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($this->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;
        //判断是否强制到服务号阅读
        if($link && $link->force_show_qrcode)
        {
            //Cookie::queue('force_show_qrcode', 1, 1);
        }else{
            $query_param['source'] = 'wechatmsg';
        }
        $query_param['stats'] = 3;
        $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());
            }
            //211渠道特殊统计
            if($param && $link->distribution_channel_id && $uid && $link->book_id){
                $this->specialChannelIdStats($param,$link->distribution_channel_id,$uid,$link->book_id);
            }
            $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 (!Cookie::get('send_order_flag_' . $param) && !in_array($param, $send_orders)) {
                Redis::hincrby('send_order_uv_' . $param, $key, 1);
                Redis::hincrby('send_order_uv_' . $param, 'total', 1);
                //Cookie::queue('send_order_flag_'.$param,$param, env('U_COOKIE_EXPIRE'), null, null, false, false);
                array_push($send_orders, $param);
                $str = implode(',', $send_orders);
                Cookie::queue('send_order_flag', $str, env('U_COOKIE_EXPIRE'), null, null, false, false);
            }

            if (Cookie::get('send_order_flag_' . $param)) {
                array_push($send_orders, $param);
                $str = implode(',', $send_orders);
                Cookie::queue('send_order_flag', $str, env('U_COOKIE_EXPIRE'), null, null, false, false);
                Cookie::queue('send_order_flag_' . $param, null, -1);
            }
            //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 (isset($link->send_time) && $link->send_time) {
                //$uv = WapVisitStatService::getSendOrderTotalUv($param);
                /*if($link->send_time && $param){
                    try{
                        $this->insertOrder($param, $link->send_time, $link->distribution_channel_id,$link->name);
                    }catch (\Exception $e){
                        \Log::info($e);
                    }
                }*/

            } else {
                $uv = Redis::hget('send_order_uv_' . $param, $key);
                $this->updateSendOrderTime($param, $uv);
            }
            //统计
            $this->InnerOuterWeixinStats($link->promotion_type,$param);
            //
            $redirect_path = $request->get('redirect_path');
           if($redirect_path){
               $redirect_path = urldecode($redirect_path);
               $url = secure_url('/') .$redirect_path;
               return redirect()->to($url);
           }else{
               if (($recent_url = $this->JumpTorecentRead($link->redirect_url, $this->uid, $param))) {
                   return redirect()->to($recent_url);
               } else {
                   return redirect()->to($url);
               }
               //return redirect()->to($url);
           }
        }
        return redirect()->to(parse_url(url()->current())['scheme'] . '://' . _domain() . '/?' . $query);
    }


    private function JumpTorecentRead($url, $uid, $send_order_id)
    {
        //Log::info('JumpTorecentRead($url, $uid, $send_order_id)'.$url.'--'.$uid.'----'.$send_order_id);
        if (!$uid) return '';
        $url_info = parse_url($url);
        //Log::info($url_info);
        if (!isset($url_info['path']) || !isset($url_info['query']) || $url_info['path'] != '/reader') return '';

        parse_str($url_info['query'], $query_param);
        //Log::info('$query_param');
        //Log::info($query_param);
        if (!$query_param || !isset($query_param['bid']) || !isset($query_param['cid'])) return '';
        $bid = 0;
        $bid_str = $query_param['bid'];
        $cid = $query_param['cid'];
        try {
            $bid_arr = Hashids::decode($bid_str);
            if (isset($bid_arr[0])) $bid = $bid_arr[0];
        } catch (\Exception $e) {
        }
        //Log::info('$bid is: .'.$bid);
        if (!$bid) return '';
        $record_info = '';
        try {
            $record_info = ReadRecordService::getRecordByUidBid($uid, $bid);
        } catch (\Exception $e) {
            \Log::info($e);
        }

        if (!$record_info) return '';
        $record_info_arr = explode('_', $record_info);
        if (!isset($record_info_arr[0])) return '';

        $param['cid'] = $record_info_arr[0];
        $param['bid'] = $bid_str;
        $param['soid'] = $send_order_id;
        $param['jump_from'] = 'yun';
        if ($cid && $cid != $record_info_arr[0]) {
            $url = env('H5_SCHEME', 'https') . '://' . _domain() . '/reader?' . http_build_query($param);
            return $url;
        }
        return '';
    }


    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);
            Cookie::queue('cpc_ad_status', 'show', 3600,null, null, false, false);
        }
    }

    public function testauth(Request $request){
        $channel_id = $request->get('id');
        if(!$channel_id){
            return 'not channel id';
        }
        $h5_scheme = env('PROTOCOL','https');
        $domain = _domain();
        $params['redirect_url'] = urlencode($h5_scheme . '://' . $domain . '/oauthCallBacktest');

        $params['timestamp'] = time();

        //$params['gzh_app_id'] = 'wx939e8ff1b572aa49';
        $info = specialChannelAuthInfo();
        if(!isset($info[$channel_id]) ){
            return 'channel has no appid';
        }
        $params['gzh_app_id'] = $info[$channel_id];

        $params['sign'] = 'hgygusdxfhr5ea14576klncsw';

        $redirect = env('AUTH_URL') . '?' . http_build_query($params);

        return redirect()->to($redirect);
    }

    public function clearCookie(){
        setcookie(env('COOKIE_AUTH_WEB_WECHAT'), "", time()-3600);
    }

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


    /**
     * 用户从A连接推送的书，进入后，被标记bookid+派单id，之后所有的统计计算到该派单下
     * @param int $send_order_id
     * @param int $distribution_channel_id
     * @param int $uid
     * @param int $bid
     */
    private function specialChannelIdStats(
        int $send_order_id,
        int $distribution_channel_id,
        int $uid,
        int $bid
    ):void{

        if(!$bid || !$distribution_channel_id || !$uid || !$send_order_id)
            return ;
        $specialChannelIdStats = env('SPECIAL_CHANNEL_STATS',211);
        if(!in_array($distribution_channel_id,explode(',',$specialChannelIdStats)) ){
            return ;
        }
        WapVisitStatService::specialChannelIdStatsMarkUser($uid,$bid,$send_order_id);
        return ;
    }

    //内外部模板客服统计埋点
    private function InnerOuterWeixinStats($promotion_type,$send_order_id){
        if(!$promotion_type || !$send_order_id) return ;
        $openChannel = redisEnv('OPEN_INNER_OUTER_WEIXIN_STATS');
        if(!$openChannel || !in_array($this->distribution_channel_id,explode(',',$openChannel))) return ;
        if($promotion_type == 'EXTERNAL'){
            ReadRecordService::setByMultiField($this->uid,['new_outer'=>$send_order_id,'new_total'=>$send_order_id]);
        }

        if($promotion_type == 'INTERNAL'){
            ReadRecordService::setByMultiField($this->uid,['new_inner'=>$send_order_id,'new_total'=>$send_order_id]);
        }
        $day = date('Y-m-d');
        $pv_key = sprintf('InnerOuterWeixinStats:pv:%s:%s',$send_order_id,$this->distribution_channel_id);
        $uv_key = sprintf('InnerOuterWeixinStats:uv:%s:%s:%s',$send_order_id,$this->distribution_channel_id,$day);
        Redis::hincrby($pv_key,$day,1);
        Redis::sadd($uv_key,$this->uid);
        Redis::sadd('InnerOuterWeixinStats:'.$day,$send_order_id.':'.$this->distribution_channel_id);
    }

    public function customPushtransferPage(Request $request,$channel_id, $domain){
        $data = [];
        $url = $request->get('origin_url');
        $from_type = $request->get('fromtype');
        if(!$url) return redirect()->to('/');
        $url = urldecode($url);
        $info = parse_url($url);
        if(!isset($info['path']) || $info['path'] != '/reader'){
            if(strpos($url,'?') === false){
                return redirect()->to($url.'?fromtype='.$from_type);
            }else{
                return redirect()->to($url.'&fromtype='.$from_type);
            }
        }
        parse_str($info['query'],$output);
        if(!isset($output['bid']) || !isset($output['cid'])) return redirect()->to('/');
        $distribution_channel_id = decodeDistributionChannelId($channel_id);
        if($from_type){
            //['custom','template']
            $push_info = explode('_',$from_type);
            $push_id = 0;
            if($push_info && !empty($push_info[1]) && is_numeric($push_info[1])){
                $push_id = $push_info[1];
            }
            if(str_contains($from_type,['custom']) && $push_id){
                $info = CustomSendMsgs::customSendMsgsById($push_id);
                if(!$info || $info->distribution_channel_id != $distribution_channel_id){
                    return redirect()->to('/');
                }
                $push_transfer_custom_flag = Cookie::get('push_transfer_custom_flag');
                if(!$push_transfer_custom_flag || !in_array($push_id,explode(',',$push_transfer_custom_flag))){
                    Redis::hincrby('push_transfer_page_custom_uv' , $push_id,  1);
                    if($push_transfer_custom_flag) {$push_transfer_custom_flag = $push_transfer_custom_flag.','.$push_id;}
                    else {$push_transfer_custom_flag = $push_id;}
                    Cookie::queue('push_transfer_custom_flag',$push_transfer_custom_flag, env('U_COOKIE_EXPIRE'), null, null, false, false);
                }
                Redis::hincrby('push_transfer_page_custom_pv' , $push_id,  1);
            }
            if(str_contains($from_type,['template']) && $push_id){
                $info = WechatTemplateMsgs::wechatTemplateMsgsById($push_id);
                if(!$info || $info->distribution_channel_id != $distribution_channel_id){
                    return redirect()->to('/');
                }
                $push_transfer_template_flag = Cookie::get('push_transfer_template_flag');
                if(!$push_transfer_template_flag || !in_array($push_id,explode(',',$push_transfer_template_flag))){
                    Redis::hincrby('push_transfer_page_template_uv' , $push_id,  1);
                    if($push_transfer_template_flag) {$push_transfer_template_flag = $push_transfer_template_flag.','.$push_id;}
                    else {$push_transfer_template_flag = $push_id;}
                    Cookie::queue('push_transfer_template_flag',$push_transfer_template_flag, env('U_COOKIE_EXPIRE'), null, null, false, false);
                }
                Redis::hincrby('push_transfer_page_template' , $push_id, 1);
            }
        }
        $bid = Hashids::decode($output['bid'])[0];
        $book_info = BookConfigService::getBookById($bid);
        $chapter_content = ChapterService::getChapter($bid, $output['cid']);

        $data['chapter_list'] = explode("\r\n",$chapter_content->content);
        $data['name'] = $book_info->book_name;
        $data['next_url'] = '/reader?bid='.$output['bid'].'&cid='.$chapter_content->next_cid.'&fromtype='.$from_type;
        return view('wap.customPushtransfer',$data);
    }
}
