<?php
/**
 * Created by PhpStorm.
 * User: songdb
 * Date: 2017/12/26
 * Time: 下午5:26
 */

namespace App\Console\Commands\BookGiftStats;

use DB;
use App\Modules\BookGifts\Services\BookGiftsStatsByGiftService;
use Log;
use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '送礼记录数据按礼物统计';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        print_r("======送礼记录数据按礼物统计 【任务执行开始】=====".date("y-m-d H:i:s"."\n"));

        Log::info("======送礼记录数据按礼物统计 【任务执行开始】=====".date("y-m-d H:i:s"."\n"));

        $start = date('Y-m-d 00:00:00',strtotime('-1 day'));
        $end   = date('Y-m-d 23:59:59',strtotime('-1 day'));
        \Log::info('start:'.$start);
        \Log::info('end:'.$end);
        $res = DB::select("SELECT gift_id,book_gifts.name_desc,count(book_gifts_send.id) as send_times,COUNT(DISTINCT book_gifts_send.uid) as send_user_num,sum(book_gifts_send.cost) as cost_sum
 FROM book_gifts_send
 LEFT JOIN book_gifts ON book_gifts.id=book_gifts_send.gift_id
 WHERE book_gifts_send.created_at BETWEEN '{$start}' AND '{$end}'
 GROUP BY gift_id");
        foreach ($res as $item){
            try{
                $data_to_add = array(
                    'date'=>date('Y-m-d'),
                    'gift_id'=>$item->gift_id,
                    'gift_name'=>$item->name_desc,
                    'gift_send_times'=>$item->send_times,
                    'gift_send_user_num'=>$item->send_user_num,
                    'gift_send_cost'=>$item->cost_sum,
                );

                BookGiftsStatsByGiftService::addGiftStats($data_to_add);
            }catch (\Exception $e){
                \Log::error('add Book Gifts Stats Failed2:'.$e->getMessage());
            }
        }

        Log::info("======送礼记录数据礼物统计 【任务执行结束】=====".date("y-m-d H:i:s"."\n"));
        print_r("======送礼记录数据按礼物统计 【任务执行结束】=====".date("y-m-d H:i:s"."\n"));
    }
}