<?php

namespace App\Console\Commands\Book;
use Illuminate\Console\Command;
use DB;
use Redis;

class NewBookTestUserDetail extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'new_book_test_user_detail';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '新书测试用户数据';
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

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

        $new_book_test_ids = DB::table('new_book_tests')
            ->leftjoin('new_book_test_users','new_book_test_users.test_id','new_book_tests.id')
            ->whereNotNull('new_book_tests.test_end_time')
            ->where('new_book_tests.status',2)
            ->whereNull('new_book_test_users.test_id')
            ->select('new_book_tests.*')
            ->get()
            ->pluck('id')
            ->toArray();
        if(!$new_book_test_ids){return;}

        foreach ($new_book_test_ids as $new_book_test_id){
            $this->getNewBookTestUserData($new_book_test_id);
        }
    }

    /**
     * 获取新书测试用户数据
     * @param $new_book_test_id
     */
    public static function getNewBookTestUserData($new_book_test_id){
        if(!$new_book_test_id)return [];

        $key ='NewBookTestUserDetail:'.$new_book_test_id;
        $count = Redis::ZCARD($key);
        $member_list = Redis::ZRANGE($key,0,$count);
        $insert_data = array();

        foreach ($member_list as $index=>$member){
            $data = array();
            $score = Redis::ZSCORE($key,$member);
            $data['uid'] = $member;
            $data['push_time'] = date('Y-m-d H:i:s',$score);
            $data['test_id'] = $new_book_test_id;
            $insert_data[] = $data;
            if(count($insert_data)>=1000){

                DB::table('new_book_test_users')->insert($insert_data);
                $insert_data = array();
            }
        }
        DB::table('new_book_test_users')->insert($insert_data);
    }
}

