<?php

namespace App\Console\Commands\Statistic;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class OptimizerMonthCharge extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Statistic:OptimizerMonthCharge {--month= : 统计月份} {--user_ids= : 投手uids}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '优化师充值月统计';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $month = $this->option('month') ?? date('Y-m', strtotime('last month'));
        $monthStart = $month. '-01';
        $montEnd = date_sub(date_add(date_create($monthStart),
            date_interval_create_from_date_string('1 month')),
            date_interval_create_from_date_string('1 day'))->format('Y-m-d');

        $user_ids = $this->option('user_ids');
        if($user_ids) {
            $userIds = explode(',',  $user_ids);
        } else {
            $userIds = DB::table('user_has_roles')
                ->where(['role_id' => 2])
                ->select('user_id')
                ->get()->pluck('user_id');
        }

        $now = date('Y-m-d H:i:s');
        foreach ($userIds as $userId) {
            $puser_id = DB::table('users')->where('id', $userId)->value('pid');
            $result = DB::table('tj_optimizer_day_charge')
                ->whereBetween('day_at', [$monthStart, $montEnd])
                ->where('user_id', $userId)
                ->select(
                    'miniprogram_id',
                    DB::raw("sum(pay_money) as pay_money"),
                    DB::raw("sum(common_pay_count) as common_pay_count"),
                    DB::raw("sum(common_unpay_count) as common_unpay_count"),
                    DB::raw("sum(vip_unpay_count) as vip_unpay_count"),
                    DB::raw("sum(vip_pay_count) as vip_pay_count"),
                )->groupBy('miniprogram_id')
                ->get();
            $insertData = [];
            foreach ($result as $item) {
                $info['pay_money'] = $item->pay_money ?? 0;
                $info['common_pay_count'] = $item->common_pay_count ?? 0;
                $info['common_unpay_count'] = $item->common_unpay_count ?? 0;
                $info['vip_unpay_count'] = $item->vip_unpay_count ?? 0;
                $info['vip_pay_count'] = $item->vip_pay_count ?? 0;
                $info['miniprogram_id'] = $item->miniprogram_id ?? 0;
                $info['created_at'] = $info['updated_at'] = $now;
                $info['month_at'] = $month;
                $info['user_id'] = $userId;
                $info['puser_id'] = $puser_id;
                $insertData[] = $info;
            }

            DB::table('tj_optimizer_month_charge')
                ->insert($insertData);
        }
    }
}
