<?php

namespace App\Console\Commands\Statistic;

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

class CompanyMonthCharge extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Statistic:CompanyMonthCharge {--month= : 统计月份} {--company_uids= : 公司管理员ids}';

    /**
     * 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');

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

        $now = date('Y-m-d H:i:s');
        foreach ($companyUids as $companyUid) {
            $info = DB::table('tj_company_day_charge')
                ->whereBetween('day_at', [$monthStart, $montEnd])
                ->where(['company_uid' => $companyUid])
                ->select(
                    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"),
                )->first();
            DB::table('tj_company_month_charge')
                ->insert([
                    'month_at' => $month,
                    'pay_money' => $info->pay_money ?? 0,
                    'common_pay_count' => $info->common_pay_count ?? 0,
                    'common_unpay_count' => $info->common_unpay_count ?? 0,
                    'vip_pay_count' => $info->vip_pay_count ?? 0,
                    'vip_unpay_count' => $info->vip_unpay_count ?? 0,
                    'company_uid' => $companyUid,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
        }
    }
}
