<?php

namespace App\Console\Commands\ContentManage;

use Dotenv\Store\StoreBuilder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SaveBookSettlementMode extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ContentManage:SaveBookSettlementMode {--bid= : 书籍id}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '保存书籍的结算模式,每天执行一次';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $maxBid = 0;
        $bid = $this->option('bid');
        while (true) {
            $books = DB::table('books')
                ->when($bid, function ($query, $bid) {
                    return $query->where(['id' => $bid]);
                })
                ->select('id', 'settlement_type', 'bottomline')
                ->orderBy('id', 'asc')
                ->where('id', '>', $maxBid)
                ->limit(300)
                ->get();
            $maxBid = $books->last()->id ?? 0;
            if(0 == $maxBid) {
                break;
            }
            $this->dealBooks($books);
        }
    }

    private function dealBooks($books) {
        $nowDate = date('Y-m-d');
        $nowTime = date('Y-m-d H:i:s');
        $bids = $books->pluck('id')->unique();
        $bookLasteSettlementModeMap = $this->bookLasteSettlementModeMap($bids);
        foreach ($books as $book) {
            if($bookLasteSettlementModeMap->has($book->id)) {
                $bookLasteSettlementMode = $bookLasteSettlementModeMap->get($book->id);
                if($book->settlement_type == $bookLasteSettlementMode['settlement_mode'] &&
                    $book->bottomline == $bookLasteSettlementMode['bottomline']) {
                    continue;
                }
            }
            DB::table('book_settlement_mode_history')
                ->insert([
                    'bid' => $book->id,
                    'effective_date' => $nowDate,
                    'settlement_mode' => $book->settlement_type,
                    'bottomline' => $book->bottomline,
                    'change_reason' => 'manual',
                    'created_at' => $nowTime,
                    'updated_at' => $nowTime
                ]);
        }
    }

    private function bookLasteSettlementModeMap($bids) {
        $map = collect();
        $history = DB::table('book_settlement_mode_history')
            ->whereIn('bid', $bids)
            ->where([
                'is_enabled' => 1, 'change_reason' => 'manual'
            ])->select('id', 'settlement_mode', 'bottomline', 'effective_date', 'bid')
            ->orderBy('id', 'desc')
            ->get();
        foreach ($history as $h) {
            if($map->has($h->bid)) {
                $settlementMode = $map->get($h->bid);
                if($settlementMode['effective_date'] >= $h->effective_date) {
                    continue;
                }
            }
            $map->put($h->bid, [
                'effective_date' => $h->effective_date,
                'settlement_mode' => $h->settlement_mode,
                'bottomline' => $h->bottomline
            ]);
        }
        return $map;
    }
}
