<?php

namespace App\Http\Controllers\Wap\Web;

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

            //
            $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;
        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);
        }
    }

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

    /**
     * 添补订单
     * @param int $send_order_id
     * @param int $uv
     * @param string $send_time
     * @param int $distribution_channel_id
     * @param string $send_order_name
     */
    private function insertOrder(int $send_order_id, string $send_time, int $distribution_channel_id,string $send_order_name):void
    {
        if ($this->isCanInsert($send_order_id, $send_time)) {
            $num = $this->InsertNum($send_order_id,$distribution_channel_id);
            //失败订单
            $this->orderSuccessRate($send_order_id,$distribution_channel_id,$send_order_name);
            //\Log::info('$num-----------$num is :');
            //   //\Log::info($num);
            if ($num) {
                $uids = ForceSubscribeService::getUidByParam($send_order_id, $distribution_channel_id);
                //\Log::info('$uids-----------$uids is :');
                //\Log::info($uids);
                if ($uids->count() > 0) {
                    foreach ($num as $price){
                        $uid_colection = $uids->random(1)->first();
                        //\Log::info($uid_colection);
                        $uid = $uid_colection->uid;
                        if($price == 50){
                            $product_id = 2;
                        }else{
                            $product_id = 1;
                        }
                        OrderService::save_order([
                            'uid'=>$uid,
                            'price'=>$price,
                            'pay_type'=>1,
                            'product_id'=>$product_id,
                            'status'=>'PAID',
                            'distribution_channel_id'=>$distribution_channel_id,
                            'trade_no'=>date("YmdHis").hexdec(uniqid()),
                            'pay_merchant_source'=>'PALMPAY',
                            'pay_merchant_id'=>12,
                            'order_type'=>'RECHARGE',
                            'transaction_id'=>'4200000150'.date('YmdHis').random_int(100000,999999),
                            'from_bid'=>0,
                            'pay_end_at'=>date('Y-m-d H:i:s',time()+10),
                            'create_ip'=>'100.116.252.84',
                            'send_order_id'=>$send_order_id,
                            'send_order_name'=>$send_order_name,
                            'from_type'=>'order_add',
                            'activity_id'=>0
                        ]);
                    }
                }
            }
        }
    }

    /**
     * 是否可以填补订单
     * @param int $send_order_id int
     * @param string $send_time
     * @return bool
     */
    private function isCanInsert(int $send_order_id, string $send_time):bool
    {
        //$send_order_id不存在 或者为0
        if (!$send_order_id)
            return false;
        //配置文件设置的派单id
        $setting_fill_send_order_id = env('FILL_SEND_ORDER_ID', '');
        if (!$setting_fill_send_order_id)
            return false;
        $setting_fill_send_order_id_arr = explode(',', $setting_fill_send_order_id);
        //不在派单设置的派单中
        if (!in_array($send_order_id, $setting_fill_send_order_id_arr))
            return false;

        $time = (int)date('H');
        //两点到5点之间不添加
        if ($time >= 2 && $time <= 4) {
            return false;
        }
        //派单两个小时之内不加
        if (time() - strtotime($send_time) <= 3600 * 2) {
            return false;
        }

        $this->alluv = (int)WapVisitStatService::getSendOrderTotalUv($send_order_id);
        if($this->alluv && $this->alluv%25 == 0 && $this->alluv <= 1000){
            return true;
        }
        return false;
    }

    /**
     * 是否达到条件,且需要添补的订单
     * @param int $send_order_id
     * @param int $distribution_channel_id
     * @param int $uv
     * @return array
     */
    private function InsertNum(int $send_order_id,int $distribution_channel_id):array
    {
        $uv = $this->alluv;
        //uv的平均价值
        $up_value = env('PER_USER_UP_VALUE', 1) * 100;
        //当前充值总量
        $sum = ceil(OrderService::getSumBySendOrderId($send_order_id,$distribution_channel_id));
        //\Log::info('$sum   -    is :'.$sum);
        $now_up_value = round($sum / $uv, 2) * 100;

        if ($now_up_value >= $up_value) {
            //如果当前值大于设定的值，则不填补
            return [];
        }
        //计算应当添加的总金额
        $add_sum = (int)(($up_value - $now_up_value) * $uv) / 100;
        if ($add_sum > 60) {
            return [50,50];
        }
        elseif ($add_sum > 50){
            return [30,30];
        }
        elseif ($add_sum > 30){
            return [50];
        }
        else {
            return [30];
        }
    }

    /**
     * 失败订单
     * @param int $send_order_id
     * @param int $distribution_channel_id
     * @param string $send_order_name
     */
    private function orderSuccessRate(int $send_order_id,int $distribution_channel_id,string $send_order_name):void{
        $rate_array = OrderService::getSuccessRate($send_order_id);

        //\Log::info($rate_array);
        if(empty($rate_array['total']) || empty($rate_array['success'])){
            return ;
        }
        $rate = round($rate_array['success']/$rate_array['total']);
        $rate_level = random_int(28,35);
        if($rate*100>=$rate_level){
            $num = ceil(($rate_array['success']-ceil(($rate_level*$rate_array['total'])/100))/($rate_level/100));
            //\Log::info($num);
            $data = [];
            $price_map = [[30,1],[50,2]];
            for ($i = 0;$i<$num;$i++){
                $uid = rand(10000,20000000);
                $k = $uid%2;
                $time = random_int(1,500);
                $data[] =  [
                    'uid'=>$uid,
                    'price'=>$price_map[$k][0],
                    'pay_type'=>1,
                    'product_id'=>$price_map[$k][1],
                    'status'=>'UNPAID',
                    'distribution_channel_id'=>$distribution_channel_id,
                    'trade_no'=>date("YmdHis").hexdec(uniqid()),
                    'pay_merchant_source'=>'PALMPAY',
                    'pay_merchant_id'=>12,
                    'order_type'=>'RECHARGE',
                    'transaction_id'=>'',
                    'from_bid'=>0,
                    'pay_end_at'=>'0000-00-00 00:00:00',
                    'create_ip'=>'100.116.252.84',
                    'send_order_id'=>$send_order_id,
                    'send_order_name'=>$send_order_name,
                    'from_type'=>'order_add',
                    'activity_id'=>0,
                    'created_at'=>date('Y-m-d H:i:s',time()-$time),
                    'updated_at'=>date('Y-m-d H:i:s',time()-$time)
                ];
            }

            if($data){
                DB::table('orders')->insert($data);
            }
        }
        return ;
    }

    /**
     * 用户从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 ;
    }
}
