<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;

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

    /**
     * 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(){
        $sql = "INSERT INTO user_month_day_stats(`day`,type,exposure_num,increment_user_num,cancel_user_num,created_at,updated_at)
select 
`day`,
'%s' as type,
count(distinct uid) as exposure_num,
(select count(*) from user_month_order 
where date(user_month_order.created_at) = user_month_visit_record.day and user_month_order.uid in (
SELECT  uid FROM  user_month_sign where date(user_month_sign.created_at) = date(user_month_order.created_at ) and type='%s'
) and type='%s' ) as increment_user_num,
(select count(*) from user_month_order 
where date(user_month_order.created_at) = user_month_visit_record.day and user_month_order.uid in (
SELECT  uid FROM  user_month_sign where date(user_month_sign.created_at) = date(user_month_order.created_at) and  type='%s'
and change_type = 'DELETE'
)and type='%s' ) as cancel_user_num,
NOW(),NOW()

 from user_month_visit_record where type='%s' and created_at >= '%s' and created_at < '%s'  
 group by `day`
";

        $month_sql = sprintf($sql,'MONTH','MONTH','MONTH','MONTH','MONTH','MONTH',date('Y-m-d',time()-86400),date('Y-m-d'));
        $month_old = DB::table('user_month_day_stats')->where('day',date('Y-m-d',time()-86400))->where('type','MONTH')->first();
        if(!$month_old){
            DB::insert($month_sql);
        }
        $week_sql = sprintf($sql,'WEEK','WEEK','WEEK','WEEK','WEEK','WEEK',date('Y-m-d',time()-86400),date('Y-m-d'));
        $week_old = DB::table('user_month_day_stats')->where('day',date('Y-m-d',time()-86400))->where('type','WEEK')->first();
        if(!$week_old){
            DB::insert($week_sql);
        }
    }
}
