<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Redis;
use DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->saveDB();
    }

    private function saveDB(){
        $result = $this->compactData();
        if(!$result){
            return ;
        }
        foreach ($result as $key=>$v){
            $table = sprintf('record_records%s',$key);
            DB::connection('read_record_mysql')->table($table)->insert($v);
        }
    }

    private function getRecord(){
        $length = Redis::Llen('ReadRecordStats');
        if(!$length) return [];
        $count = ceil($length/200);
        $result = [];
        for ($i=0;$i <$count;$i++){
            $start = $i*200;
            $end = $start+199;
            $result[] = Redis::Lrange('ReadRecordStats',$start,$end);
        }
        Redis::del('ReadRecordStats');
        return $result;
    }

    private function compactData(){
        $data = $this->getRecord();
        if(!$data){
            return [];
        }
        $result = [];
        foreach ($data as $item){
            foreach ($item  as $v){
                $record = json_decode($v,1);
                $table = $record['uid']%2048;
                $result[$table][] =  $record;
            }
        }

        return  $result;
    }
}
