<?php

namespace App\Http\Controllers\Business;

use App\Exports\OrderBlankExport;
use App\Http\Controllers\Controller;
use App\Models\BusinessOrder;
use App\Models\Shop;
use App\Utils\DateTimeUtils;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Resources\BusinessOrderResource;
use Maatwebsite\Excel\Facades\Excel;

class BusinessOrderController extends Controller
{
    public function index(Request $request)
    {
        $businessOrders = BusinessOrder::query()
            ->where('shop_id', '<>', 8)
            ->with([
                'shop:id,name',
                'items:id,business_order_id,goods_name,goods_number,external_sku_id'
            ])
            ->orderByDesc('confirm_at')
            ->filter()
            ->paginate($request->get('per_page'));

        return BusinessOrderResource::collection($businessOrders);
    }

    public function exportOrderBlank(Request $request)
    {
        $shopId = $request->get('shop_id');
        $startNo = $request->get('start_no');
        $endNo = $request->get('end_no');
        $isSupplier = $request->get('is_supplier');
        $field = 'participate_no';
        if ($isSupplier) {
            $field = 'supply_participate_no';
        }
        $startTime = BusinessOrder::query()
            ->where('shop_id', $shopId)
            ->where('is_supplier', $isSupplier)
            ->where($field, $startNo)
            ->orderByDesc('id')
            ->value('confirm_at');
        if (empty($startTime)) {
            exit('开始跟团号订单未查询到或正在同步中,请稍后再次获取');
        }
        $startTime = DateTimeUtils::getMicroTime($startTime);
        $endTime = BusinessOrder::query()
            ->where('shop_id', $shopId)
            ->where('is_supplier', $isSupplier)
            ->where($field, $endNo)
            ->orderByDesc('id')
            ->value('confirm_at');
        if (empty($endTime)) {
            exit('结束跟团号订单未查询到或正在同步中,请稍后再次获取');
        }
        $endTime = DateTimeUtils::getMicroTime($endTime);
        if ($startTime > $endTime) {
            exit('开始跟团号订单 成交时间 大于 结束跟团号订单时间,请查验后再试!');
        }
        $orders = BusinessOrder::query()
            ->with([
                'items:id,business_order_id,external_sku_id,goods_number,goods_name,already_cancel_number',
                'items.goodsSkuLocation:id,external_sku_id,location,goods_name'
            ])
            ->where('shop_id', $shopId)
            ->where('confirm_at', '>=', $startTime)
            ->where('confirm_at', '<=', $endTime)
            ->where('after_sales_status', 0)
            ->where('cancel_status', 0)
            ->where('is_supplier', $isSupplier)
            ->orderByDesc('confirm_at')
            ->get(['id', $field]);
        $distribution = [];
        $no = [];
        foreach ($orders as $key => $order) {
            $index = $key + 1;
            $no[] = 'P' . $index . '(' . $order->$field . ')';
            foreach ($order->items as $item) {
                $item = $item->toArray();
                $num = $item['goods_number'] - $item['already_cancel_number'];
                if (empty($item['external_sku_id']) || empty($num)) {
                    continue;
                }
                $local = $item['goods_sku_location'] ? $item['goods_sku_location']['location'] : '无';
                $index = $key + 1;
                $index = "P{$index}*{$num}";
                [$goodsCode, $skuCode] = explode('_', $item['external_sku_id']);
                if (isset($distribution[$item['external_sku_id']])) {
                    $distribution[$item['external_sku_id']]['p'][] = $index;
                    $distribution[$item['external_sku_id']]['num'] += $num;
                } else {
                    $distribution[$item['external_sku_id']] = [
                        'p' => [$index],
                        'local' => $local,
                        'num' => $num,
                        'goods_name' => $item['goods_name'],
                        'goods_code' => $goodsCode,
                        'sku_code' => $skuCode,
                    ];
                }
            }
        }
        $shopName = Shop::query()->where('id', $shopId)->value('name');
        ob_end_clean();

        return Excel::download(new OrderBlankExport($shopName, $no, $distribution), $shopName . date('Y-m-d H:i:s') . '.xlsx');
    }

    public function groupActivity(Request $request, $shopId)
    {
        $todayTime = Carbon::today()->timestamp;
        $todayTime = DateTimeUtils::getMicroTime($todayTime);

        return BusinessOrder::query()
            ->where('shop_id', $shopId)
            ->where('confirm_at', '>=', $todayTime)
            ->groupBy(['activity_no', 'activity_title'])
            ->get(['activity_title', 'activity_no'])
            ->toArray();
    }
}
