<?php

namespace App\Console\Commands\ContentManage;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Modules\Common\Support\Trace\TraceContext;
use Modules\ContentManage\Services\CpManage\BookSettlement;

class CpSubscribeMonthStatisticData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ContentManage:CpSubscribeMonthStatisticData {--month= : 被统计的月份}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'cp订阅数据月统计';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $month = $this->option('month');
        if(!$month){
            $this->error('month necessary');
        }

        $cpNames = DB::table('cps')
            ->select('cp_name')
            ->get()->pluck('cp_name');

        $datas = DB::table('cp_subscribe_statistic_data')
            ->where([
                'month' => $month
            ])->select(
                DB::raw('count(distinct bid) as book_num'),
                'cp_name'
            )->groupBy('cp_name')
            ->get()->keyBy('cp_name');

        $insertDatas = [];
        $now = date('Y-m-d H:i:s');
        foreach ($cpNames as $cpName) {
            $bookFinalAmounts = [];
            $bids = DB::table('cp_subscribe_statistic_data')
                ->where(['cp_name' => $cpName, 'month' => $month])
                ->distinct()
                ->select('bid')
                ->get()->pluck('bid');
            $finalAmount = 0;
            DB::table('cp_book_month_final_amounts')
                ->where(['cp_name' => $cpName, 'month' => $month])
                ->update(['is_enabled' => 0, 'updated_at' => $now]);
            foreach ($bids as $bid) {
                $service = new BookSettlement($bid, $month);
                $service->traceContext = TraceContext::newFromParent(app(TraceContext::class)->getTraceInfo());
                $bookFinalAmountDetails = $service->detail();
                $monthFinalAmount = array_sum($bookFinalAmountDetails);
                $finalAmount += $monthFinalAmount;
                $bookFinalAmounts[] = [
                    'bid' => $bid,
                    'cp_name' => $cpName,
                    'month' => $month,
                    'final_amount' => $monthFinalAmount,
                    'created_at' => $now,
                    'updated_at' => $now,
                ];
            }

            DB::table('cp_book_month_final_amounts')
                ->insert($bookFinalAmounts);

            $insertDatas[] = [
                'book_num' => $datas->get($cpName)->book_num ?? 0, 'final_amount' => $finalAmount,
                'cp_name' => $cpName, 'month' => $month, 'created_at' => $now, 'updated_at' => $now,
            ];
        }

        DB::table('cp_subscribe_month_statistic_data')
            ->insert($insertDatas);
    }

}