<?php

namespace App\Console\Commands\Statistic;

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

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '投放公司日充值';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $date = $this->option('date') ?? date('Y-m-d', strtotime('yesterday'));
        $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('orders')
                ->whereBetween('created_at', [$date, $date. ' 23:59:59'])
                ->where('puser_id', $companyUid)
                ->select(
                    DB::raw("sum(if(status = 'unpaid', 0, price)) as pay_money"),
                    DB::raw("sum(if(status <> 'unpaid' and order_type in ('coin', 'first_coin'), 1, 0)) as common_pay_count"),
                    DB::raw("sum(if(status = 'unpaid' and order_type in ('coin', 'first_coin'), 1, 0)) as common_unpay_count"),
                    DB::raw("sum(if(status <> 'unpaid' and order_type not in ('coin', 'first_coin'), 1, 0)) as vip_pay_count"),
                    DB::raw("sum(if(status = 'unpaid' and order_type not in ('coin', 'first_coin'), 1, 0)) as vip_unpay_count"),
                )->first();
            DB::table('tj_company_day_charge')
                ->insert([
                    'day_at' => $date,
                    '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,
                ]);

        }

    }
}
