<?php

namespace App\Console\Commands\Temp;

use Log;
use Illuminate\Console\Command;
use DB;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use Hashids;
use Redis;

class PayUserAutoSub extends Command
{
    /**
     * 执行命令   php artisan temp:pay_user_auto_do
     *
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'temp:pay_user_auto_do';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动订阅';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        print_r("======自动订阅 【任务执行开始】=====".date("y-m-d H:i:s"."\n"));
        Log::info("======自动订阅 【任务执行开始】=====".date("y-m-d H:i:s"."\n"));
        $date = date('Y-m-d');
        //$total_real_fee = 0;//总消耗
        $host = DB::table('sys_configs')->where('name','brush_host')->pluck('value')->first();
        if(!$host) dd('系统参数配置有误');

        DB::table('temp_pay_users')->where('to_do_date',$date)->where('has_done',0)->orderBy('id','asc')->chunk(1000,function ($users) use($host){

            foreach ($users as $user)
            {
                $brush_read_data = [];
                $record_data = $user;
dump('user:');dump($user);
                $user_day_real_fee = 0;//用户日总消耗书币
                $brush_read_time = strtotime($user->to_do_date) + mt_rand(8*3600,9*3600);//阅读时间

                $read_record_info =  Redis::hgetall('book_read:' . $user->uid);

                dump('read_record_fee');dump($read_record_info);

                $last_record = isset($read_record_info['last_read']) ? explode('_',$read_record_info['last_read']) : null;

                $latest_read_at = $last_record ? $last_record[2] : 0;

                //判断最近一个月是否有阅读 有则continue 无阅读记录可能存储有误

                dump('$latest_read_at');dump($latest_read_at);
        //        if(!$latest_read_at || (time() - $latest_read_at < 30*86400)) continue;

                //阅读记录
                $to_do_bids = explode(',',$user->bids);//等待刷的bid

                //用户信息
                $user_info = DB::table('users')->find($user->uid);
                dump('user');dump($user_info);

                //已经订购的图书
                $ordered_books = [];

                $client = new Client();
                $cookieJar = CookieJar::fromArray([
                    'web_user_auth' => encrypt($user_info->id)
                ], $host);
dump('$to_do_bids');dump($to_do_bids);

                //阅读图书
                foreach ($to_do_bids as $_bid)
                {
                    $encode_bid = Hashids::encode($_bid);
                    $latest_chapter_id = 0;

                    //判断bid阅读按本付费或按章
                    if(isset($read_record_info[$_bid]) && $read_record_info[$_bid] && $_dt = explode('_',$read_record_info[$_bid]))
                    {
                        //上次阅读章节位置
                        $latest_chapter_id = $_dt[0];
                    }
                    $book_info = DB::table('book_configs')->where('bid',$_bid)->first();
dump('$book_info');dump($book_info);
                      //按本
                    $is_pay_by_book = $book_info->charge_type == 'BOOK' ? true : false;
                    if($is_pay_by_book)
                    {
                        $is_book_ordered = DB::table('book_orders')->where('uid',$user->uid)->where('bid',$_bid)->count();
                        if(!$is_book_ordered) {
                            if($user_day_real_fee >= $user->to_do_fee) break;//用户超过日上限则退出

                            //直接订购最后一章
                            $last_chapter = DB::table('chapters')->select('id')->where('bid', $_bid)->orderBy('sequence', 'desc')->first();
                            $_cid = $last_chapter->id;
                            $res = $client->request('GET', "http://{$host}/api/books/{$encode_bid}/balance/chapterOrders/{$_cid}",[
                                'cookies' => $cookieJar,
                                'delay'=>300,
                                'query'=>['inter_not_need_sub'=>1]
                            ]);
                            dump('http code :');dump($res->getStatusCode());

                            $res_data = json_decode($res->getBody()->getContents(), true);
                            dump('$res_data');dump($res_data);

                            $book_ordered = DB::table('book_orders')->where('uid', $user->uid)->where('bid', $_bid)->first();
                            dump('$book_ordered');dump($book_ordered);

                            if ($book_ordered)//订购成功
                            {
                                $brush_read_time += mt_rand(60,180);//增加阅读时间
                                $brush_read_data['book'][] = ['bid'=>$_bid,'read_time'=>date('Y-m-d H:i:s',$brush_read_time)];

                                $ordered_books[] = $_bid;
                                $user_day_real_fee += $book_ordered->fee;//用户单日消耗
                                $ordered_books[] = $_bid;
                            }

                        }else {
                            $ordered_books[] = $_bid;
                        }

                    }else{
                        //按章节
                        //查用户起始章节
                        $table = $user->uid%512;
                        dump('$table');dump($table);
                        $latest_sub_chapter = DB::connection('chapter_order_mysql')->table('chapter_orders'.$table)->where('uid',$user->uid)->where('bid',$_bid)->orderBy('id','desc')->first();
                        dump('$latest_sub_chapter');dump($latest_sub_chapter);
                        $start_cid = $latest_sub_chapter ? $latest_sub_chapter->cid : 0;

                        //获取章节目录 cid
                        $chapters = DB::table('chapters')->select(['id'])->where('bid',$_bid)->where('is_vip',1)->orderBy('sequence')->get();
                        $chapter_count = count($chapters);
                        $start = false;
                        //dump('$chapters');dump($chapters);
                        foreach ($chapters as $seq=>$_chapter)
                        {
                            if(!$start_cid) $start = true;
                            $_cid = $_chapter->id;

                            if($start)
                            {
                                //订阅

                                //判断是否已经订购
                                $is_ordered = DB::connection('chapter_order_mysql')->table('chapter_orders'.$table)->where('uid',$user->uid)->where('bid',$_bid)->where('cid',$_cid)->count();
                                if(!$is_ordered)
                                {
                                    if($user_day_real_fee >= $user->to_do_fee) break;//用户超过日上限则退出
dump("http://{$host}/api/books/{$encode_bid}/chapters/{$_cid}");

                                    $res = $client->request('GET', "http://{$host}/api/books/{$encode_bid}/chapters/{$_cid}",[
                                        'cookies' => $cookieJar,
                                        'delay'=>300,
                                        'query'=>['inter_not_need_sub'=>1]
                                    ]);

                                    dump('http code :');dump($res->getStatusCode());

                                    $return_info = json_decode($res->getBody()->getContents(),true);
                                    dump($return_info);
                                    if(isset($return_info['code']) && $return_info['code'] == 0)
                                    {

                                        $chapter_order = DB::connection('chapter_order_mysql')->table('chapter_orders'.$table)->where('uid',$user->uid)->where('bid',$_bid)->where('cid',$_cid)->first();
                                        if($chapter_order)//判断是否订购成功
                                        {
                                            $brush_read_time += mt_rand(60,125);//增加阅读时间
                                            $brush_read_data['chapter'][] = ['bid'=>$_bid,'cid'=>$_cid,'read_time'=>date('Y-m-d H:i:s',$brush_read_time)];
                                            $user_day_real_fee += $chapter_order->fee;//用户单日消耗
                                            if($chapter_count-1 == $seq) $ordered_books[] = $_bid;
                                        }
                                    }elseif(isset($return_info['code']) && $return_info['code'] > 0){
                                        break;
                                    }
                                }
                            }

                            if($start_cid && $_chapter->id == $start_cid)
                            {
                                $start = true;
                            }
                        }
                    }

                }

                $real_do_fee = $user_day_real_fee;
                $done_bids = implode(',',$ordered_books);
                $has_done = 1;
                $done_num = $user->done_num+1;
                $done_time = date('Y-m-d H:i:s');

                $up_data = compact('real_do_fee','done_bids','has_done','done_num','done_time');

                //更新刷数据用户
                DB::table('temp_pay_users')->where('id',$user->id)->update($up_data);

                $record_data = array_merge((array)$record_data,$up_data);
                unset($record_data['id']);
                //插入到records
                dump('record_data');dump($record_data);
                DB::table('temp_pay_users_records')->insert($record_data);

                //更新订阅时间
                foreach ($brush_read_data as $type=>$_item)
                {
                    if($type=='book')
                    {
                        foreach ($_item as $_sub)
                        {
                            DB::table('book_orders')->where('uid',$user->uid)->where('bid',$_sub['bid'])->update(['created_at'=>$_sub['read_time'],'updated_at'=>$_sub['read_time']]);
                        }
                    }
                    if($type=='chapter')
                    {
                        foreach ($_item as $_sub)
                        {
                            DB::connection('chapter_order_mysql')->table('chapter_orders'.$table)->where('uid',$user->uid)->where('bid',$_sub['bid'])->where('cid',$_sub['cid'])->update(['created_at'=>$_sub['read_time'],'updated_at'=>$_sub['read_time']]);
                        }
                    }
                }
            }
        });

        Log::info("======自动订阅 【任务执行结束】=====" . date("y-m-d H:i:s" . "\n"));
        print_r("======自动订阅 【任务执行结束】=====" . date("y-m-d H:i:s" . "\n"));
    }
}