<?php

namespace App\Console\Commands;

use App\Modules\Statistic\Services\WapVisitStatService;
use DB;
use Illuminate\Console\Command;
use Redis;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {

        /*$start_date = '2016-08-29';
        $end_date =  date("Y-m-d", strtotime("-1 day"));
        $end_timestamp = strtotime($end_date);
        $start_timestamp = strtotime($start_date);

        // 计算日期段内有多少天
        $days = ($end_timestamp - $start_timestamp) / 86400 + 1;
        for ($i = 0; $i < $days; $i++) {
            $date = date('Y-m-d', $start_timestamp + (86400 * $i));
            $this->getReadVisitUvInfo($date);
        }

        /*$yesterday = date("Y-m-d", strtotime("-1 day"));
        $this->getReadVisitUvInfo($yesterday);*/

        $yesterday = date("Y-m-d", strtotime("-1 day"));
        $this->getReadVisitUvInfo($yesterday);
    }

    function getReadVisitUvInfo($date)
    {
        $channels = Redis::smembers(sprintf('recordReaderUvAndPv:date:%s', $date));
        if ($channels) {
            foreach ($channels as $channel) {
                $data = WapVisitStatService::getReaderUvAndPv($channel, $date);
                if ($data) {
                    $uv = $data['uv'];
                    $pv = $data['pv'];
                    $distribution_channel_id = $channel;
                    $created_at = date("Y-m-d H:i:s");
                    $updated_at = date("Y-m-d H:i:s");
                    $data = compact('date', 'uv', 'pv', 'created_at', 'updated_at', 'distribution_channel_id');
                    DB::table('channel_reader_visit_stats')->insert($data);
                }
            }
        }
        WapVisitStatService::deleteReaderUvAndPvRedisKey($date);
    }
}