<?php
namespace App\Console\Subscribe;

use App\Cache\StatisticCache;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class BookOrderByDayCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Subscribe:BookOrderByDay {--day=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'redis临时保存的订阅记录按天汇总写入数据库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $day = $this->option('day');
        if (!$day) $day = date('Y-m-d', strtotime('-1 day'));
        $this->saveDB($day);
    }

    private function saveDB($day)
    {
        dLog('command_logs')->info('~~~~~~~~~~~~~~~~~~~~~~~~~~开始统计redis临时保存的订阅记录~~~~~~~~~~~~~~~~~~~~~~~~~~');
        $executeStart = microtime(true);
        // 获取数据
        $data = $this->getRecord($day);

        $fields = ['bid', 'day', 'balance', 'charge_balance', 'reward_balance', 'is_chapter', 'count'];

        // 组装数据
        $insertData = [];
        foreach ($data as $item) {
            foreach ($item as $v) {
                $arr = json_decode($v, true);
                if (!is_array($arr) || empty($arr)) {
                    continue;
                }

                // 参数不正确就跳过
                foreach ($fields as $field) {
                    if (!isset($arr[$field])) continue(2);
                }
                if (isset($arr['uid'])) unset($arr['uid']);
                $arr['created_at'] = $arr['updated_at'] = date('Y-m-d H:i:s');

                // 不是指定日期的数据则跳过
                if ($arr['day'] != $day) continue;

                // 按书籍id累加
                if (isset($insertData[$arr['bid']])) {
                    $insertData[$arr['bid']]['balance'] += $arr['balance'];
                    $insertData[$arr['bid']]['charge_balance'] += $arr['charge_balance'];
                    $insertData[$arr['bid']]['reward_balance'] += $arr['reward_balance'];
                    $insertData[$arr['bid']]['count'] += $arr['count'];
                }else {
                    $insertData[$arr['bid']] = $arr;
                }

            }
        }

        if ($insertData) {
            DB::table('book_order_by_day')->where('day', $day)->delete();
            DB::table('book_order_by_day')->insert($insertData);
        }

        $executeEnd = microtime(true);
        dLog('command_logs')->info('脚本运行时间: ', ['execute_time'=>round(($executeEnd - $executeStart), 6).'s']);
        dLog('command_logs')->info('~~~~~~~~~~~~~~~~~~~~~~~~~~结束统计redis临时保存的订阅记录~~~~~~~~~~~~~~~~~~~~~~~~~~');
    }

    private function getRecord($day)
    {
        if ($day) $day = date('Ymd', strtotime($day));
        else $day = date('Ymd', strtotime('-1 day'));
        $length = StatisticCache::getSubscribeCount($day);
        if (!$length) return [];
        $count = ceil($length / 1000);
        $result = [];
        for ($i = 0; $i < $count; $i++) {
            $start = $i * 1000;
            $end = $start + 999;
            $result[] = StatisticCache::getSubscribe($day, $start, $end);
        }
        return $result;
    }
}
