<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2020/9/16
 * Time: 15:31
 */

namespace App\Console\Commands\User;

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

class UserLastChapterOrder extends Command
{
    const USER_LAST_CHAPTER_ORDER = 'userLastChapterOrder';
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'User:UserLastChapterOrder';

    /**
     * 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(){
        $this->start();
    }

    private function start(){
        $record = Redis::hgetAll(self::USER_LAST_CHAPTER_ORDER);
        if(!$record) return ;
        Redis::del(self::USER_LAST_CHAPTER_ORDER);
        $save_data = [];
        $temp = 1;
        foreach ($record as $uid=>$bid){
            $exists = DB::table('user_last_chapter_order')->where('uid',$uid)->select('id','bid')->first();
            if($exists){
                if($exists->bid == $bid)continue;
                DB::table('user_last_chapter_order')->where('uid',$uid)->update([
                    'bid'=>$bid,'updated_at'=>date('Y-m-d H:i:s')
                ]);
            }else{
                $save_data[] = ['uid'=>$uid,'bid'=>$bid,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
                if($temp++ % 100 == 0){
                    DB::table('user_last_chapter_order')->insert($save_data);
                    $save_data = [];
                }
            }
        }
        if($save_data) {
            DB::table('user_last_chapter_order')->insert($save_data);
        }
    }
}