<?php

namespace App\Console\Commands;

use App\Jobs\SendTemplateNotice;
use App\Models\Collaborator;
use App\Models\FatLog;
use App\Models\NewFatLog;
use App\Models\Restaurant;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '去重体脂秤信息';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('去重体脂秤信息');
        //接收参数
        NewFatLog::groupBy(["user_id", "created_at", "type"])->having("count", ">", 1)->selectRaw("user_id, created_at, type, count(*) as count")->orderBy("count", "desc")->chunk(100,function($logs) {
            $count = $logs->count();
            $this->info("总数:".$count);
            foreach($logs as $log) {
                $first_log = NewFatLog::where("user_id", $log->user_id)->where("type", $log->type)->where("created_at", $log->created_at->toDateTimeString())->first();
                if ($first_log) {
                    NewFatLog::where("id", "!=", $first_log->id)->where("user_id", $log->user_id)->where("type", $log->type)->where("created_at", $log->created_at->toDateTimeString())->delete();
                    $count--;
                }
                $this->info("剩余:".$count);
            }
        });
        return Command::SUCCESS;
    }
}
