<?php

namespace App\Console\Commands;

use App\Models\BusinessOrderItem;
use App\Models\DailyReport;
use App\Models\GoodsSku;
use Carbon\Carbon;
use Illuminate\Console\Command;

class GoodsSkuDailyReport extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'daily:report:goods_sku {date?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '每日商品数据记录';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $date = $this->argument('date');
        if (is_null($date)) {
            $date = Carbon::yesterday()->format('Y-m-d');
        }
        $startDateTime = Carbon::parse($date)->startOfDay()->toDateTimeString();
        $endDateTime = Carbon::parse($date)->endOfDay()->toDateTimeString();

        $orderItems = BusinessOrderItem::query()
            ->select(['shop_id', 'already_cancel_number', 'external_sku_id', 'goods_amount', 'goods_cost_price', 'goods_number', 'goods_price'])
            ->where('external_sku_id', '<>', '')
            ->where('created_at', '>=', $startDateTime)
            ->where('created_at', '<=', $endDateTime)
            ->get();
        if ($orderItems->isEmpty()) {
            return;
        }

        $externalSkuIds = array_unique(array_column($orderItems->toArray(), 'external_sku_id'));
        $goodsSkus = GoodsSku::query()
            ->select(['id', 'goods_id', 'cost', 'external_sku_id'])
            ->with([
                'goods:id,type_id,brand_id'
            ])
            ->where('is_combination', 0)
            ->whereIn('external_sku_id', $externalSkuIds)
            ->get()
            ->pluck(null, 'external_sku_id')
            ->toArray();
        if (empty($goodsSkus)) {
            return;
        }

        $data = [];
        foreach ($orderItems as $orderItem) {
            if (!isset($goodsSkus[$orderItem->external_sku_id])) {
                continue;
            }
            if (!isset($data[$orderItem->external_sku_id])) {
                $data[$orderItem->external_sku_id] = [
                    'goods_id' => $goodsSkus[$orderItem->external_sku_id]['goods']['id'],
                    'type_id' => $goodsSkus[$orderItem->external_sku_id]['goods']['type_id'],
                    'brand_id' => $goodsSkus[$orderItem->external_sku_id]['goods']['brand_id'],
                    'goods_sku_id' => $goodsSkus[$orderItem->external_sku_id]['id'],
                    'cost' => $goodsSkus[$orderItem->external_sku_id]['cost'],
                    'total_goods_price' => 0,
                    'total_goods_cost_price' => 0,
                    'total_goods_amount' => 0,
                    'total_goods_number' => 0,
                    'total_cancel_number' => 0,
                    'shop_data' => [],
                ];
            }

            $data[$orderItem->external_sku_id]['total_goods_price'] += $orderItem->goods_price;
            $data[$orderItem->external_sku_id]['total_goods_cost_price'] += $orderItem->goods_cost_price;
            $data[$orderItem->external_sku_id]['total_goods_amount'] += $orderItem->goods_amount;
            $data[$orderItem->external_sku_id]['total_goods_number'] += $orderItem->goods_number;
            $data[$orderItem->external_sku_id]['total_cancel_number'] += $orderItem->already_cancel_number;

            if (!isset($data[$orderItem->external_sku_id]['shop_data'][$orderItem->shop_id])) {
                $data[$orderItem->external_sku_id]['shop_data'][$orderItem->shop_id] = [
                    'total_goods_price' => 0,
                    'total_goods_cost_price' => 0,
                    'total_goods_amount' => 0,
                    'total_goods_number' => 0,
                    'total_cancel_number' => 0,
                ];
            }

            $data[$orderItem->external_sku_id]['shop_data'][$orderItem->shop_id]['total_goods_price'] += $orderItem->goods_price;
            $data[$orderItem->external_sku_id]['shop_data'][$orderItem->shop_id]['total_goods_cost_price'] += $orderItem->goods_cost_price;
            $data[$orderItem->external_sku_id]['shop_data'][$orderItem->shop_id]['total_goods_amount'] += $orderItem->goods_amount;
            $data[$orderItem->external_sku_id]['shop_data'][$orderItem->shop_id]['total_goods_number'] += $orderItem->goods_number;
            $data[$orderItem->external_sku_id]['shop_data'][$orderItem->shop_id]['total_cancel_number'] += $orderItem->already_cancel_number;
        }

        foreach ($data as $externalSkuId => $datum) {
            DailyReport::query()->firstOrCreate([
                'date' => $date,
                'external_sku_id' => $externalSkuId
            ], $datum);
        }
    }
}
