<?php

namespace App\Console\Commands\Temp;

use Log;
use Illuminate\Console\Command;
use DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '书币大于500最近签到';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        /**
         * CREATE TABLE `temp_user_sign` (
        `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
        `uid` int(11) DEFAULT NULL,
        `distribution_channel_id` int(11) DEFAULT NULL,
        `balance` decimal(11,2) DEFAULT NULL,
        `latest_sign_time` datetime DEFAULT NULL,
        PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
         *
         *
         */
        print_r("======书币大于500最近签到生成 【任务执行开始】=====".date("y-m-d H:i:s"."\n"));
        Log::info("======书币大于500最近签到生成 【任务执行开始】=====".date("y-m-d H:i:s"."\n"));

        $_start = new \DateTime('2017-12-12');
        $_end = new \DateTime('2018-02-18');

        foreach (new \DatePeriod($_start, new \DateInterval('P1D'), $_end) as $d)
        {

            $date = $d->format('Y-m-d');
            $start = $date;
            $end = date('Y-m-d', strtotime($date) + 86400);

            $offset = 0;
            $limit = 1000;
            $data = [];

            while (true) {

                print_r("select id,distribution_channel_id,balance from users where balance > 500 limit $offset,$limit" . "\n");
                $users = DB::select("select id,distribution_channel_id,balance from users where balance > 500 limit $offset,$limit");
                print_r("users_count:".count($users));
                if (count($users) == 0) break;

                foreach ($users as $user) {

                    $sign = DB::table('user_sign')->where('uid',$user->id)->orderBy('id','desc')->first();
                    $data[] = [
                        'uid'=>$user->id,
                        'distribution_channel_id'=>$user->distribution_channel_id,
                        'balance'=>$user->balance,
                        'latest_sign_time'=>$sign ? $sign->created_at : null
                    ];
                }

                $offset = $offset + $limit;
                DB::table('temp_user_sign')->insert($data);
                $data = [];
            }

            Log::info("======书币大于500最近签到生成 【任务执行结束】=====" . date("y-m-d H:i:s" . "\n"));
            print_r("======书币大于500最近签到生成 【任务执行结束】=====" . date("y-m-d H:i:s" . "\n"));


        }
    }
}